Node.js中AES加密和其它語言不一致問題解決辦法

來源:互聯網
上載者:User

例子一:

這幾天被一個問題困擾著。Nodejs的AES加密和Java,C#加密出來的不一致。當然,這樣就不能解密了。糾結了許久:後來還是實在不行了,看了下原始碼,要不然還得繼續糾結下去。網上說,通常的nodejs AES和其他語言實現不一樣。好吧~~或許吧。
nodejs的crypto模組。
複製代碼 代碼如下:
var crypto = require('crypto');

    var data = "156156165152165156156";
    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-ecb';
    var key = '78541561566';
    var clearEncoding = 'utf8';
    //var cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    var cipherEncoding = 'base64';
/*加密*/
    var cipher = crypto.createCipher(algorithm, key);

    var cipherChunks = [];
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));
/*解密*/
    var decipher = crypto.createDecipher(algorithm, key);
    var plainChunks = [];
    for (var i = 0;i < cipherChunks.length;i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));

    }
    plainChunks.push(decipher.final(clearEncoding));
    console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));
的確,沒錯~~加密解密成功。但是和java,C#中加密出來的不一樣啊。神啊。我想,大家都在這裡糾結著吧~~對不對。其實只要加個向量,就可以和一致了。網上搜尋出來的資源太少。才讓自己糾結那麼久。好吧,正確代碼是:
複製代碼 代碼如下:
var crypto = require('crypto');

    var data = "156156165152165156156";
    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-ecb';
    var key = '78541561566';
    var clearEncoding = 'utf8';
    var iv = "";
    //var cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    var cipherEncoding = 'base64';
    var cipher = crypto.createCipheriv(algorithm, key,iv);

    var cipherChunks = [];
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));

    var decipher = crypto.createDecipheriv(algorithm, key,iv);
    var plainChunks = [];
    for (var i = 0;i < cipherChunks.length;i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));

    }
    plainChunks.push(decipher.final(clearEncoding));
    console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));
對比發現,加密出來是一致的。好吧,結貼~~~我恨你,浪費了我一天時間。


例子二:

工作中遇到nodejs端通過aes加密,安卓用戶端java解密,同意nodejs也需要解密安卓用戶端加密過來的內容,發現兩個加密結果不一樣,查詢資料發現java端需要對密鑰za再MD5加密一遍,以下是aes ecb加密的內容,如果是cbc也同樣需要對秘鑰MD5加密:


nodejs:
複製代碼 代碼如下:
/**
 * aes加密
 * @param data
 * @param secretKey
 */ 
encryptUtils.aesEncrypt = function(data, secretKey) { 
    var cipher = crypto.createCipher('aes-128-ecb',secretKey); 
    return cipher.update(data,'utf8','hex') + cipher.final('hex'); 


/**
 * aes解密
 * @param data
 * @param secretKey
 * @returns {*}
 */ 
encryptUtils.aesDecrypt = function(data, secretKey) { 
    var cipher = crypto.createDecipher('aes-128-ecb',secretKey); 
    return cipher.update(data,'hex','utf8') + cipher.final('utf8'); 


java:
複製代碼 代碼如下:
package com.iofamily.util; 

import java.security.MessageDigest; 

import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 

/**
 * AES加密,與Nodejs 保持一致
 * @author lmiky
 * @date 2014-2-25
 */ 
public class AESForNodejs { 
    public static final String DEFAULT_CODING = "utf-8"; 

    /**
     * 解密
     * @author lmiky
     * @date 2014-2-25
     * @param encrypted
     * @param seed
     * @return
     * @throws Exception
     */ 
    private static String decrypt(String encrypted, String seed) throws Exception { 
        byte[] keyb = seed.getBytes(DEFAULT_CODING); 
        MessageDigest md = MessageDigest.getInstance("MD5"); 
        byte[] thedigest = md.digest(keyb); 
        SecretKeySpec skey = new SecretKeySpec(thedigest, "AES"); 
        Cipher dcipher = Cipher.getInstance("AES"); 
        dcipher.init(Cipher.DECRYPT_MODE, skey); 

        byte[] clearbyte = dcipher.doFinal(toByte(encrypted)); 
        return new String(clearbyte); 
    } 

    /**
     * 加密
     * @author lmiky
     * @date 2014-2-25
     * @param content
     * @param key
     * @return
     * @throws Exception
     */ 
    public static String encrypt(String content, String key) throws Exception { 
        byte[] input = content.getBytes(DEFAULT_CODING); 

        MessageDigest md = MessageDigest.getInstance("MD5"); 
        byte[] thedigest = md.digest(key.getBytes(DEFAULT_CODING)); 
        SecretKeySpec skc = new SecretKeySpec(thedigest, "AES"); 
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
        cipher.init(Cipher.ENCRYPT_MODE, skc); 

        byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; 
        int ctLength = cipher.update(input, 0, input.length, cipherText, 0); 
        ctLength += cipher.doFinal(cipherText, ctLength); 

        return parseByte2HexStr(cipherText); 
    } 

    /**
     * 字串轉位元組數組
     * @author lmiky
     * @date 2014-2-25
     * @param hexString
     * @return
     */ 
    private static byte[] toByte(String hexString) { 
        int len = hexString.length() / 2; 
        byte[] result = new byte[len]; 
        for (int i = 0; i < len; i++) { 
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); 
        } 
        return result; 
    } 

    /**
     * 位元組轉16進位數組
     * @author lmiky
     * @date 2014-2-25
     * @param buf
     * @return
     */ 
    private static String parseByte2HexStr(byte buf[]) { 
        StringBuffer sb = new StringBuffer(); 
        for (int i = 0; i < buf.length; i++) { 
            String hex = Integer.toHexString(buf[i] & 0xFF); 
            if (hex.length() == 1) { 
                hex = '0' + hex; 
            } 
            sb.append(hex); 
        } 
        return sb.toString(); 
    } 

    public static void main(String[] args) throws Exception { 
        System.out.println(AESForNodejs.encrypt("fsadfsdafsdafsdafsadfsadfsadf", "1234fghjnmlkiuhA")); 
        System.out.println(AESForNodejs.decrypt("5b8e85b7a86ad15a275a7cb61fe4c0606005e8741f68797718a3e90d74b5092a", "1234fghjnmlkiuhA")); 
    } 
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.