?
對稱式加密的實現
?? 加密可提高終端和網路通訊的物理安全,有三種方法加密傳輸資料
*?連結加密:在網路節點間加密,在節點間傳輸加密,傳送到節點後解密,不同節點對間用不同密碼.?
*?節點加密:與連結加密類似,不同的只是當資料在節點間傳送時,不用明碼格式傳送,而是用特殊??的加密硬體進行解密和重加密,這種專用硬體通常旋轉在安全保險箱中.?
*?首尾加密:對進入網路的資料加密,然後待資料從網路傳送出後再進行解密.網路本身並不會知?道正在傳送的資料是加密資料.這一方法的優點是,網路上的每個使用者(通常是每個機器的一個??使用者)可有不同的加密關鍵詞,並且網路本身不需增添任何專門的加密裝置.缺點是每個系統必?須有一個加密裝置和相應的軟體(管理加密關鍵詞)或者每個系統必須自己完成加密工作(當數?據傳輸率是按兆位/秒的單位計算時,加密任務的計算量是很大的)
? 本文採用首尾加密,代碼如下:
//從密鑰檔案中讀密鑰
?? 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=Cipher.getInstance("DES");
//設定加密模式
???? cipher.init(Cipher.ENCRYPT_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
{
//輸入資料流
BufferedInputStream in=new BufferedInputStream(new FileInputStream(file));
//輸出資料流
????? CipherOutputStream out=new CipherOutputStream(new BufferedOutputStream(
??????????? new FileOutputStream("c://安全檔案//檔案//"+filename+".yhb")),cipher);
?? ???int i;
??????? do{
??????? i=in.read();
??????? if(i!=-1) out.write(i);
???????? }while(i!=-1);
????? in.close();
????? out.close();
????? }
????? catch(Exception ey5)
????? {
????? System.out.println("Error when encrypt the file");
????? System.exit(0);
????? }
?
作者又名HongSoft,研究領域:1)基於工作流程的BPM系統研究2)基於JAVA的資訊安全技術.歡迎和大家討論JAVA相關各方面問題 hongbosoftware@163.com