gpt4 book ai didi

javax.crypto.IllegalBlockSizeException : last block incomplete in decryption

转载 作者:行者123 更新时间:2023-11-29 05:32:46 26 4
gpt4 key购买 nike

我正在开发一个 android 项目,我必须从 PHP 服务器中的文件中解密字符串,加密是使用 PHP 完成的。(AES 128 算法)

加密代码:

 function aes128Encrypt($key, $data) {
$key = md5($key);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
}

我从 URL 获取字符串的代码:

String myUri = "http://www.example.com/lib2.php";
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(myUri);

HttpResponse response = httpClient.execute(get);

String bodyHtml = "";
String xmlFile = "";
bodyHtml = EntityUtils.toString(response.getEntity());
System.out.println(bodyHtml);
xmlFile = decrypt(bodyHtml);
System.out.println(xmlFile);

解密() 方法:

public static String decrypt(String encData) throws Exception
{
Key key = generateKey();

Cipher c = Cipher.getInstance(algo + "/CBC/PKCS7Padding");

//Cipher c = Cipher.getInstance(algo);

IvParameterSpec ivSpec = new IvParameterSpec(ivbytes);

c.init(Cipher.DECRYPT_MODE, key , ivSpec);

//byte[] decValue = Base64.decode(encData , Base64.NO_PADDING);

//byte[] decFin = Base64.decode(decValue, Base64.NO_PADDING);

//byte[] decFinal = c.doFinal(decValue);

byte[] decFinal = c.doFinal(encData.getBytes());

String getAns = new String(decFinal, "UTF8");

return getAns;
}

在 generateKey() 中:

public static Key generateKey()
{

try {
MessageDigest digest = java.security.MessageDigest
.getInstance("MD5");

digest.update(myChar.getBytes());

key1 = digest.digest();

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}



Key key = new SecretKeySpec(key1,algo);
return key;
}
}

Logcat 显示以下异常:

javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

在行 c.doFinal()

我注释掉的代码也是我查过的代码。这段代码有什么问题?任何帮助将不胜感激。

最佳答案

您的 chiper 正在等待填充“/CBC/PKCS7Padding”。这与消息编码 (BASE64) 无关。要么在 Java 端更改预期的 chipher,要么在 PHP 端使用填充进行加密。

Chiper 被指定为 algorithm/mode/paddingalgortihm,参见 http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html了解详情。

你正在指定一个带有填充的 chiper,但实际上在 php 端进行了零填充,

摘自 http://www.php.net/manual/de/function.mcrypt-encrypt.php :

# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);

关于javax.crypto.IllegalBlockSizeException : last block incomplete in decryption,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20562287/

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