将Java AES加密代码移植到node.js

时间:2016-03-01 14:58:35

标签: javascript java node.js encryption meteor

我试图将以下AES加密代码移植到来自java的nodejs。

import java.security.MessageDigest;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class AESEncryption {

    public static void main(String[] args) {
        try {
            String key = "AsKUMDPsr7dfuk6fxgpfRdwm6de+MArf4SdAds9aq";
            byte[] hashedKey = MessageDigest.getInstance("SHA1").digest(key.getBytes("UTF-8"));
            SecretKeySpec keySpec = new SecretKeySpec(hashedKey, 2, 16, "AES"); // don't know how to port this to nodejs

            String plainText = "test123";
            Cipher cipher = Cipher.getInstance("AES");
            cipher1.init(1, keySpec);
            System.out.println(Base64.encodeBase64String(cipher.doFinal(plainText.getBytes("UTF-8"))));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

尝试编写以下nodejs代码,但加密文本不同。

crypto = require('crypto');

var key = 'AsKUMDPsr7dfuk6fxgpfRdwm6de+MArf4SdAds9aq';
var shasum = crypto.createHash('sha1');
shasum.update(key);
var encrypted_key = shasum.digest('').slice(2, 18).toString('utf8');
console.log(encrypted_key);

var plain_text = 'test123';
var cipher = crypto.createCipheriv('aes-128-ecb', encrypted_key, '');
var encrypted_text = cipher.update(plain_text, 'utf-8', 'base64');
encrypted_text += cipher.final('base64');
console.log(encrypted_text);

如何移植从字节数组创建的SecretKeySpec

1 个答案:

答案 0 :(得分:1)

var encrypted_key = shasum.digest('').slice(2, 18).toString('utf8');

应该是

var encrypted_key = shasum.digest().slice(2, 18);

获取Buffer并从中切片正确的字节。

安全注意事项:

绝不使用ECB mode 。它具有确定性,因此在语义上不安全。您应该至少使用CBCCTR等随机模式。最好对您的密文进行身份验证,以便像padding oracle attack这样的攻击是不可能的。这可以使用经过身份验证的模式(如GCM或EAX)或encrypt-then-MAC方案来完成。