当前位置: 代码迷 >> Java相关 >> Exception in thread "main" java.security.InvalidKeyException:
  详细解决方案

Exception in thread "main" java.security.InvalidKeyException:

热度:4980   发布时间:2013-02-25 21:50:57.0
用AES加密密钥长度问题
我想用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。。。
  相关解决方案