2016-12-01 7 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; 

あなたはジャバスクリプト(NodeJS)にJavaのラップ機能を書き換えるために私を助けてもらえますか?

答えて

1

問題は修正されました。

問題はバッファを連結していました。演算子 "+"が正しくありません。デフォルトの方法を使用する必要があります。

Buffer.concat([initializationVector, encrypted])