我有一个在NodeJ上运行的代码。我们想改变技术(到java)。 问题是我们有一些现有的密码,我不知道如何将加密逻辑复制到java。 因此,可能的解决方案之一是在javascript中运行加密逻辑(例如命令行,嵌入java等)并获得结果。
问题是 - 我该怎么做?
nodejs代码如下:
crypto = require('crypto');
this.salt = this.makeSalt();
encryptPassword: function(password) {
var salt = new Buffer(this.salt, 'base64');
return crypto.pbkdf2Sync(password, salt, iterations, keylen).toString('base64');
crypto.randomBytes(..)
}
makeSalt: function() {
return crypto.randomBytes(numOfBytes).toString('base64');
},
更新: 按照这里的建议,我添加了完整的代码。如果正确的方法是将javascript代码转换为java代码,请帮我翻译上面的代码吗?
答案 0 :(得分:1)
如果你想在Java中使用随机字节,你不应该这样做。您应该能够用Java复制加密逻辑。
byte[] b = new byte[20];
new Random().nextBytes(b);
几乎所有Node.js加密函数都是通用的,并且应该有自己的Java对应项或第三方库。
<强>更新强>
如果必须通过java运行节点代码,可以添加此方法
public static String runCommand(String command) {
String output = "";
try {
String line;
Process process = Runtime.getRuntime().exec( command );
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()) );
while ((line = reader.readLine()) != null) {
output += line;
}
reader.close();
} catch (Exception exception) {
// ...
}
return output;
}
并像这样运行
String encryptedPassword = runCommand("node myEncryption.js --password=1234");