【发布时间】:2011-12-08 22:07:30
【问题描述】:
寻找一种在节点中加密数据(主要是字符串)并在安卓应用程序(java)中解密的方法。
在每一个中都已成功完成(在节点中加密/解密,在 java 中加密/解密),但似乎无法在它们之间工作。
可能我没有以相同的方式加密/解密,但是每种语言的每个库对相同的事物都有不同的名称...
任何帮助表示赞赏。
这里有一些代码: Node.js
var crypto = require('crypto')
var cipher = crypto.createCipher('aes-128-cbc','somepass')
var text = "uncle had a little farm"
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex')
//now crypted contains the hex representation of the ciphertext
和java
private static String decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec );
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted);
}
原始密钥是这样创建的
private static byte[] getRawKey(String seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] seedBytes = seed.getBytes()
sr.setSeed(seedBytes);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
而加密的十六进制字符串被转换成这样的字节
public static byte[] toByte(String hexString) {
int len = hexString.length()/2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
return result;
}
【问题讨论】:
-
请向我们展示代码,至少包含一个示例输入,以及 Node 加密版本和 Java 解密版本。我们需要一些东西在这里继续。
标签: java android node.js cryptography