BouncyCastle JCE實踐(五)

對稱解密的實現

對稱加密/解密算法在電子商務交易過程中存在幾個問題:

(1)?????? 要求提供一條安全的渠道使通訊雙方在首次通訊時協商一個共同的密鑰。直接的面對面協商可能是不現實而且難於實施的,所以雙方可能需要藉助於郵件和電話等其它相對不夠安全的手段來進行協商;

(2)?????? 密鑰的數目難於管理。因爲對於每一個合作者都需要使用不同的密鑰,很難適應開放社會中大量的信息交流;

(3)?????? 對稱加密算法一般不能提供信息完整性的鑑別。它無法驗證發送者和接受者的身份;

對稱密鑰的管理和分發工作是一件具有潛在危險的和煩瑣的過程。對稱加密是基於共同保守祕密來實現的,採用對稱加密技術的貿易雙方必須保證採用的是相同的密鑰,保證彼此密鑰的交換是安全可靠的,同時還要設定防止密鑰泄密和更改密鑰的程序。

對稱解密的代碼實現如下:

//從密鑰文件中讀密鑰

?? SecretKey key=null;

?? try

?? {ObjectInputStream keyFile=new ObjectInputStream(

???? new FileInputStream("c://安全文件//"+misClass.username+"//對稱//對稱密鑰//yhb.des"));

??? key=(SecretKey)keyFile.readObject();

??? keyFile.close();

??? }

??? catch(FileNotFoundException ey1)

??? {

??? System.out.println("Error when read keyFile");

??? System.exit(0);

??? }

??? catch(Exception ey2)

??? {

??? System.out.println("error when read the keyFile");

??? System.exit(0);

??? }

?? //key產生Cipher

??? Cipher cipher=null;

??? try

{

//設置算法,應該與加密時的設置一樣

cipher=Cipher.getInstance("DES");

//設置解密模式

???? cipher.init(Cipher.DECRYPT_MODE,key);

???? }catch(Exception ey3)

???? {

???? System.out.println("Error when create the cipher");

???? System.exit(0);

???? }

???? //從對話框中取得要解密的文件並解密

???? File file=new File(dirstring,string1);

???? String filename=file.getName();

??? try

{

//輸出流,請注意文件名稱的獲取

BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(

????????? "c://安全文件//文件//"+filename.substring(0,filename.length()-4)));

???? //輸入流

????? CipherInputStream in=new CipherInputStream(new BufferedInputStream(

??????????? new FileInputStream(file)),cipher);

??? int thebyte=0;

??? while((thebyte=in.read())!=-1)

??? {

??? out.write(thebyte);

??? }

????? in.close();

????? out.close();

????? }

????? catch(Exception ey5)

????? {

????? System.out.println("Error when encrypt the file");

????? System.exit(0);

????? }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章