nodejs和java密钥的生成
发布于 11 年前 作者 hf201429 12363 次预览 最后一次回复是 11 年前 来自 问答
Java代码:
public String encryption(String str)throws Exception{
try {
String KEY = "123456789";
byte[] enCriptSHA1String = enCriptSHA1(str);//SHA-1
String base64String = enBase64(enCriptSHA1String);//
System.out.println("1 "+base64String);
System.out.println("1.5 "+(str + "_" + base64String));
byte[] enCrptString = enCrpt((str + "_" + base64String).getBytes(), KEY.getBytes());//DESede
String base64StringRe = enBase64(enCrptString);
System.out.println("2 "+base64StringRe);
str=URLEncoder.encode(base64StringRe);
System.out.println("3 "+str);
} catch (Exception e) {
throw e;
}
return str;
}
public byte[] enCriptSHA1(String authenticator){
//加密的方式
final String Algorithm = "SHA-1";
//实例MessageDigest对象
MessageDigest md=null;
byte[] encode=null;
//加密数据转换成字节
byte[] bt=authenticator.getBytes();
try {
//SHA-1加密
md=MessageDigest.getInstance(Algorithm);
md.update(bt);
//二行制到字符串的转变
encode=md.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return encode;
}
public byte[] enCrpt(byte[] reqStr ,byte[] enkey){
//加密的方式
final String Algorithm = "DESede";
//加密后的数据
byte[] encoded = null;
//根据密钥加密对象
Cipher cipher = null;
//得到密钥
SecretKey secretKey = null;
try {
//得到密钥
secretKey = getSecretKey(enkey,Algorithm);
//加密
cipher = Cipher.getInstance(Algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//得到解加密后的数据
encoded = cipher.doFinal(reqStr);
} catch (Exception e) {
}
return encoded;
}
nodejs 代码:
function aesEncrypt(data) {
var cipher = crypto.createHash('sha1');
var encodeC = cipher.update(data).digest().toString('base64');
var ciphertwo = crypto.createCipher('des-ede',new Buffer('12345678'),0);
var endate = data+'_'+encodeC;
var en = ciphertwo.update(new Buffer(endate),'binary','base64')+ciphertwo.final('base64');
console.info("en: "+en+" ");
return en;
};
以上分别是我java和nodejs加密写法,为什么得出的结果不一样呢请大神指导下,看看哪里有错。
7 回复
看看能不能帮到你 http://blog.csdn.net/linminqin/article/details/19972751
谢谢,这个我看过,好像不行。。。
你的 getSecretKey 方法在哪里? 贴了个小片段,想试验一下都不行。。。。
我也在这里卡了一段时间,后来各种尝试终于解决了:(不太懂这个网站应该怎么格式代码,代码贴的比较丑,见谅了;)
AESCrypt.js
AESCryptTest.js
@gastrodia var iv = new Buffer(‘00000000000000000000000000000000’,‘hex’).toString(‘utf-8’); var encipher = crypto.createCipheriv(‘aes-128-cbc’, cryptkey, iv);
这个iv到底什么东西,兄弟解释下呗。。。先谢了。
@fish public SecretKey getSecretKey(byte[] reqKey,String Algorithm){ //创建密钥 SecretKey secretKey = new SecretKeySpec(reqKey, Algorithm); return secretKey; }
@hf201429 iv是起始变数,具体的意思你可以看这篇文章
http://ijecorp.blogspot.sg/2013/08/python-m2crypto-aes-encrypt-decrypt.html