gpt4 book ai didi

java - 在 Java 中执行 AES 解密时出现奇怪的字符

转载 作者:行者123 更新时间:2023-11-30 02:47:29 24 4
gpt4 key购买 nike

我正在尝试解密 AES-ECB 128 加密字符串。该字符串未使用 Java 加密,我收到它作为 Java 中的输入,并且想要解密它。

我已使用 AESLib 在 Arduino 中加密了消息“0123456789012345”

  uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
char data[] = "0123456789012345"; //16 chars == 16 bytes
aes128_enc_single(key, data);

加密形式的字符串为“1425EC9B5D983FF7DF45A4A8089E69FC”。

这就是我在java中解密它的方法:

private static byte[] key = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15};

public static String decrypt()
{

byte[] info= hexStrToByteArray("1425EC9B5D983FF7DF45A4A8089E69FC");
try
{
Cipher cipher = Cipher.getInstance("AES/ECB/NOPADDING");
final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedResult= cipher.doFinal(info);
String result = new String(result, "UTF-8");
return result;
}
catch (Exception e)
{
e.printStackTrace();

}
return null;
}


private static byte[] hexStrToByteArray(String hex) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(hex.length() / 2);

for (int i = 0; i < hex.length(); i += 2) {
String output = hex.substring(i, i + 2);
int decimal = Integer.parseInt(output, 16);
baos.write(decimal);
}
return baos.toByteArray();
}

我从这个函数得到的是:.1�@JY�y�Гv�

我猜是编码问题。如何以可读的形式获得解密结果?

谢谢!

最佳答案

您的 key 不正确。

在加密方面,您有:

uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

在解密方面,您有:

private static byte[] key = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15};

0x1212 不同。您在文字中混淆了十六进制和十进制。在解密方面,您的意思是:

private static byte[] key = { 
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

或者:

private static byte[] key = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };

顺便说一句,你的原始数据是us-ascii而不是utf-8;在这里并没有真正的区别,也不是问题的一部分,但为了安全起见,您也应该在解密端使用 us-ascii。

关于java - 在 Java 中执行 AES 解密时出现奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733712/

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