gpt4 book ai didi

javax.crypto.BadPaddingException : Given final block not properly padded. ..尝试使用 getbytes ("UTF")

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

我已经尝试添加 getbytes("UTF") 或 getbytes("UTF-8"),因为它在类似的问题中被建议。它说我们需要在将字节转换为字符串时尝试使用 UTF,反之亦然。但它仍然不适用于我的代码...请帮忙

public class Password1 {

private static final String ALGO = "AES";
private static byte[] keyValue = new byte[]{'t','h','y','u','e','f','z','s','y','k','f','l','d','a','b','m'};

public static void main(String[] args) {
//Password1 p = new Password1();
Scanner sc = new Scanner(System.in);
String i = sc.nextLine();
System.out.println("Password = "+i);

try {
String en = encrypt(i);
System.out.println(en);
String dec = decrypt(en);

System.out.println("Encrypted = " + en);
System.out.println("Decrypted = " + dec);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static String encrypt(String Data) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = c.doFinal(Data.getBytes("UTF-8"));
String encrypted = new BASE64Encoder().encode(encVal);

return encrypted;
}

public static String decrypt(String encrypted) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key);
//Byte bencrypted = Byte.valueOf(encrypted);
byte[] decoded = new BASE64Decoder().decodeBuffer(encrypted);

byte[] decValue = c.doFinal(decoded);
String decrypted = new String(decValue);
return decrypted;
}

private static Key generateKey() throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
keyValue = sha.digest(keyValue);
keyValue = Arrays.copyOf(keyValue, 16);
SecretKeySpec key = new SecretKeySpec(keyValue, ALGO);
return key;
}

}

最佳答案

当您调用 encrypt() 时,您用它的散列替换密码,然后使用散列作为 key 。

然后调用decrypt(),重新散列哈希值,并使用散列后的散列值作为 key 。所以你没有使用相同的 key 进行加密和解密。

main() 中生成 key 一次,并将其作为参数传递给 encrypt()decrypt()。使 keyValue 最终化。或者更好的是,将其设为 main 的局部变量。

关于javax.crypto.BadPaddingException : Given final block not properly padded. ..尝试使用 getbytes ("UTF"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35853757/

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