nodejs Encryption Crypto Instance Code

  • 2021-07-02 23:02:30
  • OfStack

Encryption technology is usually divided into two categories: "symmetric" and "asymmetric".

Symmetric encryption:

Encryption and decryption use the same key, which is usually called "Session Key". This encryption technology is widely used today. For example, the DES encryption standard adopted by the American government is a typical "symmetric" encryption method, and its Session Key length is 56bits.
Asymmetric encryption:

That is, encryption and decryption are not used with the same key. Usually, there are two keys, called "public key" and "private key". They must be paired, otherwise the encrypted file cannot be opened.

Encryption is a frequently used function in the system. node comes with powerful encryption function Crypto. The following is a simple example to practice.

1. Reference of encryption module:


var crypto=require('crypto');
var $=require('underscore');var DEFAULTS = {
  encoding: {
    input: 'utf8',
    output: 'hex'
  },
  algorithms: ['bf', 'blowfish', 'aes-128-cbc']
};

Default Encryption Algorithm Configuration Items:

The input data format is utf8, the output format is hex,

The algorithm uses three encryption algorithms: bf, blowfish and aes-128-abc.

2. Initialization of configuration items:


function MixCrypto(options) {
  if (typeof options == 'string')
    options = { key: options };

  options = $.extend({}, DEFAULTS, options);
  this.key = options.key;
  this.inputEncoding = options.encoding.input;
  this.outputEncoding = options.encoding.output;
  this.algorithms = options.algorithms;
}

Encryption algorithm can be configured, through the configuration of option for different encryption algorithm and encoding use.

3. The encryption method code is as follows:


MixCrypto.prototype.encrypt = function (plaintext) {
  return $.reduce(this.algorithms, function (memo, a) {
    var cipher = crypto.createCipher(a, this.key);
    return cipher.update(memo, this.inputEncoding, this.outputEncoding)
      + cipher.final(this.outputEncoding)
  }, plaintext, this);
};

Use crypto to encrypt data.

4. The decryption method code is as follows:


MixCrypto.prototype.decrypt = function (crypted) {
  try {
    return $.reduceRight(this.algorithms, function (memo, a) {
      var decipher = crypto.createDecipher(a, this.key);
      return decipher.update(memo, this.outputEncoding, this.inputEncoding)
        + decipher.final(this.inputEncoding);
    }, crypted, this);
  } catch (e) {
    return;
  }
};

Use crypto to decrypt data.

Encryption and decryption algorithms are executed by reduce and reduceRight methods in underscore.

This article is written according to the algorithm written by Minshao. Please forgive me for any shortcomings. Rookie on the road, keep moving.


Related articles: