[Reprint] Cryptographic algorithm library CRYPTO--NODEJS middleware series

Source: Internet
Author: User

Label:

The zero-based NODEJS series article will show you how to benefit JavaScript as a server-side script through NODEJS Framework web development. The NODEJS framework is a V8-based engine and is the fastest JavaScript engine available today. The Chrome browser is based on V8, and opening 20-30 pages is a smooth one. The NODEJS Standard Web Development Framework Express helps us quickly build web sites that are more efficient than PHP and have a lower learning curve. Very suitable for small websites, personalization sites, our own Geek website!!

About the author

    • Zhang Dan (Conan), entrepreneur, programmer (Java,r,javascript)
    • Weibo: @Conan_Z
    • Blog:http://blog.fens.me
    • Email: [Email protected]

Reprint please specify the source:
http://blog.fens.me/nodejs-crypto/

Objective

Cryptography is one of the most basic technologies of Internet application, which ensures the security of data. The security definition is multidimensional, the security of the login password can be ensured by the non-reversible hash algorithm, and the security of the data storage can be ensured through the asymmetric encryption algorithm, and the digital signature can verify whether the data has been tampered with during transmission.

We want to do Internet applications, data security is a problem that cannot be ignored. Otherwise, such as CSDN 1 million user plaintext password is leaked things, Ctrip, 1 million user personal information leaks things.

The Crypto Library of node. JS provides a variety of cryptographic algorithms that make it very easy to use cryptography to solve problems in application development.

Directory

    1. Crypto Introduction
    2. Hash algorithm
    3. HMAC algorithm
    4. Encryption and decryption algorithms
    5. Signature and validation algorithms
    6. Salt algorithm
    7. Program code
1. Crypto Introduction

The crypto library is packaged and distributed with the Nodejs kernel, which provides encryption, decryption, signing, verification and other functions. Crypto uses the OpenSSL library to implement its encryption technology, which provides a series of hashing methods in OpenSSL, including encapsulation of HMAC, cipher, decipher, signature, and validation methods.

Crypto Official document: http://nodejs.org/api/crypto.html

2. Hash algorithm

A hashing algorithm, which refers to a binary value of any length that is mapped to a shorter fixed-length binary value, a small binary value called a hash value. A hash value is a unique and extremely compact numeric representation of a piece of data. If you hash a clear text and even change only one letter of the paragraph, subsequent hashes will produce different values. To find two different inputs that hash the same value, it is not possible to compute, so the hash value of the data can verify the integrity of the data. Typically used for quick find and encryption algorithms.

Usually we use the hash algorithm to encrypt the login password, the typical hashing algorithm includes ' md5′, ' sha ', ' sha1′, ' sha256′, ' sha512′, ' Rsa-sha '. Let's do the test of the algorithm.

System environment

    • Win7 64bit
    • nodejs:v0.10.31
    • npm:1.4.23

Create a project

~ cd D:\workspace\javascript>~ D:\workspace\javascript>mkdir nodejs-crypto && cd nodejs-crypto

New file Hash.js, print out the supported hash algorithm.

~ vi hash.jsvar crypto = require(‘crypto‘);  # 加载crypto库console.log(crypto.getHashes()); # 打印支持的hash算法

Run the program

