gpt4 book ai didi

java - 尝试使用 AES 加密和解密字符串时出现 IllegalBlockSizeException

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:17:39 25 4
gpt4 key购买 nike

我有一个硬编码 key ,我想在将字符串存储到 SharedPreferences 之前用它加密字符串。这是我到目前为止的代码:

public class TokenEncryptor {

private final static String TOKEN_KEY = "91a29fa7w46d8x41";

public static String encrypt(String plain) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
SecretKeySpec newKey = new SecretKeySpec(TOKEN_KEY.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(plain.getBytes()));
} catch (Exception e) {
Ln.e(e);
return null;
}
}

public static String decrypt(String encoded) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AlgorithmParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
SecretKeySpec newKey = new SecretKeySpec(TOKEN_KEY.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
return new String(cipher.doFinal(encoded.getBytes()));
} catch (Exception e) {
Ln.e(e);
return null;
}
}
}

它似乎在decrypt 方法的末尾捕获了一个异常:

javax.crypto.IllegalBlockSizeException:错误:0606506D:数字信封例程:EVP_DecryptFinal_ex:错误的最终 block 长度

有人能指出我正确的方向吗?我感觉我在实例化 IvParameterSpec 时做错了什么。

最佳答案

当您使用 AES 加密字符串时,您会得到一个字节数组。尝试将这些字节直接转换为字符串 (new String(cipher.doFinal(plaintextBytes))) 会导致各种问题。如果您要求加密方法的输出为字符串,请使用 Base64 而不是尝试直接转换。在您的解密方法中,在解密字节数组之前,将 Base64 字符串转换回字节数组。

此外,不要使用 getBytes(),因为输出取决于系统默认值。使用 getBytes("utf-8") 或其他。这消除了歧义。

关于java - 尝试使用 AES 加密和解密字符串时出现 IllegalBlockSizeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30383736/

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