用js和Java加密

时间:2019-07-06 07:10:04

标签: javascript java encryption

我尝试加密client(java)和server(js)中的某些字符串。 但是这两种方法的结果是不同的。 是什么原因造成的?

JAVA:

private static byte[] iv = "EmdadsSecretKeys".getBytes();

public static String encrypt(String content) throws Exception {
    byte[] input = content.getBytes("utf-8");
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String key = "ASDFasdf18448348";
    byte[] thedigest = md.digest(key.getBytes("utf-8"));
    SecretKeySpec skc = new SecretKeySpec(thedigest, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("UTF-8"), "AES"), new IvParameterSpec(iv));
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
    int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
    ctLength += cipher.doFinal(cipherText, ctLength);
    return DatatypeConverter.printHexBinary(cipherText);
}

JS:

var crypto = require('crypto');
exports.crypto = function (data) {
var key = "ASDFasdf18448348" ;
var iv = "EmdadsSecretKeys" ;
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
var crypted = cipher.update(data, 'utf8', 'binary');
var cbase64  =   new Buffer(crypted, 'binary').toString('base64');
crypted += cipher.final('binary');
crypted = new Buffer(crypted, 'binary').toString('base64');
return crypted;
}

0 个答案:

没有答案