【发布时间】:2017-07-13 15:34:24
【问题描述】:
我正在尝试从 nodejs 上的 java 代码中解密加密值
下面是java的加密方法
public class EncryptUtil {
public static String getKey()
{
return "somekeysomekey+)"; //key length 16!Use this on nodejs
}
public static String encryptAES(String ID) throws Exception {
Key secretKeySpec = new SecretKeySpec(getKey().getBytes(), "AES");
String transform = "AES/ECB/ISO10126Padding";
String output = "";
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(transform);
cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKeySpec);
String originStr = ID;
byte[] input = originStr.getBytes("UTF8");
byte[] output = cipher.doFinal(input);
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
output = encoder.encode(output);
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
return output;
}
}
//This is how to encrypt from above
//String encryptText = (String) EncryptUtil.encryptAES("something");
//System.out.println(encryptText) ---> "47gPeqm+0lvKb0VNXF29yQ==";
这是我在 nodejs 上解密上述结果的代码
const crypto = require('crypto');
const key = 'somekeysomekey+)';
const algorithm = 'aes-128-ecb';
function decryptFunc(encryptedStr) {
const base64Decoded = new Buffer(encryptedStr, 'base64').toString('binary');
const decipher = crypto.createDecipher(algorithm, key);
decipher.setAutoPadding(false);
let result = decipher.update(base64Decoded, 'binary', 'binary');
result += decipher.final('binary');
return new Buffer(result).toString('utf8');
};
但是我的代码不起作用.. 如何在 nodejs 上解密?..
【问题讨论】:
-
你的意思是“不工作”?抛出异常,返回错误结果还是别的什么?
-
你的加密方式一样吗?
-
您尝试过
new Buffer(result, 'binary')吗?'utf8'是默认的字符串编码。此外,您应该避免使用'binary'字符串编码,而直接使用缓冲区。最后,使用Buffer.from()而不是new Buffer()。 -
还有一点:ECB模式很糟糕,不惜一切代价避免它。
-
@talex 我知道我的功能完全错误。这只是我尝试解码的众多尝试之一。我的问题的重点是如何在节点js上通过上述java代码解密加密结果(使用crypto模块)
标签: java node.js encryption aes