NodeJs 中的Crypto 加密模块

加密技术一般分为两大类:“对称式”和“非对称式”。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;
}
相关文章
相关标签/搜索