~ node hash.js[ ‘DSA‘,  ‘DSA-SHA‘,  ‘DSA-SHA1‘,  ‘DSA-SHA1-old‘,  ‘RSA-MD4‘,  ‘RSA-MD5‘,  ‘RSA-MDC2‘,  ‘RSA-RIPEMD160‘,  ‘RSA-SHA‘,  ‘RSA-SHA1‘,  ‘RSA-SHA1-2‘,  ‘RSA-SHA224‘,  ‘RSA-SHA256‘,  ‘RSA-SHA384‘,  ‘RSA-SHA512‘,  ‘dsaEncryption‘,  ‘dsaWithSHA‘,  ‘dsaWithSHA1‘,  ‘dss1‘,  ‘ecdsa-with-SHA1‘,  ‘md4‘,  ‘md4WithRSAEncryption‘,  ‘md5‘,  ‘md5WithRSAEncryption‘,  ‘mdc2‘,  ‘mdc2WithRSA‘,  ‘ripemd‘,  ‘ripemd160‘,  ‘ripemd160WithRSA‘,  ‘rmd160‘,  ‘sha‘,  ‘sha1‘,  ‘sha1WithRSAEncryption‘,  ‘sha224‘,  ‘sha224WithRSAEncryption‘,  ‘sha256‘,  ‘sha256WithRSAEncryption‘,  ‘sha384‘,  ‘sha384WithRSAEncryption‘,  ‘sha512‘,  ‘sha512WithRSAEncryption‘,  ‘shaWithRSAEncryption‘,  ‘ssl2-md5‘,  ‘ssl3-md5‘,  ‘ssl3-sha1‘,  ‘whirlpool‘ ]

We see a lot of support hash, exactly how to choose the right, I also say not clear. With my understanding of the algorithm, I will use encryption to calculate the time and length of the code to do the basis of choice. Here is a simple comparison of several common algorithms.

Edit Hash.js File

~ vi hash.js///////////////////////////// Hash算法///////////////////////////var crypto = require(‘crypto‘)    ,fs = require(‘fs‘);function hashAlgorithm(algorithm){    var s1 = new Date();    var filename = "package.json";    var txt = fs.ReadStream(filename);    var shasum = crypto.createHash(algorithm);    txt.on(‘data‘, function(d) {        shasum.update(d);    });    txt.on(‘end‘, function() {        var d = shasum.digest(‘hex‘);        var s2 = new Date();        console.log(algorithm+‘,‘+(s2-s1) +‘ms,‘+ d);    });}function doHash(hashs){    hashs.forEach(function(name){        hashAlgorithm(name);    })}//var algs = crypto.getHashes();var algs = [ ‘md5‘,‘sha‘,‘sha1‘,‘sha256‘,‘sha512‘,‘RSA-SHA‘,‘RSA-SHA1‘,‘RSA-SHA256‘,‘RSA-SHA512‘];doHash(algs);

Run the program

~ node hash.jsmd5,6ms,85cd416f811574bd4bdb61b241266670sha,18ms,b1fc6647fa4fdb4b1b394f8dc7856ac140e2fbdbsha1,20ms,0777e65066dca985569fa892fa88e21b45dc656dsha256,21ms,5e4aea76f93ee87f422fcbd9458edad0e33ddf256d5d93bcc47977e33cb1654csha512,23ms,94249ec2f83b006354774dd8f8ec81125ea9e1e00f94393d8b20bbd7678e63db53fab6af125e139f9257fd7dbb6c69474e443d059903a9cb2dded03a94c8143RSA-SHA,24ms,b1fc6647fa4fdb4b1b394f8dc7856ac140e2fbdbRSA-SHA1,25ms,0777e65066dca985569fa892fa88e21b45dc656dRSA-SHA256,26ms,5e4aea76f93ee87f422fcbd9458edad0e33ddf256d5d93bcc47977e33cb1654cRSA-SHA512,26ms,94249ec2f83b006354774dd8f8ec81125ea9e1e00f94393d8b20bbd7678e63db53fab6af125e139f9257fd7dbb6c69474e4433d059903a9cb2dded03a94c8143

The output is separated by commas, which are the algorithm name, time, and ciphertext. The most common MD5, the shortest length of the ciphertext, the least computational time; Sha and SHA1 are close, sha512 ciphertext is the longest, and the computation time is the longest.

Because MD5 already has a large number of dictionary libraries, for the security level of the general site with SHA1 Bar, if the security level is very high, CPU configuration is also very cow, you can consider using SHA512.

3. HMAC algorithm

HMAC is a key-related hash operation message authentication code (hash-based message Authentication code), the HMAC operation takes advantage of a hashing algorithm, takes a key and a message as input, generates a message digest as output. HMAC can effectively prevent some similar MD5 such as rainbow table attacks, such as some common passwords directly MD5 into the database, may be reverse-cracked.

