Encryption techniques are usually grouped into two broad categories: symmetric and asymmetric.
Symmetric encryption:
Encryption and decryption using the same key, usually called "session key" this encryption technology is widely used today, such as the United States Government adopted DES Encryption standard is a typical "symmetric" encryption method, its session key length of 56bits.
non-symmetric encryption:
That is, encryption and decryption are not using the same key, usually have two keys, called "Public Key" and "private key", they are two must pair use, otherwise cannot open the encrypted file.
Encryption is a function that is often used in the system, and node has its own powerful encryption function crypto, and the following is practiced with a simple example.
1, the Encryption module reference:
var crypto=require (' Crypto ');
var $=require (' underscore '); var DEFAULTS = {
encoding: {
input: ' UTF8 ',
output: ' Hex '
},
Algorithms: [' BF ', ' blowfish ', ' AES-128-CBC ']
};
Default Cryptographic algorithm Configuration entry:
The input data format is UTF8, the output format is hex,
The algorithm uses BF,BLOWFISH,AES-128-ABC three kinds of encryption algorithms;
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;
}
The encryption algorithm can be configured to use different encryption algorithms and codes by configuring option.
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 for data encryption processing.
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 the data.
The algorithm of encryption and decryption is performed through the reduce and reduceright methods in underscore.
This article according to the people write algorithm to write, if there are deficiencies, please forgive. Rookie on the road, continue to move forward.
The above Nodejs encryption Crypto example code is a small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.