When interacting with Java programs, the Java side uses AES 128-bit fill mode: Aes/cbc/pkcs5padding encryption method, the corresponding AES-128-CBC encryption method in the Nodejs can be corresponding, because there is the use of vector (iv), So the Createcipheriv method should be used in Nodejs, not createcipher.
In this kind of encryption and decryption calculation, the most important thing to pay attention to is the Chinese coding problem, otherwise it will be mined pit. I stepped out of the pit, the code can be run to send up under the environment Nodejs 4.4.6.
varCrypto = require (' crypto ')); /** * Encryption method * @param key Encryption key * @param IV vector * @param data required to encrypt * @returns string*/varEncrypt =function(Key, IV, data) {varcipher = Crypto.createcipheriv (' AES-128-CBC '), key, IV); varcrypted = cipher.update (data, ' UTF8 ', ' binary '); Crypted+ = cipher.final (' binary '); Crypted=NewBuffer (crypted, ' binary '). ToString (' base64 '); returncrypted;}; /** * Decryption method * @param key Decrypted key * @param IV vector * @param crypted ciphertext * @returns string*/varDecrypt =function(Key, IV, crypted) {crypted=NewBuffer (crypted, ' base64 '). toString (' binary '); varDecipher = Crypto.createdecipheriv (' AES-128-CBC '), key, IV); vardecoded = Decipher.update (crypted, ' binary ', ' UTF8 '); Decoded+ = decipher.final (' UTF8 '); returndecoded;}; varKey = ' 751f621ea5c8f930 '; Console.log (' Encrypted key: ', key.tostring (' hex ')));varIV = ' 2624750004598718 '; Console.log (' Encrypted IV: ', iv);vardata = "Hello, Nodejs." Demo AES-128-CBC encryption and decryption "; Console.log ("Data that needs to be encrypted:", data);varcrypted =Encrypt (key, IV, data); Console.log ("After data encryption:", crypted);varDec =Decrypt (key, IV, crypted); Console.log ("After the data is decrypted:", DEC);
Run the output result:
2624750004598718 data that needs to be encrypted: Hello, Nodejs. demo AES-128-CBC encryption and decryption data after encryption: 7L/q8zzhlani1toa/ra9b/ ezngiyto9dhtqoo105bntsto/qooctyljny6dvu1x+ Data decryption: Hello, Nodejs. Demo AES-128-CBC encryption and decryption
Original: http://www.01happy.com/nodejs-aes-128-cbc/
AES-128-CBC encryption and decryption in Nodejs