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

6

我正在尝试进行以下字符串加密

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");

1
可能是如何修复无效的AES密钥长度?的重复问题。 - Tom
2
“无效密钥大小6字节”这个错误怎么可能再清楚不过了呢?我不明白你为什么需要问这个问题? - Luke Joshua Park
将您的加密密钥“abc123”增加到16个字符,例如“abc123abc123abc1”。 - varotariya vajsi
3个回答

23

AES只支持16、24或32字节的密钥...所以您必须更改您的EncryptionKey。

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

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


3
你还应该谈一下密钥处理。没有适当的密钥处理,这就没有那么有用了。 - Artjom B.
你应该把那段代码放在你想要使用加密的地方。 - Alper Özaslan

8
AES允许使用128、192和256位密钥长度。换句话说,可以使用16、24或32字节。

1
感谢上帝有人懂密码学,不像我。 - Chaki_Black
正确!类似于“GWS3eDKYYoaZISBxbUINjvhreiiYHSAg”的字符串,长度为32。 - Farmaker

4

如果您想使用密码,应该从密码中派生出一个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();

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接