gpt4 book ai didi

java - 为什么在尝试加密字符串时会出现 BadPaddingException?

转载 作者:行者123 更新时间:2023-12-01 14:47:51 25 4
gpt4 key购买 nike

我创建了一个Encryption类来加密/解密我的Android项目中的二进制数据,通过这个link .

package com.my.package;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

// TODO Incomplete class
public class Encryption {

private static final byte[] salt = { (byte) 0xA4, (byte) 0x0B, (byte) 0xC8,
(byte) 0x34, (byte) 0xD6, (byte) 0x95, (byte) 0xF3, (byte) 0x13 };

private static int BLOCKS = 128;

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}

private static byte[] getKey() throws Exception {
byte[] keyStart = "this is a key".getBytes();
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(keyStart);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
return key;
}

public static void test() {
String test = "My Name Is Dragon Warrior";

byte[] e = null;
try {
e = encrypt(getKey(), test.getBytes());
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] d = null;
try {
d = decrypt(getKey(), e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(new String(d));
}
}

然后我在主要 Activity 中运行代码:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
Encryption.test();
// ...
}

然后,当在 test() 中执行以下代码时,我得到一个 BadPaddingException:

try {
d = decrypt(getKey(), e);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

有趣的是我创建了一个Java项目而不是Android项目。并且代码运行良好,没有任何异常。

我的代码有什么问题吗?

最佳答案

“SHA1PRNG”不是 key 派生函数,并且不同提供商的实现可能有所不同。请使用正确的 KDF(例如 PBKDF2)作为密码。 “这是一个键”不是一个键,它是一个字符串。

关于java - 为什么在尝试加密字符串时会出现 BadPaddingException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15240134/

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