gpt4 book ai didi

java - AES 加密,InvalidKeyException : Unsupported key size: 6 bytes?

转载 作者:行者123 更新时间:2023-11-29 09:34:25 25 4
gpt4 key购买 nike

我正在尝试加密一个字符串,如下所示

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

最佳答案

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

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

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

关于java - AES 加密,InvalidKeyException : Unsupported key size: 6 bytes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com