我试图将以下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
?
答案 0 :(得分:1)
var encrypted_key = shasum.digest('').slice(2, 18).toString('utf8');
应该是
var encrypted_key = shasum.digest().slice(2, 18);
获取Buffer
并从中切片正确的字节。
绝不使用ECB mode 。它具有确定性,因此在语义上不安全。您应该至少使用CBC或CTR等随机模式。最好对您的密文进行身份验证,以便像padding oracle attack这样的攻击是不可能的。这可以使用经过身份验证的模式(如GCM或EAX)或encrypt-then-MAC方案来完成。