gpt4 book ai didi

Java解密

转载 作者:行者123 更新时间:2023-12-01 14:46:00 24 4
gpt4 key购买 nike

我有一个问题

javax.crypto.Cipher

当我写这行代码时

    Cipher cipher;
byte[] bytes = null;

try
{
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
bytes = cipher.doFinal(input.getBytes("UTF-8"));
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}

控制台给我这个错误

javax.crypto.IllegalBlockSizeException 
Input length must be multiple of 16 when
decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at it.unitn.se.gym.backend.utils.Security.AES128Decode(Security.java:109)
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:96)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)
Exception in thread "main" java.lang.NullPointerException
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:97)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)

前两行代码是正确的,但是当我将 byte[] 类型的属性“text”传递给 doFinal 函数时,它给出了错误。

谁能告诉我为什么?

已解决:

好的,问题解决了

byte[] encrypted = UniversalBase64Encoder.decode(input);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
byte[] originalBytes = cipher.doFinal(encrypted);

这是我编写的正确代码

最佳答案

问题在于您尝试解密未加密的字符串,这样做违反了解密算法的假设(即其输入大小始终是 16 的倍数)。

这是加密然后解密字符串的代码块。请注意,当打印加密字符串时,它的长度为 16 个字节,尽管输入字符串并非如此。加密算法在加密之前将输入字符串填充为 16 字节的倍数。该 16 字节长的加密字符串现在是解密的有效输入。

这个假设(加密的结果将是均匀大小)是相当标准的。它不仅使解密/加密算法更容易编写,而且还可以防止攻击者知道您加密的内容的长度。

byte[] keyBytes = new byte[16];
keyBytes[0] = 1;
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
String input = "hello";
Cipher cipher;
byte[] bytes = null;
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
bytes = cipher.doFinal(input.getBytes("UTF-8"));

System.out.println("Encoded: "+Arrays.toString(bytes));

cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decoded = cipher.doFinal(bytes);

System.out.println("Decoded: "+new String(decoded, "UTF-8"));

关于Java解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15432917/

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