Defining an HMAC requires a cryptographic hash function (denoted as h, which can be MD5 or SHA-1) and a key K. We use B to represent the number of bytes in the data block. (The partition data block of the hash function mentioned above is b=64), and L is used to represent the output data bytes of the hash function (l=20 in L=16,sha-1 in MD5). The length of the authentication key can be any positive integer value that is less than or equal to the word size of the data block. If the key length used in the application is larger than B, it is first used with the hash function h and then the L-length string with the H output as the actual key used in the HMAC. In general, the recommended minimum key k length is l bytes.

Since HMAC uses hash functions, we also choose several of the above algorithms for testing. New file Hmac.js.

~ VI hmac.js/////////////////////////////HMAC algorithm///////////////////////////var crypto = require (' crypto '), FS = Require    (' fs '); function Hmacalgorithm (Algorithm,key) {var S1 = new Date ();    var filename = "Package.json"; var txt = fs.    Readstream (filename);    var shasum = Crypto.createhmac (Algorithm,key);    Txt.on (' Data ', function (d) {shasum.update (d);    });        Txt.on (' End ', function () {var d = shasum.digest (' hex ');        var s2 = new Date ();    Console.log (algorithm+ ', ' + (S2-S1) + ' MS, ' + d '); });}    function Dohmac (hashs,key) {Console.log ("\nkey:%s", key);    Console.log ("============================");    Hashs.foreach (function (name) {hmacalgorithm (Name,key); })}//var ALGs = Crypto.gethashes () var ALGs = [' MD5 ', ' sha ', ' SHA1 ', ' sha256 ', ' sha512 ', ' Rsa-sha ', ' rsa-sha1 ', ' rsa-sha256 ' ', ' rsa-sha512 '];//short key test settimeout (function () {Dohmac (ALGs, "abc"),},1)//Long key test settimeout (function () {var key = " jifdkd;adkfaj^&fjdifefdafda,ijjifdkd;adkfaj^&FJDIFEFDAFDALJIFDKD;ADKFAJ^&FJDIFEFDAFDA "; Dohmac (Algs,key);},2*1000)

Run the program

~ Node Hmac.jskey:abc============================md5,6ms,bf106a077abcfa0fffe6ec0da039545bsha,6ms, A43a00981346ac64bb7b6fb0641b72a101fb04a5sha1,6ms,aead69a72da77d0615a854dda1086d885807574asha256,7ms, 98ac955cb2205ba01a6337951d0ed3fd9b68753544cf81275eced365da57fc5dsha512,8ms, 054f37e34b55a19e64a7f88fb60b1122dc0a30e9864ca28d01d61115b13c74de292ab66e85bf007e1a463a52d7c30fdff174618ef954401bc9c2c3318 E762c8frsa-sha,10ms,a43a00981346ac64bb7b6fb0641b72a101fb04a5rsa-sha1,11ms, Aead69a72da77d0615a854dda1086d885807574arsa-sha256,12ms, 98AC955CB2205BA01A6337951D0ED3FD9B68753544CF81275ECED365DA57FC5DRSA-SHA512,13MS, 054f37e34b55a19e64a7f88fb60b1122dc0a30e9864ca28d01d61115b13c74de292ab66e85bf007e1a463a52d7c30fdff174618ef954401bc9c2c3318 e762c8fkey:jifdkd;adkfaj^&fjdifefdafda,ijjifdkd;adkfaj^&fjdifefdafdaljifdkd;adkfaj^&fjdifefdafda== ==========================MD5,5MS,164A8FEE6E37BB3E40A9D5DFF5C2FD66SHA,5MS, Ba06f536856553c3756aa36254a63ef35e225d38sha1,7ms,f3a89b0a5ee8a55c2bb6a861748d43e9d44dc489sha256,7ms,f2df911f40e74b2b9bb3d53a7ca4b78d438d511e015d4b50431eaea65339380dsha512,8ms, 5b4b57386b1fcc4f1945c47788bf38c013e1cde356fc15e1f946e6bf6738b5dc52ecf17b3ddc80b2ff21f985a1a707df9357fe305e9aa143da073d2ca Fd794dcrsa-sha,11ms,ba06f536856553c3756aa36254a63ef35e225d38rsa-sha1,12ms, F3a89b0a5ee8a55c2bb6a861748d43e9d44dc489rsa-sha256,14ms, F2df911f40e74b2b9bb3d53a7ca4b78d438d511e015d4b50431eaea65339380drsa-sha512,16ms, 5b4b57386b1fcc4f1945c47788bf38c013e1cde356fc15e1f946e6bf6738b5dc52ecf17b3ddc80b2ff21f985a1a707df9357fe305e9aa143da073d2ca Fd794dc

