Nodejs Crypto module MD5 and HMAC encryption

Source: Internet
Author: User
Tags base64 cast5 hmac md5 encryption sha1



Nodejs Crypto module MD5 and HMAC encryption



In Nodejs, you can use the Crypto module to implement a variety of encryption and decryption processing, in the Crypto module contains similar MD5 or SHA-1 these hashing algorithms, we can implement the HMAC by the Crypto module.
What is an HMAC operation?
The Chinese meaning of the HMAC is: hash operation message authentication code; The operation uses the hashing algorithm to generate a message digest as output with a key and a message as input. The HMAC operation can be used to verify that two pieces of data match to verify that the data has not been tampered with.



In the crypto module, a class is defined for each cryptographic algorithm. You can use the Getciphers method to view all the cryptographic algorithms that can be used in Nodejs. The method returns an array that includes all the hashing algorithms that can be used in the Nodejs. Use the following method:


Const crypto = require(‘crypto‘);
Console.log(crypto.getCiphers());
/*
 Output is as follows
 [ ‘aes-128-cbc‘,
  ‘aes-128-cbc-hmac-sha1’,
  ‘aes-128-cbc-hmac-sha256’,
  ‘aes-128-ccm‘,
  ‘aes-128-cfb’,
  ‘aes-128-cfb1’,
  ‘aes-128-cfb8’,
  ‘aes-128-ctr‘,
  ‘aes-128-ecb’,
  ‘aes-128-gcm‘,
  ‘aes-128-ofb’,
  ‘aes-128-xts’,
  ‘aes-192-cbc’,
  ‘aes-192-ccm‘,
  ‘aes-192-cfb’,
  ‘aes-192-cfb1’,
  ‘aes-192-cfb8’,
  ‘aes-192-ctr‘,
  ‘aes-192-ecb’,
  ‘aes-192-gcm’,
  ‘aes-192-ofb’,
  ‘aes-256-cbc’,
  ‘aes-256-cbc-hmac-sha1’,
  ‘aes-256-cbc-hmac-sha256’,
  ‘aes-256-ccm’,
  ‘aes-256-cfb’,
  ‘aes-256-cfb1’,
  ‘aes-256-cfb8’,
  ‘aes-256-ctr’,
  ‘aes-256-ecb’,
  ‘aes-256-gcm’,
  ‘aes-256-ofb’,
  ‘aes-256-xts’,
  ‘aes128’,
  ‘aes192’,
  ‘aes256’,
  ‘bf‘,
  ‘bf-cbc’,
  ‘bf-cfb’,
  ‘bf-ecb’,
  ‘bf-ofb’,
  ‘blowfish’,
  ‘camellia-128-cbc’,
  ‘camellia-128-cfb’,
  ‘camellia-128-cfb1’,
  ‘camellia-128-cfb8’,
  ‘camellia-128-ecb’,
  ‘camellia-128-ofb’,
  ‘camellia-192-cbc’,
  ‘camellia-192-cfb’,
  ‘camellia-192-cfb1’,
  ‘camellia-192-cfb8’,
  ‘camellia-192-ecb’,
  ‘camellia-192-ofb’,
  ‘camellia-256-cbc’,
  ‘camellia-256-cfb’,
  ‘camellia-256-cfb1’,
  ‘camellia-256-cfb8’,
  ‘camellia-256-ecb’,
  ‘camellia-256-ofb’,
  ‘camellia128’,
  ‘camellia192’,
  ‘camellia256’,
  ‘cast’,
  ‘cast-cbc’,
  ‘cast5-cbc’,
  ‘cast5-cfb‘,
  ‘cast5-ecb’,
  ‘cast5-ofb’,
  ‘des’,
  ‘des-cbc’,
  ‘des-cfb’,
  ‘des-cfb1’,
  ‘des-cfb8’,
  ‘des-ecb’,
  ‘des-ede‘,
  ‘des-ede-cbc’,
  ‘des-ede-cfb’,
  ‘des-ede-ofb’,
  ‘des-ede3’,
  ‘des-ede3-cbc’,
  ‘des-ede3-cfb’,
  ‘des-ede3-cfb1’,
  ‘des-ede3-cfb8’,
  ‘des-ede3-ofb’,
  ‘des-ofb’,
  ‘des3’,
  ‘desx‘,
  ‘desx-cbc‘,
  ‘id-aes128-CCM’,
  ‘id-aes128-GCM’,
  ‘id-aes128-wrap‘,
  ‘id-aes192-CCM’,
  ‘id-aes192-GCM’,
  ‘id-aes192-wrap‘,
  ‘id-aes256-CCM’,
  ‘id-aes256-GCM’,
  ‘id-aes256-wrap‘,
  ‘id-smime-alg-CMS3DESwrap‘,
  ‘idea‘,
  ... 19 more items ]
*/


