我必须使用带有密钥的 DES 加密/解密 java 中的纯文本。我在 IBM 有一个非常好的教程,可以在这里找到。此示例的问题在于它在程序本身中生成密钥。现在,如果我加密一个字符串(例如密码)并存储在数据库中,那么我将无法解密它,因为我不知道密钥。
以下是 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") );
}
}
谁能建议我如何在此示例中添加自己的密钥?