By comparing the short key and the long key, there are some effects on the long-coded algorithm. Since HMAC has a second parameter key, it will be more secure than the individual hash encryption login password.

For the website login password design, we can make 2 field storage, with password word Gencun ciphertext, passkey field store key, the algorithm directly encapsulated inside the program.

{  username: ‘xxxx‘  password: ‘aead69a72da77d0615a854dda1086d885807574a‘,  passkey:‘abc‘}

Even if the database is attacked, the hacker just took the ciphertext and key, the password plaintext has not been leaked. And without knowing the encryption algorithm, it is difficult to attack through the rainbow table.

4. Encryption and decryption algorithms

For the login password, it is not necessary to consider the decryption, usually with an irreversible algorithm, such as Md5,sha-1. However, for data with security requirements, we need to encrypt the storage, and then decrypt the use, then we need to use a reversible encryption algorithm. For this key-based algorithm, it can be divided into symmetric and asymmetric encryption.

    • The principle of symmetric encryption algorithm is easy to understand, the communication side with KEK encryption plaintext, the other party received after the same key to decrypt the plaintext can be obtained.
    • Asymmetric encryption algorithm that uses two pairs of keys that are completely different but perfectly matched: the public key and the private key. When encrypting a file using an asymmetric encryption algorithm, the process of encrypting and decrypting the plaintext is accomplished only by using a matching pair of public and private keys.

For this type of operation, the crypto package also provides a large number of algorithmic support. Create a new file Cipher.js and print out the supported algorithms.

~ vi cipher.jsvar crypto = require(‘crypto‘);console.log(crypto.getCiphers());

Run the program

~ Node cipher.js[' CAST-CBC ', ' AES-128-CBC ', ' aes-128-cbc-hmac-sha1 ', ' 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-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-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 ', ' Camelli ' A-128-CBC ', ' camellia-128-cfb ', ' camellia-128-cfb1 ', ' camellia-128-cfb8 ', ' CAMELLIA-128-ECB ', ' camellia-128-ofb ', ' C AMELLIA-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 ', ' d ES-CBC ', ' des-cfb ', ' des-cfb1 ', ' des-cfb8 ', ' DES-ECB ', ' des-ede ', ' DES-EDE-CBC ', ' des-ede-cfb ', ' des-ede-ofb ', ' d Es-ede3 ', ' DES-EDE3-CBC ', ' des-ede3-cfb ', ' des-ede3-cfb1 ', ' des-ede3-cfb8 ', ' des-ede3-ofb ', ' des-ofb ', ' des3 ', ' de SX ', ' DESX-CBC ', ' id-aes128-gcm ', ' id-aes192-gcm ', ' id-aes256-gcm ', ' idea ', ' IDEA-CBC ', ' idea-cfb ', ' IDEA-ECB ', ' IDEA-OFB ', ' RC2 ', ' RC2-40-CBC ', ' RC2-64-CBC ', ' RC2-CBC ', ' rc2-cfb ', ' RC2-ECB ', ' rc2-ofb ', ' RC4 ', ' rc4-40 ', ' rc4-' Hmac-md5 ', ' seed ', ' SEED-CBC ', ' seed-cfb ', ' SEED-ECB ', ' SEED-OFB ']

Similarly, in the face of such a large pile of algorithms, there is no way to know how to choose. I still use encryption and decryption of the calculation time as a reference indicator, select a few common algorithms to test.