1. Hashing algorithm



Hash (also known as hash) algorithm, it is used to validate a piece of data before the data is blurred, or can also provide a check code for a large segment of data.
In Nodejs, in order to use this hashing algorithm, we first use the CreateHash method to create a hash object. Here's how to use it:



Crypto.createhash (params);



In the above method, you need to use a parameter whose parameter value is an algorithm that can be used in node. js, such as ' SHA1 ', ' MD5 ', ' sha512 ', and so on, to specify the hash algorithm that needs to be used, which returns the hash object that was created.



After you have created the hash object, you can create a digest by using the object's Update method. This method is used in the following ways:



Hash.update (data, [encoding]);



In the method above, the method needs to use two parameters, the first parameter is a required option, the parameter value is a buffer object or a string to specify the summary content, the second parameter encoding is used to specify the digest content to use the encoding format, can be specified as ' utf-8 ', ' ASCII ', or ' binary '. If you do not use the second argument, the data parameter value of the first parameter must be a buffer object, and we can add the summary content using multiple Updata methods before the digest is output.



After creating a hash object in the first step, the second step is to add the summary content, then the third step is to use the digest method of the hash object to output the digest content; Digest using the hash object
method, you can no longer append the summary content to the hash object, meaning that you are using the digest method as the output, you will not execute the Append content, so you cannot append content to the hash object.
Here's how to use it:



Hash.digest ([encoding]);



The method has a parameter, which is an optional value that indicates the encoding format used to specify the output digest, specifying the parameter value ' hex ', ' binary ', and ' base64 '. If this parameter is used, the digest method returns a summary of the string format, If this parameter is not used, then the digest method returns a buffer object.



2. MD5 algorithm
MD5 is the most widely used hash function in the computer domain (which can be called a hashing algorithm, a digest algorithm), which is used to ensure the integrity and consistency of the message.



Below we mainly use MD5 encryption as an example to understand the next encryption algorithm.
The MD5 algorithm has the following features:
1. compressibility: Any length of data, the calculated length of the MD5 value is fixed.
2. Easy to calculate: It is easy to figure out the MD5 value from the original data.
3. Anti-modification: Make any changes to the original data, even if only one byte is modified, the resulting MD5 value is very different.
4. Strong anti-collision: known raw data and its MD5 value, it is very difficult to find a pseudo-data with the same MD5 value.



MD5 's role is to allow bulk information to be compressed into a confidential format before signing a private key with a digital signature software (that is, converting any string of any length into a long hexadecimal number string).



Use the code as follows:


Const crypto = require(‘crypto‘);

Const str = ‘abc‘;

// Create a hash object
Const md5 = crypto.createHash(‘md5‘);

// Add summary content to the hash object
Md5.update(str);

// Use the digest method to output the summary content, without using the encoding format parameters. The output is a Buffer object.
// console.log(md5.digest());
// Output <Buffer 90 01 50 98 3c d2 4f b0 d6 96 3f 7d 28 e1 7f 72>

/ / Use the parameters of the encoding format, the output is a summary content in a string format
Console.log(md5.digest(‘hex‘)); // Output 900150983cd24fb0d6963f7d28e17f72


MD5 algorithm demo Real column:



Now let's take a look at the next demo, such as some login information, such as the password is stored directly in plaintext in the database is not safe, developers can directly through the naked eye to know, can be written down, so we need to use MD5 to encrypt, so we can do the following code encryption:




const crypto = require(‘crypto‘); var cryptoPassFunc = function(password) {
  const md5 = crypto.createHash(‘md5‘); return md5.update(password).digest(‘hex‘);
};

const password = ‘123456‘;
const croptyPass = cryptoPassFunc(password);

const croptyPass2 = cryptoPassFunc(password);

console.log(croptyPass); // e10adc3949ba59abbe56e057f20f883e  console.log(croptyPass2); // e10adc3949ba59abbe56e057f20f883e


As above Console.log output is through the MD5 encryption after the code;



The disadvantage of MD5 encryption only:



Through the above to MD5 encryption is indeed much better than clear text, at least a lot of people directly with the naked eye to see and remember, do not know how much password, but only to MD5 encryption also has shortcomings, such as the code using Console.log printed two times, after the code is the same, that is, the same plaintext password, After the encryption, output two times, the value of MD5 is the same. So it's not safe.



Add salt to the password:



What do you mean? is to insert a specific string at a specific location of the password, and then to encrypt the modified string MD5, the benefit is that each time the code is called, the inserted string is different, resulting in a different MD5 value. The code is as follows:


