AES加密,InvalidKeyException:不支持的密钥大小:6个字节?

时间:2017-04-03 10:58:42

标签: java encryption aes

我正在尝试按如下方式加密字符串

public class AES256Cipher {
static byte[] ivBytes = new byte[]{0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
static String EncryptionKey = "abc123";

public static byte[] encrypt(String plainText)
        throws java.io.UnsupportedEncodingException,
        NoSuchAlgorithmException,
        NoSuchPaddingException,
        InvalidKeyException,
        InvalidAlgorithmParameterException,
        IllegalBlockSizeException,
        BadPaddingException {
    byte[] keyBytes = EncryptionKey.getBytes("UTF-8");

    AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
    byte[] cipherData = cipher.doFinal(plainText.getBytes("UTF-8"));
    Log.e("cipher", Base64.encodeToString(cipherData, Base64.DEFAULT));
    return cipher.doFinal(plainText.getBytes("UTF-8"));
}
}

我收到此异常

java.security.InvalidKeyException: Unsupported key size: 6 bytes
at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER$AES.checkSupportedKeySize(OpenSSLCipher.java:686)
at com.android.org.conscrypt.OpenSSLCipher.checkAndSetEncodedKey(OpenSSLCipher.java:442)
at com.android.org.conscrypt.OpenSSLCipher.engineInit(OpenSSLCipher.java:272)
at javax.crypto.Cipher.tryTransformWithProvider(Cipher.java:608)
at javax.crypto.Cipher.tryCombinations(Cipher.java:532)
at javax.crypto.Cipher.getSpi(Cipher.java:437)
at javax.crypto.Cipher.init(Cipher.java:909)
at javax.crypto.Cipher.init(Cipher.java:859)
at com.vfirst.util.netwrok.AES256Cipher.encrypt(AES256Cipher.java:36)
at com.vfirst.LoginActivity.onCreate(LoginActivity.java:61)
at android.app.Activity.performCreate(Activity.java:6321)

要加密的字符串

AES256Cipher.encrypt("12345");

3 个答案:

答案 0 :(得分:9)

AES仅支持16,24或32字节的密钥大小...因此您必须更改EncryptionKey。

SecureRandom random = new SecureRandom();
byte[] EncryptionKey = new byte[16];
random.nextBytes(EncryptionKey);

您可以使用上面的代码示例。

答案 1 :(得分:3)

如果您想使用密码,则应从密码中获取AES密钥,而不是直接尝试使用密码作为密钥。

最简单的方法是使用SHA-256散列密码,并使用散列密码作为AES密钥。

常用方法(首选)是使用PBKDF2,例如使用HMAC-SHA1从密码生成AES密钥(128/192或256位):

byte[] salt = new byte[8];
random.nextBytes(salt);
KeySpec spec = new PBEKeySpec(EncryptionKey.toCharArray(), salt, 65536, 128);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] keyBytes = f.generateSecret(spec).getEncoded();

请注意,如果您想稍后从密码生成相同的密钥,则必须存储随机盐。

答案 2 :(得分:2)

AES允许密钥长度为128192256 bit。 换句话说,162432 byte