发布于 2017-03-02 13:23:56 | 155 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Node.js教程,程序狗速度看过来!

Node.js 服务器端的JavaScript

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台, 用来方便地搭建快速的 易于扩展的网络应用· Node.js 借助事件驱动, 非阻塞I/O 模型变得轻量和高效, 非常适合 运行在分布式设备 的 数据密集型 的实时应用


下面小编就为大家带来一篇nodejs加密Crypto的实例代码。小编觉得挺不错的, 现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

加密技术通常分为两大类:“对称式”和“非对称式”。

对称式加密:

就是加密和解密使用同一个密钥,通常称之为“Session Key ”这种加密技术在当今被广泛采用,如美国政府所采用的DES加密标准就是一种典型的“对称式”加密法,它的Session Key长度为56bits。
非对称式加密:

就是加密和解密所使用的不是同一个密钥,通常有两个密钥,称为“公钥”和“私钥”,它们两个必需配对使用,否则不能打开加密文件。

加密为系统中经常使用的功能,node自带强大的加密功能Crypto,下面通过简单的例子进行练习。

1、加密模块的引用:


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

默认加密算法配置项:

输入数据格式为utf8,输出格式为hex,

算法使用bf,blowfish,aes-128-abc三种加密算法;

2、配置项初始化:


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进行不同加密算法及编码的使用。

3、加密方法代码如下: 


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进行数据的加密处理。

4、解密方法代码如下:


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方法,进行加密和解密的算法执行。

本文根据民少编写的算法进行编写,如有不足之处,敬请原谅。菜鸟在路上,继续前进。

以上这篇nodejs加密Crypto的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持phperz。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务