我需要将一些代码从java
移植到处理加密的javascript
。在给定相同密钥的情况下,我无法根据现有代码重现相同的密文。
我怀疑我无法弄清楚正确的模式。附上代码段 -
public String encrypt(String message, String enc_key) throws Exception {
try {
initEncrypt(enc_key);
byte[] encstr = cipher.doFinal(message.getBytes());
return HexUtil.HextoString(encstr);
} catch (BadPaddingException nse) {
throw new Exception("Invalid input String");
}
}
public void initEncrypt(String key) throws Exception {
try {
skeySpec = new SecretKeySpec(HexUtil.HexfromString(key), "AES");
cipher = Cipher.getInstance("AES");
// cipher.
cipher.init(1, skeySpec);
System.out.println(cipher.getAlgorithm());
} catch (NoSuchAlgorithmException nsae) {
throw new Exception("Invalid Java Version");
} catch (NoSuchPaddingException nse) {
throw new Exception("Invalid Key");
}
}
HexToString函数只是转换字节数组中的十六进制字符串键。
提供密钥 - 10663d0b39d73d614116f0b3cbebd666
(hex)纯文本 - hello
,我得到 - 密文 - 57C758B2B3A8580658A11DBD95109EC4
根据这个so的回答,默认模式应该是AES/ECB/PKCS5Padding
但是,当我尝试使用相同的值here进行加密时,我得到了密文 -
3874350661ABB0B452A4960FE3953C18
我尝试了其他各种模式,但我无法匹配密文。任何帮助将不胜感激。
不要依赖默认行为。如果您知道这些选项,请继续并指定它们。如果您不知道这些选项,请继续查找它们,然后指定它们。
两个加密的消息都是用你的密钥“hello”加密的..唯一的区别是不同的填充模式:
57C758B2B3A8580658A11DBD95109EC4 decrypts to 68656c6c6f0b0b0b0b0b0b0b0b0b0b0b
h e l l o <-- pkcs5 padding -->
3874350661ABB0B452A4960FE3953C18 decrypts to 68656c6c6f0000000000000000000000
h e l l o <-- zerro padding -->