AES算法JAVA Giving:java.lang.IllegalArgumentException:密钥大小无效

时间:2014-03-12 07:20:47

标签: java encryption aes

我正在为AES算法做一个简单的实现。

// Get the Key Generator
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128); // 192 and 256 bits may not be available
        // Generate the secret key specs.
        SecretKey secret = kgen.generateKey();
        byte[] raw = secret.getEncoded();

String key = new String(Base64.encodeBase64(raw));

我在数据库中保存"key"。   现在再次在另一个操作中,我正在获取一个"键"来自数据库n试图解密数据。我将解密功能称为

String dencryptReq = Utils.decrypt2(new String(Base64.decodeBase64(secretKeyInformation.getSecretKey().getBytes())),Base64.decodeBase64(encryptReq.getBytes()) );


public static String decrypt2(String key, byte[] encrypted)
        throws GeneralSecurityException {

    byte[] raw = Base64.decodeBase64(key.getBytes());
    if (raw.length != 16) {
        throw new IllegalArgumentException("Invalid key size.");
    }
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec,
            new IvParameterSpec(new byte[16]));
    byte[] original = cipher.doFinal(encrypted);

    return new String(original, Charset.forName("US-ASCII"));
}

But it is throwing me invalid key size exception.

If i do in one time this without saving in databse and fetching from database it is working fine.

1 个答案:

答案 0 :(得分:0)

我已尝试使用 apache commons编解码器库进行Base64转换的一些修改代码,

/* Derive the key, given password and salt. */
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec("password".toCharArray(), "salt".getBytes(), 65536, 128);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");


/* Encrypt the message. */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] ciphertext = cipher.doFinal("Hello, World! My data is here.. !".getBytes("UTF-8"));
System.out.println("cipher :"+new String(ciphertext));






/*String-key convertion */
String stringKey=Base64.encodeBase64String(secret.getEncoded());//To String key
byte[] encodedKey     = Base64.decodeBase64(stringKey.getBytes());
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");// Convert from string



/* Decrypt the message, given derived key and initialization vector. */
Cipher cipher1 = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher1.init(Cipher.DECRYPT_MODE, originalKey, new IvParameterSpec(iv));
String plaintext = new String(cipher1.doFinal(ciphertext), "UTF-8");
System.out.println(plaintext);

此代码在我的系统中运行良好。