加密技術一般分爲兩大類:「對稱式」和「非對稱式」。javascript
對稱式加密:java
就是加密和解密使用同一個密鑰,一般稱之爲「Session Key 」這種加密技術在當今被普遍採用,如美國政府所採用的DES加密標準就是一種典型的「對稱式」加密法,它的Session Key長度爲56bits。
非對稱式加密:node
就是加密和解密所使用的不是同一個密鑰,一般有兩個密鑰,稱爲「公鑰」和「私鑰」,它們兩個必需配對使用,不然不能打開加密文件。算法
加密爲系統中常用的功能,node自帶強大的加密功能Crypto,下面經過簡單的例子進行練習。ui
一、加密模塊的引用:this
var crypto=require('crypto');
var $=require('underscore');
var DEFAULTS = { encoding: { input: 'utf8',//輸入數據格式爲utf8 output: 'hex' //輸出數據格式爲hex(二進制) }, algorithms: ['bf', 'blowfish', 'aes-128-cbc'] //使用的加密算法 };
默認加密算法配置項:編碼
輸入數據格式爲utf8,輸出格式爲hex,加密
算法使用bf,blowfish,aes-128-abc三種加密算法;spa
二、配置項初始化:prototype
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; }
加密算法能夠進行配置,經過配置option進行不一樣加密算法及編碼的使用。
三、加密方法代碼以下:
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); };
使用crypto進行數據的加密處理。
四、解密方法代碼以下:
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; } };
使用crypto進行數據的解密處理。
經過underscore中的reduce、reduceRight方法,進行加密和解密的算法執行。
簡單的加密解密實例:
var crypto = require('crypto'); //加密 function encrypt(str, secret) { var cipher = crypto.createCipher('aes192', secret); var enc = cipher.update(str, 'utf8', 'hex'); enc += cipher.final('hex'); return enc; } //解密 function decrypt(str, secret) { var decipher = crypto.createDecipher('aes192', secret); var dec = decipher.update(str, 'hex', 'utf8'); dec += decipher.final('utf8'); return dec; }