我想用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);}}问题出在哪里?应该怎么改?请大家帮帮忙!安全版太冷清了,看这里比较热闹,就来这里问了,呵呵。

解决方案 »

  1.   

    public static void main(String[] args) throws Exception {
    String message = "This is just an example"; // Get the KeyGenerator KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128); // 192 and 256 bits may not be available // Generate the secret key specs.
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded(); Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    aesCipher.init(Cipher.ENCRYPT_MODE, skey); // 这句报错了
    byte[] plaintext = "Hello!".getBytes();
    byte[] ciphertext = aesCipher.doFinal(plaintext);
    aesCipher.init(Cipher.DECRYPT_MODE, skey);
    byte[] decrypted = aesCipher.doFinal(ciphertext);
    System.out.println(decrypted);
    }
      

  2.   

    key 128位
    SecretKeySpec aesKey = new SecretKeySpec("1234567812345678".getBytes(), "AES");
      

  3.   

    AES的基本要求是,采用对称分组密码体制,密钥长度的最少支持为128、192、256,分组长度128位
      

  4.   

    可是在生成密钥时,我还想用自己提供的一个密码,因此用了这句SecretKeySpec aesKey = new SecretKeySpec("12345678".getBytes(), "AES"); “12345678”是我提供的一个任意长度的密码,密钥通过它生成。