Cryptographic decryption algorithm///////////////////////////var crypto = require (' crypto '), FS = require (' FS ');//    Cryptographic function cipher (algorithm, key, BUF, CB) {var encrypted = "";    var CIP = Crypto.createcipher (algorithm, key);    encrypted + = Cip.update (buf, ' binary ', ' hex ');    encrypted + = cip.final (' hex '); CB (encrypted);}    Decrypt function decipher (algorithm, key, ENCRYPTED,CB) {var decrypted = "";    var decipher = Crypto.createdecipher (algorithm, key);    decrypted + = Decipher.update (encrypted, ' hex ', ' binary ');    decrypted + = decipher.final (' binary '); CB (decrypted);} function Cipherdecipherfile (Filename,algorithm, key) {fs.readfile (filename, "Utf-8", function (err, data) {if (E        RR) throw err;        var S1 = new Date ();            Cipher (algorithm, key,data,function (encrypted) {var s2 = new Date ();            Console.log (' cipher: ' +algorithm+ ', ' + (S2-S1) + ' MS '); Decipher (algorithm, key,encrypted,function (TXT) {var s3 = new Date ();            Console.log (' Decipher: ' +algorithm+ ', ' + (S3-S2) + ' MS ');//Console.log (TXT);        });    }); });} Console.log (Crypto.getciphers ()); var ALGs = [' Blowfish ', ' AES-256-CBC ', ' cast ', ' des ', ' des3 ', ' idea ', ' RC2 ', ' RC4 ', ' Seed '];var key = "abc"; var filename = "book.pdf";//"Package.json"; Algs.foreach (function (name) {Cipherdecipherfile ( Filename,name,key);})

Run the program

~ node cipher.jscipher:blowfish,46msdecipher:blowfish,95mscipher:des,67msdecipher:des,104mscipher:idea,54msdecipher:idea,88mscipher:rc4,16msdecipher:rc4,44mscipher:des3,158msdecipher:des3,193mscipher:aes-256-cbc,19msdecipher:aes-256-cbc,47mscipher:cast,46msdecipher:cast,82mscipher:seed,64msdecipher:seed,98mscipher:rc2,104msdecipher:rc2,99ms

Output altogether 3 columns, the first column, cipher (encryption), decipher (decryption), the second column, the algorithm name, and the third column is the calculation time.

In the selected algorithms, RC4 and AES-256-CBC is a good performance algorithm, encryption and decryption time is relatively short, encryption time: decryption time =1:3; other algorithms, the overall time is relatively long, and some encryption time: decryption time =1:1. So, how to choose the algorithm, another standard depends on the business requirements. If the number of decryption operations on the business is much greater than the number of cryptographic operations, and is calculated on the server, then we'd better find the encryption time: decryption time =n:1,n>1 algorithm; If encryption is on the server side, decryption is done on the client, Then the calculation time ratio of the AES-256-CBC algorithm is very suitable.

5. Signature and validation algorithms

In addition to encrypting and decrypting the data, we also need to determine whether the data is actually and completely tampered with during transmission. Then we need to use the algorithm of signature and verification, using asymmetric encryption algorithm, digital signature through the private key, the authenticity of the public key authentication data.

The process of making and validating digital signatures, as shown in.

Below we use the program, to the actual diagram of the operation process, because the certificate is our own production, not intended to be public, not to the CA certification, so the next process will not include public key forgery, and then to the CA certification process.

First, we'll use the OpenSSL command, the private key SERVER.PEM and the public key Cert.pem.

# 生成私钥~ D:\workspace\javascript\nodejs-crypto>openssl genrsa  -out server.pem 1024Generating RSA private key, 1024 bit long modulus..................++++++..................++++++e is 65537 (0x10001)# 生成公钥~ D:\workspace\javascript\nodejs-crypto>openssl req -key server.pem -new -x509 -out cert.pemYou are about to be asked to enter information that will be incorporatedinto your certificate request.What you are about to enter is what is called a Distinguished Name or a DN.There are quite a few fields but you can leave some blankFor some fields there will be a default value,If you enter ‘.‘, the field will be left blank.-----Country Name (2 letter code) [AU]:State or Province Name (full name) [Some-State]:Locality Name (eg, city) []:Organization Name (eg, company) [Internet Widgits Pty Ltd]:Organizational Unit Name (eg, section) []:Common Name (eg, YOUR name) []:Email Address []:

