K M*_*lam 5 java cryptography aes secret-key
我的目标是编写一个Java程序来加密文本文件(cipher text)AES algorithm.然后,编写另一个程序来解密该加密文件(cipher text)以获取纯文本.我想使用相同的密钥(相同的密钥,生成一次,保存在某处,并在加密和解密程序中使用它)进行加密和解密过程.如果我生成密钥并在同一程序中逐行进行加密和解密,那么它可以完美地工作.以下是该工作代码段:
String strDataToEncrypt = new String();
String strCipherText = new String();
String strDecryptedText = new String();
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
strDataToEncrypt = "any text input";
byte[] byteDataToEncrypt = strDataToEncrypt.getBytes();
byte[] byteCipherText = aesCipher.doFinal(byteDataToEncrypt);
strCipherText = new BASE64Encoder().encode(byteCipherText);
System.out.println("cipher text: " +strCipherText);
aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());
byte[] byteDecryptedText = aesCipher.doFinal(new BASE64Decoder().decodeBuffer(strCipherText));
strDecryptedText = new String(byteDecryptedText);
System.out.println("plain text again: " +strDecryptedText);
Run Code Online (Sandbox Code Playgroud)
但是,我需要有两个不同的程序(java文件)进行加密和解密.所以,我必须以某种方式生成一个密钥并保存在某个地方.然后对加密和解密程序使用相同的密钥.我怎样才能做到这一点?
EDIT_1
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
byte[] encoded = secretKey.getEncoded();
System.out.println("key: "+encoded);// key: [B@52b2a2d8
Run Code Online (Sandbox Code Playgroud)
我可以使用上面的程序获取编码的键值.但我的问题是如何在我的解密程序中使用此值生成SecretKey?
ini*_*mfs 15
如果我误解了你的问题,请原谅我,但我相信你希望SecretKey从一个字节数组中编码的现有密钥重建一个对象.
这可以通过使用javax.crypto.spec.SecretKeySpec的构造函数简单地执行:
byte[] encoded = //Key data
SecretKey secretKey = new SecretKeySpec(encoded, "AES");
Run Code Online (Sandbox Code Playgroud)
因为SecretKeySpec是SecretKey不需要铸造的子类.如果您的加密/解密算法发生变化,请确保将构造函数中使用的字符串文字更改为AES您决定将来使用的算法.