gpt4 book ai didi

java - 如何正确解密 javax.crypto 加密字符串

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

尝试解密时出现以下错误:

javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

这是我实现的加密类:

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class StringEncrypter {

public static String encrypt(String key, String string, String algorithm) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(string.getBytes());
return encrypted.toString();
}

public static String decrypt(String key, String encryptedString, String algorithm) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encryptedString.getBytes()));
return decrypted;
}
}

这就是我加密字符串的方法:

StringEncrypter.encrypt("0306868080306868", "ddd", "AES"); // [B@e19957c

当我尝试像这样解密上述加密字符串时:

String decrypted = StringEncrypter.decrypt("0306868080306868", "[B@e19957c", "AES");

我收到illegalBlockSizeException

我上面做错了什么?如何正确解密加密的字符串?

最佳答案

您需要对 key 和密文执行 Base 64 编码解码。有一个新的Base64 Java 8 中的类。您不能只存储字符串中的任何字节,并非所有字节都表示可打印字符甚至有效字符,并且密码的输出与随机输出无法区分。

除此之外,字节数组“class”(在 Java 中用 [B 表示)没有实现 toString 方法,这意味着您只是得到打印输出Object.toString,即类名[B和对象实例的人类可读标识符而不是实际的密文。

关于java - 如何正确解密 javax.crypto 加密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381630/

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