Next, we use the generated private key to generate a mathematical signature, and then use the public key to verify the data and whether it has been tampered with. New file Signer.js.

  ~ VI signer.js/////////////////////////////Signature Verification algorithm//OpenSSL genrsa-out server.pem 1024//OpenSSL req-key se  Rver.pem-new-x509-out Cert.pem///////////////////////////var crypto = require (' crypto '), FS = require (' fs '); function    Signer (algorithm,key,data) {var sign = crypto.createsign (algorithm);    Sign.update (data);    sig = Sign.sign (key, ' hex '); return SIG;}    function Verify (algorithm,pub,sig,data) {var verify = crypto.createverify (algorithm);    Verify.update (data);   Return Verify.verify (PubKey, SIG, ' hex ')}var algorithm = ' rsa-sha256 '; var data = "ABCdef"; Data transferred var PRIVATEPEM = Fs.readfilesync (' Server.pem '); var key = Privatepem.tostring (); var sig = Signer (Algorithm,key, data); Digital signature var Publicpem = Fs.readfilesync (' Cert.pem '), var pubkey = publicpem.tostring (), Console.log (Verify (algorithm,         Pubkey,sig,data));    Validation data, via public key, digital signature = "is the original data Console.log (verify (algorithm,pubkey,sig,data+" 2 ")); Validating data via public key, digital signature = "Not raw data  

Run the program

~ node signer.jstruefalse

Two rows of output, the result of the first row of validation is true, indicating that the data has not been tampered with during transmission, and the result of the second row of validation is false, indicating that the data was tampered with during transmission, not the original data. Of course, how to guarantee the matching of the private key and public key, need CA third party to authenticate, have nothing to do with Crypto library This article no longer describes.

6. Salt algorithm

We know that if the password is hashed directly, then the hacker can get a hash value by obtaining this password, and then by checking the hash value dictionary (for example, MD5 password cracking site), the password of a user.

Salt, in cryptography, refers to a process called "adding salt" by inserting a specific string at any fixed position in the password, so that the result of the hash is inconsistent with the hash result of the original password. The hash value after adding salt, can greatly reduce the risk of password leakage due to the theft of user data, even if the rainbow table to find the value of the original content of the hash, but because of the addition of salt, the inserted string disturbed the real password, so that the probability of obtaining a real password greatly reduced.

The process of adding salt is usually to add a specific character to a particular position in a field that needs to be hashed, disrupting the original string and causing the resulting hash result to change. For example, a user uses a password:

123465

After MD5 hashing, the results can be obtained:

3d9188577cc9bfe9291ac66b5cc872b7

However, due to the insufficient number of user passwords, the hash result of the short password is easily cracked by the rainbow table, so add a specific string at the end of the user's password:

123465abcdefghijklmnopqrstuvwxyz

Therefore, the number of ciphers after adding salt is longer, and the result of the hash has changed:

27e20c64ccb8cce9ad68b8ccff6252cf

New file Salt.js, implement the above program.

~ vi salt.js//////////////////////////////// salt算法//////////////////////////////var crypto = require(‘crypto‘);var md5 = crypto.createHash(‘md5‘);var txt = "123465";md5.update(txt);console.log(md5.digest(‘hex‘));md5 = crypto.createHash(‘md5‘);var salt = "abcdefghijklmnopqrstuvwxyz";md5.update(txt+salt);console.log(md5.digest(‘hex‘));

Instead of adding salt ourselves, we can use the CRYPTO.PBKDF2 () function, which calls the HMAC algorithm by default, uses the SHA1 hash function, and can set the number of iterations and the length of the cipher. The specific usage code is as follows.

