2014-01-10 55 views
0

節點js代碼:AES-128-ECB - 節點JS和java的不一致加密結果

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; 
} 

GET結果:57b6b7oulw7eO5h7efZ9/W ==

Java代碼:

主要的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); 
    } 
} 

GET結果:wA1JU6VxMaVl8Ck8pBrX8A ==

+0

實際上並沒有看它很多事,但要記住的是,節點自動墊你加密你的東西。 http://nodejs.org/api/crypto.html#crypto_cipher_setautopadding_auto_padding_true – Epicblood

+0

謝謝您的回覆! java補位節點沒有,這是我癡迷 – user3180646

回答

0

您需要墊字符串"test" 16個字節。我相信Java默認使用PKCS填充(但也有其他填充方案)。

String data = AES.encryptToBase64("test","24Qn9974h50D9DNi"); 
+0

謝謝你的回覆,我需要以java加密的結果爲目標,用js實現節點,還有其他辦法嗎? – user3180646