gpt4 book ai didi

java - Android 加密和解密错误 - javax.crypto.IllegalBlockSizeException : last block incomplete in decryption

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

我在以下代码中遇到解密问题。我有一个加密的字符串被发送到 setData()。我正在尝试解密加密的字符串(数据)。我不断收到的错误是

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

byte[] data;
String key = "tkg96827pco74510";

byte[] encryptedOut;
String decryptedOut;

Key aesKey;
Cipher cipher;

public void setData(String dataIn){
this.data = dataIn.getBytes();
try {
aesKey = new SecretKeySpec(key.getBytes(), "AES");
cipher = Cipher.getInstance("AES");

}catch(Exception e){
System.out.println("SET DATA ERROR - " + e);
}
}
public void encrypt() {
try{
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
encryptedOut = cipher.doFinal(data);
}catch(Exception e){
System.out.println(e);
}
}

public void decrypt(){
try {
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decryptedOut = new String(cipher.doFinal(data));

}catch(Exception e){
System.out.println("Decrypt Error: " + e);
}
}

public byte[] getEncrypted() {
return encryptedOut;
}

public String getDecrypted(){
return decryptedOut;
}

最佳答案

问题是由这一行引起的:

decryptedOut = new String(cipher.doFinal(data));

这里您将传递原始数据进行解密。但您应该在此处传递 encryptedOut

所以解决方案是:

decryptedOut = new String(cipher.doFinal(encryptedOut));

是的,请传递一些编码机制将 String 转换为 byteArray,反之亦然,例如 "UTF-8"

所以正确的行是:

decryptedOut = new String(cipher.doFinal(encryptedOut),"UTF-8");

假设您已经完成了这样的字节转换:

this.data = dataIn.getBytes("UTF-8");

关于java - Android 加密和解密错误 - javax.crypto.IllegalBlockSizeException : last block incomplete in decryption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30098239/

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