我已经搜索了很多,但还没有对我的特定问题做出任何澄清。我有一个使用node.js的过程,该过程加密一些数据元素并存储十六进制字符串输出。为了避免对该特定过程进行详细介绍,其结果与此处的以下在线工具相同。
如果要在该工具中输入以下内容:
Enter text to be Encrypted: "666326911"
Select Mode: "CBC"
Key Size in Bits: "256"
Enter IV: (Leave blank)
Enter Secret Key: "c88ba867994f440963f55b727cdd3cb7"
Output Text Format: "Hex"
加密输出将为您提供“ C08F3DD7F5F7ACD0FC3710ADDFBF596C”。这个结果符合我的过程。
我现在需要以相同的方式使用Java加密数据。我的代码为我提供了完全不同的结果,而且我似乎无法查明错误发生的位置。这是我正在使用的Java代码:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key key = new SecretKeySpec(Hex.decodeHex("c88ba867994f440963f55b727cdd3cb7"), "AES");
IvParameterSpec iv = new IvParameterSpec(new byte[16]);
cipher.init(Cipher.ENCRYPT_MODE,key,iv);
byte[] testString = "666326911".getBytes("UTF-8");
byte[] encrypted = cipher.doFinal(testString);
System.out.println("Encrypt Hex: "+Hex.encodeHexString(encrypted));
该代码为我提供了“ DA6711D88635E82B68673D9C077B070F”的结果。谁能告诉我我明显的错误或不正确的假设在哪里?
谢谢,斯科特
编辑:
将代码更改为:
SecretKeySpec key = new SecretKeySpec("c88ba867994f440963f55b727cdd3cb7".getBytes("UTF-8"), "AES");
导致“ InvalidKeyException:密钥大小非法”
问题似乎出在SecretKeyspec。
在在线工具上,您将其用作纯字符串。
在这里,您将其视为十六进制数字,然后首先对其进行解码。
如果你试试
Key key = new SecretKeySpec("c88ba867994f440963f55b727cdd3cb7".getBytes(), "AES");
那么您应该得到相同的结果。
这是我正在使用的代码的复制粘贴:
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Key key = new SecretKeySpec("c88ba867994f440963f55b727cdd3cb7".getBytes("UTF-8"), "AES");
IvParameterSpec iv = new IvParameterSpec(new byte[16]);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] testString = "666326911".getBytes("UTF-8");
byte[] encrypted = cipher.doFinal(testString);
System.out.println("Encrypt Hex: " + Hex.encodeHexString(encrypted));
} catch (Exception e) {
System.err.println("Uh-ohh...");
e.printStackTrace();
}
输出为:
Encrypt Hex: c08f3dd7f5f7acd0fc3710addfbf596c
Process finished with exit code 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句