2012-12-11 63 views
3

我必須使用帶有密鑰的DES在java中加密/解密純文本。我在IBM有一個很好的教程,可以找到here。這個例子的問題在於它在程序本身中生成密鑰。現在,如果我加密一個字符串(例如密碼)並存儲在數據庫中,那麼我將無法解密它,因爲我不知道密鑰。使用DES中的私鑰在使用DES時不會自動生成密鑰

下面是IBM

import java.security.*; 
import javax.crypto.*; 
// 
// encrypt and decrypt using the DES private key algorithm 
public class PrivateExample { 

    public static void main (String[] args) throws Exception { 
    // 
    // check args and get plaintext 
    if (args.length !=1) { 
     System.err.println("Usage: java PrivateExample text"); 
     System.exit(1); 
    } 
    byte[] plainText = args[0].getBytes("UTF8"); 
    // 
    // get a DES private key 
    System.out.println("\nStart generating DES key"); 
    KeyGenerator keyGen = KeyGenerator.getInstance("DES"); 
    keyGen.init(56); 
    Key key = keyGen.generateKey(); 
    System.out.println("Finish generating DES key"); 
// 
// get a DES cipher object and print the provider 
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); 
System.out.println("\n" + cipher.getProvider().getInfo()); 
// 
// encrypt using the key and the plaintext 
System.out.println("\nStart encryption"); 
cipher.init(Cipher.ENCRYPT_MODE, key); 
byte[] cipherText = cipher.doFinal(plainText); 
System.out.println("Finish encryption: "); 
System.out.println(new String(cipherText, "UTF8")); 

// 
// decrypt the ciphertext using the same key 
System.out.println("\nStart decryption"); 
cipher.init(Cipher.DECRYPT_MODE, key); 
byte[] newPlainText = cipher.doFinal(cipherText); 
System.out.println("Finish decryption: "); 

System.out.println(new String(newPlainText, "UTF8")); 
} 
} 

的例子任何人都可以建議我怎麼可以添加自己的鑰匙在這個例子嗎?

回答

1

如果您打算提供密鑰,請將其中的一個作爲參數,而不是generateKey。

編輯:generateKey生成一個隨機密鑰。保存此密鑰以用於解密可能比添加代碼以解析密鑰arg更簡單。看看KeyGeneratorSecretKey

+0

感謝您的及時答覆,但你可以請更具體一點。 generateKey不會帶任何參數! – antnewbee

+0

generateKey生成一個隨機密鑰。您可以更簡單地保存此密鑰以用於解密,而不是添加代碼以解析密鑰arg。 – jacknad

+0

這似乎並不好,因爲我將在整個應用程序中使用該類,每次重新啓動服務器時,密鑰都會改變。 – antnewbee