Encryption technology is usually divided into two categories: "symmetrical" and "asymmetrical".
Symmetric encryption:
It means that encryption and decryption use the same key, which is commonly called "Session Key". This encryption technology is widely used today. For example, the DES encryption standard adopted by the US government is a typical "symmetric" encryption method, and its Session Key length is 56 bits.
Asymmetric encryption:
That is, the encryption and decryption use not the same key, usually there are two keys, called "public key" and "private key". They must be used in pairs, otherwise the encrypted file cannot be opened.
Encryption is a frequently used function in the system. The node comes with a powerful encryption function Crypto. The following is a simple example to practice.
1. References to the 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. Configuration item initialization:
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;}The encryption algorithm can be configured, and different encryption algorithms and encodings can be used through configuration options.
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.
The encryption and decryption algorithm is executed through the reduce and reduceRight methods in the underscore.
This article is written based on the algorithm written by Min Shao. If there are any shortcomings, please forgive me. The rookie is on the road, keep moving forward.
The above example code of nodejs encryption Crypto is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.