gpt4 book ai didi

java - 解密字符串生成 IllegalBlockSizeException

转载 作者:行者123 更新时间:2023-11-29 03:19:09 26 4
gpt4 key购买 nike

我在处理解密方法时遇到了问题。加密产生了正确的输出,但是当我解密完全相同的加密字符串时(应该返回明文字符串),它不起作用。

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Samp {

private static String IV = "aaaaaaaaaaaaaaaa";
private static final String UNICODE_FORMAT = "UTF8";

private String padd(String plaintext) {
while (plaintext.length() % 16 != 0) {
plaintext += "\0";
}
return plaintext;
}

public String encryptString(String plaintext, String encryptionKey) {
try {
byte[] cipher = encrypt(padd(plaintext), encryptionKey);
return new String(cipher, UNICODE_FORMAT);
} catch (Exception ex) {
ex.printStackTrace();
}

return null;
}

public String decryptString(String encString, String encryptionKey) {
try {
System.out.println("**** decryptString ****");
System.out.println("enc = " + encString);
System.out.println("key = " + encryptionKey);

String decrypted = decrypt(encString.getBytes(UNICODE_FORMAT), encryptionKey);
return decrypted;
} catch (Exception ex) {
ex.printStackTrace();
}

return null;
}

private static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes(UNICODE_FORMAT), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes(UNICODE_FORMAT)));
return cipher.doFinal(plainText.getBytes(UNICODE_FORMAT));
}

private static String decrypt(byte[] cipherText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes(UNICODE_FORMAT), "AES");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes(UNICODE_FORMAT)));
return new String(cipher.doFinal(cipherText), UNICODE_FORMAT);
}
// implement methods here
// using AES simple encryption

public static void main(String[] args){
String plaintext = "Hello World!";
String key = "asdfqaqwsaerdqsw";

Samp s = new Samp();
String enc = s.encryptString(plaintext, key);
System.out.println("encrypted string = " + enc);
String dec = s.decryptString(enc, key);
System.out.println("decrypted string = " + dec);
}
}

我已经看过这个 post ,这和我有同样的问题。我遵循了建议(更改 getBytes() -> getBytes(UNICODE_FORMAT)),但它仍然是一样的。我仍然遇到异常(javax.crypto.IllegalBlockSizeException:输入长度不是 16 字节的倍数)

最佳答案

  public String encryptString(String plaintext, String encryptionKey)

问题就在这里。字符串不是二进制数据的容器。这个方法应该返回一个 byte[]。类似地,decrypt() 方法应该将 byte[] 作为密文参数,而不是字符串。

关于java - 解密字符串生成 IllegalBlockSizeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24749074/

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