nodejs加密Crypto的實(shí)例代碼

字號(hào):


    下面小編就為大家?guī)硪黄猲odejs加密Crypto的實(shí)例代碼。小編覺得挺不錯(cuò)的, 現(xiàn)在就分享給大家,也給大家做個(gè)參考。
    加密技術(shù)通常分為兩大類:“對(duì)稱式”和“非對(duì)稱式”。
    對(duì)稱式加密:
    就是加密和解密使用同一個(gè)密鑰,通常稱之為“Session Key ”這種加密技術(shù)在當(dāng)今被廣泛采用,如美國政府所采用的DES加密標(biāo)準(zhǔn)就是一種典型的“對(duì)稱式”加密法,它的Session Key長(zhǎng)度為56bits。
    非對(duì)稱式加密:
    就是加密和解密所使用的不是同一個(gè)密鑰,通常有兩個(gè)密鑰,稱為“公鑰”和“私鑰”,它們兩個(gè)必需配對(duì)使用,否則不能打開加密文件。
    加密為系統(tǒng)中經(jīng)常使用的功能,node自帶強(qiáng)大的加密功能Crypto,下面通過簡(jiǎn)單的例子進(jìn)行練習(xí)。
    1、加密模塊的引用:
    var crypto=require('crypto');
    var $=require('underscore');var DEFAULTS = {
      encoding: {
        input: 'utf8',
        output: 'hex'
      },
      algorithms: ['bf', 'blowfish', 'aes-128-cbc']
    };
    默認(rèn)加密算法配置項(xiàng):
    輸入數(shù)據(jù)格式為utf8,輸出格式為hex,
    算法使用bf,blowfish,aes-128-abc三種加密算法;
    2、配置項(xiàng)初始化:
    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;
    }
    加密算法可以進(jìn)行配置,通過配置option進(jìn)行不同加密算法及編碼的使用。
    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進(jìn)行數(shù)據(jù)的加密處理。
    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進(jìn)行數(shù)據(jù)的解密處理。
    通過underscore中的reduce、reduceRight方法,進(jìn)行加密和解密的算法執(zhí)行。
    本文根據(jù)民少編寫的算法進(jìn)行編寫,如有不足之處,敬請(qǐng)?jiān)?。菜鳥在路上,繼續(xù)前進(jìn)。
    以上這篇nodejs加密Crypto的實(shí)例代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考