我有以下要移植到Node.js的Java代码:
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class ChiperExample {
private static final String CIPHER_ALGORITHM = "AES";
public static String decrypt(final String encryptedMessage, final String hexEncodedKey)
throws InvalidKeyException,
InvalidAlgorithmParameterException,
NoSuchAlgorithmException,
NoSuchPaddingException,
IllegalBlockSizeException,
BadPaddingException {
byte[] key = DatatypeConverter.parseHexBinary(hexEncodedKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, CIPHER_ALGORITHM);
Cipher encryptCipher = Cipher.getInstance(CIPHER_ALGORITHM);
encryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = encryptCipher.doFinal(DatatypeConverter.parseHexBinary(encryptedMessage));
return new String(decrypted);
}
public static String encrypt(final String cleanMessage, final String hexEncodedKey)
throws InvalidKeyException,
InvalidAlgorithmParameterException,
NoSuchAlgorithmException,
NoSuchPaddingException,
IllegalBlockSizeException,
BadPaddingException {
byte[] key = DatatypeConverter.parseHexBinary(hexEncodedKey);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, CIPHER_ALGORITHM);
Cipher encryptCipher = Cipher.getInstance(CIPHER_ALGORITHM);
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = encryptCipher.doFinal(cleanMessage.getBytes());
String encryptedHexString = DatatypeConverter.printHexBinary(encrypted);
return encryptedHexString.toLowerCase();
}
}
这是我尝试使用流使用Node.js
const crypto = require('crypto');
var decipher = crypto.createDecipher('aes128', 'password');
decipher.setAutoPadding(false);
var msisdn = decipher.update('a6ee2954cb6248dc6bc48ca2109fa1d8', 'hex', 'utf8');
msisdn += decipher.final('utf8');
console.log(msisdn)
这两个版本均产生正确长度的相同输出(与输入长度相同),但是此输出与在相同输入缓冲区上操作的Java版本的解密器所产生的明文不同。如何设置像上面配置的Java解密那样的Node.js解密?