Solution to AES encryption and other language inconsistency problems in Node.js

Source: Internet
Author: User
Tags base64 decrypt join md5 stringbuffer

  This article mainly introduces the solution of AES encryption and other language inconsistency problems in node.js, for example, when communicating with C # and Java languages, the friends you need can refer to the following

Example one:   is plagued by a problem these days. Nodejs AES Encryption and java,c# encryption out of the inconsistency. Of course, this will not be decrypted. Tangled for a long time: Later or really die, looked at the source code, or else it has to continue to tangle down. On the Internet, it is common to say that Nodejs AES is different from other language implementations. Well, maybe. Nodejs's crypto module.     Code as follows: 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 are uncommented, the final cleartext is wrong.     var cipherencoding = ' base64 '; /* Encryption/*     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 (")); /* decryption */    var decipher = CRypto.createdecipher (algorithm, key);     var plainchunks = [];     for (var i = 0;i < cipherchunks.length;i++) {      Plainchunks.push (decipher.update ciphe Rchunks[i], cipherencoding, clearencoding));      }     Plainchunks.push (decipher.final (clearencoding));     Console.log ("UTF8 plaintext deciphered:" + plainchunks.join ('));   Indeed, yes ~ ~ Encryption decryption succeeded. But it's not the same as the java,c# encryption. Oh, God. I think, we are all entangled in here ~ ~ Right. In fact, just add a vector, you can and consistent. There are too few resources on the Internet to search out. Just let oneself struggle for so long. OK, the correct code is:   Code as follows: 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 are 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 ciphe Rchunks[i], cipherencoding, clearencoding));      }     Plainchunks.push (decipher.final (clearencoding));     Console.log ("UTF8 plaintext deciphered:" + plainchunks.join ('));   Contrast found that encryption is consistent. OK, knot paste ~ ~ ~ I hate you, wasted my day.     Example Two:   work encountered Nodejs end through AES encryption, Android client Java decryption, agreed to Nodejs also need to decrypt the content of Android client encryption, found two encryption results are different, Query data found that the Java side needs to encrypt the key za MD5 again, the following is the AES ECB encrypted content, if it is CBC also need to encrypt the secret key MD5:    NODEJS:     Code as follows:/**   * AES Encryption    * @param data   * @param secretkey& nbsp  */  Encryptutils.aesencrypt = function (data, Secretkey) {      var cipher = Crypto.createciphe R (' Aes-128-ecb ', secretkey);       Return cipher.update (data, ' UTF8 ', ' hex ') + cipher.final (' hex ');      /**   * AES decryption    * @param data   * @param secretkey   * @ret Urns {*}   */  Encryptutils.aesdecrypt = function (data, Secretkey) {      var cipher = cry Pto.createdecipher (' Aes-128-ecb ', secretkey);       Return cipher.update (data, ' hex ', ' UTF8 ') + cipher.final (' UTF8 ');  }     Java: Code is as follows: Package com.iofamily.util;     Import java.security.MessageDigest;     Import Javax.crypto.Cipher;   Import Javax.crypto.spec.SecretKeySpec;    /**   * AES encryption, consistent with Nodejs    * @author lmiky   * @date 2014-2-25   */  public class Aesfornodejs {      Publi C static final String default_coding = "Utf-8";        /**       * decryption        * @author lmiky    &nbs P  * @date 2014-2-25       * @param encrypted       * @param seed       * @return        * @throws exception       */      PRI Vate static string decrypt (string encrypted, string seed) throws Exception {          byte[] Key b = 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);      }        /**       * encryption        * @author lmiky       * @date 2014-2-25       * @param content       * @ Param key       * @return        * @throws exception       */& nbsp     public static string encrypt (string content, String key) throws Exception {        &NBS P 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);      }        /**       * string goto byte array        * @a Uthor lmiky       * @date 2014-2-25       * @param hexstring      & nbsp;* @return        */      private static byte[] ToByte (String hexstring) {&nbsP         int len = Hexstring.length ()/2;           byte[] result = new Byte[len];           for (int i = 0; i < len; i++) {              RES Ult[i] = integer.valueof (hexstring.substring (2 * I, 2 * i + 2). Bytevalue ();          }           return result;      }        /**       * byte ext 16 array        * @ Author lmiky       * @date 2014-2-25       * @param buf        * @return        */      private static String Parsebyte2hexstr (byte buf[]) {  &N Bsp       StringBuffer sb = new StringBuffer ();           for (int i = 0; i < buf.length i++) {            &NB Sp 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 (" 5b8e85b7a86ad15a275a7cb61fe4c0606005e8741f68797718a3e90d7 4b5092a "," 1234fghjnmlkiuhA "));      }  }    

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.