Const crypto = require(‘crypto‘);

Var saltPasswordFunc = function(password, salt) {

   // password plus salt
   Const saltPassword = password + ‘:‘ + salt;
   Console.log (‘original password: %s‘, password);
   Console.log (‘The password after salting: %s‘, saltPassword);


   Const md5 = crypto.createHash(‘md5‘);
   Const result = md5.update(saltPassword).digest(‘hex‘);
   Console.log (‘the value of md5 after the salt password is: %s‘, result);

};

Const password = ‘123456‘;

saltPasswordFunc(password, ‘abc‘);
/*
  The output is:
  Original password: 123456
  Password after adding salt: 123456: abc
  The value of md5 after adding the salt password is: 51011af1892f59e74baf61f3d4389092
*/

saltPasswordFunc(password, ‘def‘);
/*
  The output is:
  Original password: 123456
  Password after adding salt: 123456: def
  The value of md5 after adding the salt password is: 5091d17d6b08ba9a95ccef51f598b249
*/


Password encryption: Random salt value



If you add salt through the password, the security is relatively higher than using MD5 encryption alone, but there are problems, such as string concatenation algorithm in the string developers know, the second is the salt value fixed, that is, the concatenation of the string salt value is fixed; so there are some problems, So below we need a random number to generate a random salt value. This might be a higher security.



So the optimized code is as follows: (the optimization point is simply to generate a random number as the salt value)


Const crypto = require(‘crypto‘);

Var getRandomSalt = function() {
  // Use a six-digit random number
  Const randomSalt = Math.random().toString().slice(2, 8);
  Console.log(randomSalt);
  Return randomSalt;
};

Var saltPasswordFunc = function(password, salt) {
  // password plus salt
  Const saltPassword = password + ‘:‘ + salt;
  Console.log (‘original password: %s‘, password);
  Console.log (‘The password after salting: %s‘, saltPassword);


  Const md5 = crypto.createHash(‘md5‘);
  Const result = md5.update(saltPassword).digest(‘hex‘);
  Console.log (‘the value of md5 after the salt password is: %s‘, result);
};

Const password = ‘123456‘;

saltPasswordFunc(password, getRandomSalt());
/*
 The output is:
 Original password: 123456
 Password after salting: 123456: Randomly generate 6 digits
 The value of md5 after adding the salt password is: password + ‘: ‘ + randomly generate md5 value of 6 digits
*/

saltPasswordFunc(password, getRandomSalt());
/*
 The output is:
 Original password: 123456
 Password after salting: 123456: Randomly generate 6 digits
 The value of md5 after adding the salt password is: password + ‘: ‘ + randomly generate md5 value of 6 digits
*/


The advantage of this is that the salt value is different each time it is run, or when it is called a request, which results in a different password for each generated MD5 encryption.



3.  HMAC algorithm



The HMAC algorithm combines a hashing algorithm with a key to prevent damage to the integrity of the signature, which is similar to the addition of salt in the MD5 cipher mentioned above.
Before using the HMAC algorithm, we use the Createhmac method to create an HMAC object, which is created as follows:



Crypto.createhmac (params, key);



The method uses two parameters, the first parameter meaning is the algorithm used in node. js, such as ' SHA1 ', ' MD5 ', ' sha256 ', ' sha512 ' and so on, the method returns an Hmac object.
The key parameter value is a string that specifies a PEM-formatted key.



After the creation of the HMAC object, we also use an Update method to create a digest that uses the following example:



Hmac.update (data);



In the Update method, you use a parameter whose parameter value is a buffer object or a string that specifies the summary content. It is also possible to add summary content by using the Update method multiple times before being output.



The final step is to use the digest method of the HMAC object to output the digest content, and after using the digest method of the HMAC object, you can no longer append the digest to the HMAC object, that is, after you have used the digest method as the output, you cannot append content to the HMAC object. Here's how to use it:



Hmac.digest ([encoding]);



The method has a parameter, which is an optional value, which means that the encoding format used to specify the output digest can be specified with the parameter value ' hex ', ' binary ', and ' base64 '.
If this parameter is used, the digest method returns a summary of the string format, and if the parameter is not used, the digest method returns a buffer object.



Use a simple demo as below



Const crypto = require(‘crypto‘);

// Create a hmac object
Const hmac = crypto.createHmac(‘md5‘, ‘abc‘);

// Add summary content to the hmac object
Const up = hmac.update(‘123456‘);

/ / Use the digest method to output summary content

Const result = up.digest(‘hex‘);

Console.log(result); // 8c7498982f41b93eb0ce8216b48ba21d 


Nodejs Crypto module MD5 and HMAC encryption


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.