~ vi salt.jsvar crypto = require(‘crypto‘);var txt = "123465";var salt = "abcdefghijklmnopqrstuvwxyz";// 生成密文,默认HMAC函数是sha1算法crypto.pbkdf2(txt, salt, 4096, 256, function (err,hash) {    if (err) { throw err; }    console.log(hash.toString(‘hex‘));})

Run the program to generate 256 bits of ciphertext.

~ node salt.js29c7de002d942ebcbf3afe05f3eb0ff620f0515fe6b8f19176736273cd70805afdfcc828a6f227152dfa4d0c4f96da184fbd060d4d4c86a5deb8d704699c3e8653acdb0e5bc3e584e0890a44206bb2926f0289fc8e0abe49fd1876461fcc50f06dc7991c4b93cc4e80076529c73b2f2c56f16b5b319368edf017f3d3583a33aa44fd30f89801f0d8877eb8262925f5fdc40a5c57f1b275e5674784dca635c75bc58b6c22264e0f29e363eb25dedf1a242429084e3e17d344b59cab3b9723db03ee4838b632786d1a9eb968f2523404286e5d0a41a1707577650cc3cc2f1ab65714a4cb31f068e4aefa259c6be68174e0a475d5610168305a4935a14bb221a516

If the salt is fixed every time the value is also unsafe, we can also use the random randombytes () function, with the PBKDF2 () function, so that each time is a different salt, generate a higher security level of ciphertext.

~ vi salt.js//通过伪随机码生成salt,进行加密crypto.randomBytes(128, function (err, salt) {    if (err) { throw err;}    salt = salt.toString(‘hex‘);    console.log(salt); //生成salt    crypto.pbkdf2(txt, salt, 4096, 256, function (err,hash) {        if (err) { throw err; }        hash = hash.toString(‘hex‘);        console.log(hash);//生成密文    })})

Run the program

~ node salt.js# 随机生成的salt78e59de99f16697e3eb684dcfa8efa086db0940c7cd47d33f9311e3bfcf9d58bf30915f54b3f72793b5c8568d32f1f15c55cc87affd043d96f1ed1f56c25a8054b3d83a306636f3b9e3bc9e48c3303aff54da006f92e370023165857fce0a1d1ff0b89178ae8c1416747275daba25652ea864d52a80427658ea69dbe500a7261# 通过salt生成的密文48943eb51ea702b436f95bf1dacc7f64bc41cf7cfa4cb40d101d5550c28caafc58ca720934352238430634f21fd5a6a4ef63fe5828c2665362e9902adc0305f93d2523fbd28521ad00947a74ff8229f63ad5796f2e12677cbed6af02b9973ee0187a69ad67e86790471d95f18d6d2c43ef904f7d17a5d8264f8236f227363a016ae2c14559c17236d540e06c5fd443af740721897f76bdbd9711c8499d7a34cae2e917f900fc364f72f9afaf301845c6e0b5c37def949b4af62336a39dbd1e829405d6189536092c7769a5d7e427b8e97419988da4e1bad49c69f25ac4e96f74a0ce3eab9e1433277568105b1dcc0cf9e1f9c91a7ed391c5825eefcd71ef5ca1

We store the salt and ciphertext together to ensure the security of the user's password.

7. Program code

The program code of this article, you can download the source code of this project directly from GitHub, and follow the instructions in the article to learn Crypto,:https://github.com/bsspirit/nodejs-crypto

You can also download it directly from the GitHub command line:

~ git clone [email protected]:bsspirit/nodejs-crypto.git   # 下载github项目~ cd nodejs-crypto                                      # 进入下载目录

Finally to declare: I understand the password technology is not deep, the password technology involved in this article is only crypto library in the application, the text of the view is not clear or description of the place, but also experts to correct!!

Reference article:

    • Talking about the crypto module in Nodejs
    • Talking about the crypto module in Nodejs (fill out)

Reprint please specify the source:
Http://blog.fens.me/nodejs-crypto

[Reprint] Cryptographic algorithm library CRYPTO--NODEJS middleware series

Related Article

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.

Tags Index: