节点js代码:
function AES_encrypt(){
var bKey = new Buffer('24Qn9974h50D9DNi', 'utf-8');
var bInput = new Buffer(‘test’, 'utf-8');
console.log(bKey.length);
var cipher = crypto.createCipher('AES-128-ECB',bKey);
//cipher.setAutoPadding(auto_padding=false);
var crypted = cipher.update(bInput,null,'base64');
crypted+=cipher.final('base64');
console.log(crypted);
return crypted;
}
获得结果:57b6b7oulw7eO5h7efZ9 / w ==
java代码:
main java:
String data = AES.encryptToBase64("test","24Qn9974h50D9DNi");
AES java:
public static String encryptToBase64(String data, String key){
try {
byte[] valueByte = encrypt(data.getBytes("utf-8"), key.getBytes("utf-8");
return new String(Base64.encode(valueByte));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("encrypt fail!", e);
}
}
public static byte[] encrypt(byte[] data, byte[] key) {
if(key.length!=16){
throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
}
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat,"AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, seckey);// 初始化
byte[] result = cipher.doFinal(data);
return result; // 加密
} catch (Exception e){
throw new RuntimeException("encrypt fail!", e);
}
}
获得结果:wA1JU6VxMaVl8Ck8pBrX8A ==
答案 0 :(得分:2)
使用crypto.createCipheriv解决问题, http://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv
答案 1 :(得分:0)
您需要将字符串"test"
填充到16个字节。我相信Java默认使用PKCS填充(但也有其他填充方案)。
String data = AES.encryptToBase64("test","24Qn9974h50D9DNi");