2016-12-01 51 views
3

我有一个用于AES加密和解密的Java算法,必须在JavaScript中实现解密。加密JAVA到node.js

public static final String ENCRYPTION_ALGORITHM = "AES/CBC/PKCS5Padding"; 
public static String wrap(String clearText, String key) { 
    byte[] iv = getIv(); 

    byte[] cipherText = encrypt(clearText, key, iv); 
    byte[] wrapped = new byte[iv.length + cipherText.length]; 
    System.arraycopy(iv, 0, wrapped, 0, iv.length); 
    System.arraycopy(cipherText, 0, wrapped, 16, cipherText.length); 

    return new String(Base64.encodeBase64(wrapped)); 
} 

private static byte[] encrypt(String clearText, String key, byte[] iv) { 
    try { 
     Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); 
     AlgorithmParameters params = AlgorithmParameters.getInstance("AES"); 
     params.init(new IvParameterSpec(iv)); 
     cipher.init(Cipher.ENCRYPT_MODE, getKey(key), params); 
     return cipher.doFinal(clearText.getBytes()); 
    } catch (GeneralSecurityException e) { 
     throw new RuntimeException("Failed to encrypt.", e); 
    } 
} 

private static SecretKeySpec getKey(String key) { 
    try { 
     return new SecretKeySpec(Hex.decodeHex(key.toCharArray()), "AES"); 
    } catch (DecoderException e) { 
     throw new RuntimeException("Failed to generate a secret key spec", e); 
    } 
} 

private static byte[] getIv() { 
    byte[] iv = new byte[16]; 
    new SecureRandom().nextBytes(iv); 

    return iv; 
} 

我已经写了JavaScript代码,但它产生不正确的结果:

var responseBody = JSON.stringify({"key":"215467ryhfdjeu8373t4"}); 
var initializationVector = crypto.randomBytes(16); 
key = new Buffer(key.substring(0,32), 'hex'); 
var cipher = crypto.createCipheriv('aes-128-cbc', key, iv); 
var encrypted = cipher.update(new Buffer(responseBody)) +  cipher.final('hex'); 
var encoded = new Buffer(initializationVector+encrypted, 'binary'); 
return encoded; 

能否请你帮我改写的Java包功能的JavaScript(的NodeJS)?

回答

1

问题已修复。

问题在于缓冲区的连接。运营商“+”不正确。需要使用默认方法。

Buffer.concat([initializationVector, encrypted])