我想用AES加密信息,其中密钥是根据我输入的一个字符串生成的,运行时系统报错说“Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 8 bytes”,出错的语句是“aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);”,下面是我的代码:
import javax.crypto.spec.*;
import javax.crypto.*;
public class Experiment {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
SecretKeySpec aesKey = new SecretKeySpec("12345678".getBytes(), "AES");
Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
aesCipher.init(Cipher.ENCRYPT_MODE, aesKey); //这句报错了
byte[] plaintext = "Hello!".getBytes();
byte[] ciphertext = aesCipher.doFinal(plaintext);
aesCipher.init(Cipher.DECRYPT_MODE, aesKey);
byte[] decrypted = aesCipher.doFinal(ciphertext);
System.out.println(decrypted);
}
}
问题出在哪里?应该怎么改?请大家帮帮忙!
------解决方案--------------------------------------------------------
SecretKeySpec aesKey = new SecretKeySpec("1234567812345678".getBytes(), "AES"); //Key要16位的
因为AES是128\192\256。。。