2012-12-11 65 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