Nodejs学习记录:crypto模块

http://nodejs.cn/api/crypto.h…

示例:

// 注意:该 demo 模拟计算密集型应用,请勿在生产环境中使用。
const http = require('http');
const crypto = require('crypto');
const reqHeaders = [];
const algorithm = 'aes-256-cbc';
const key = ['this', 'is', 'a', 'test'].join(' ');
const encode = function(str) {
  var buf = new Buffer(str)
  var encrypted = "";
  var cip = crypto.createCipher(algorithm, key);
  encrypted += cip.update(buf, 'binary', 'hex');
  encrypted += cip.final('hex');
  return encrypted;
};
const decode = function(encrypted){
  var decrypted = "";
  var decipher = crypto.createDecipher(algorithm, key);
  decrypted += decipher.update(encrypted, 'hex', 'binary');
  decrypted += decipher.final('binary');
  return decrypted;
}
http.createServer(function(req, res) {
  reqHeaders.push(req.headers);
  let enc = encode(req.headers['host']);
  let dec = decode(enc);
  res.end('hello')
}).listen(8848);
$ npm install utility
'use strict';

var crypto = require('crypto');

/**
 * hash
 *
 * @param {String} method hash method, e.g.: 'md5', 'sha1'
 * @param {String|Buffer} s
 * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
 * @return {String} md5 hash string
 * @public
 */
exports.hash = function hash(method, s, format) {
  var sum = crypto.createHash(method);
  var isBuffer = Buffer.isBuffer(s);
  if (!isBuffer && typeof s === 'object') {
    s = JSON.stringify(sortObject(s));
  }
  sum.update(s, isBuffer ? 'binary' : 'utf8');
  return sum.digest(format || 'hex');
};

/**
 * md5 hash
 *
 * @param {String|Buffer} s
 * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
 * @return {String} md5 hash string
 * @public
 */
exports.md5 = function md5(s, format) {
  return exports.hash('md5', s, format);
};

/**
 * sha1 hash
 *
 * @param {String|Buffer} s
 * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
 * @return {String} sha1 hash string
 * @public
 */
exports.sha1 = function sha1(s, format) {
  return exports.hash('sha1', s, format);
};

/**
 * sha256 hash
 *
 * @param {String|Buffer} s
 * @param {String} [format] output string format, could be 'hex' or 'base64'. default is 'hex'.
 * @return {String} sha256 hash string
 * @public
 */
exports.sha256 = function sha1(s, format) {
  return exports.hash('sha256', s, format);
};

/**
 * HMAC algorithm.
 *
 * Equal bash:
 *
 * ```bash
 * $ echo -n "$data" | openssl dgst -binary -$algorithm -hmac "$key" | openssl $encoding
 * ```
 *
 * @param {String} algorithm, dependent on the available algorithms supported by the version of OpenSSL on the platform.
 *   Examples are 'sha1', 'md5', 'sha256', 'sha512', etc.
 *   On recent releases, `openssl list-message-digest-algorithms` will display the available digest algorithms.
 * @param {String} key, the hmac key to be used.
 * @param {String|Buffer} data, content string.
 * @param {String} [encoding='base64']
 * @return {String} digest string.
 */
exports.hmac = function hmac(algorithm, key, data, encoding) {
  encoding = encoding || 'base64';
  var hmac = crypto.createHmac(algorithm, key);
  hmac.update(data, Buffer.isBuffer(data) ? 'binary' : 'utf8');
  return hmac.digest(encoding);
};

/**
 * Base64 encode string.
 *
 * @param {String|Buffer} s
 * @param {Boolean} [urlsafe=false] Encode string s using a URL-safe alphabet,
 *   which substitutes - instead of + and _ instead of / in the standard Base64 alphabet.
 * @return {String} base64 encode format string.
 */
exports.base64encode = function base64encode(s, urlsafe) {
  if (!Buffer.isBuffer(s)) {
    s = new Buffer(s);
  }
  var encode = s.toString('base64');
  if (urlsafe) {
    encode = encode.replace(/\+/g, '-').replace(/\//g, '_');
  }
  return encode;
};

/**
 * Base64 string decode.
 *
 * @param {String} encode, base64 encoding string.
 * @param {Boolean} [urlsafe=false] Decode string s using a URL-safe alphabet,
 *   which substitutes - instead of + and _ instead of / in the standard Base64 alphabet.
 * @param {encoding} [encoding=utf8] if encoding = buffer, will return Buffer instance
 * @return {String|Buffer} plain text.
 */
exports.base64decode = function base64decode(encodeStr, urlsafe, encoding) {
  if (urlsafe) {
    encodeStr = encodeStr.replace(/\-/g, '+').replace(/_/g, '/');
  }
  var buf = new Buffer(encodeStr, 'base64');
  if (encoding === 'buffer') {
    return buf;
  }
  return buf.toString(encoding || 'utf8');
};

function sortObject(o) {
  if (!o || Array.isArray(o) || typeof o !== 'object') {
    return o;
  }
  var keys = Object.keys(o);
  keys.sort();
  var values = [];
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i];
    values.push([k, sortObject(o[k])]);
  }
  return values;
}

示例2

戳这里
bilibili-vue/bilibili-api/app/utils/EncryptUtil.js

import crypto from 'crypto'

// 检测是否支持crypto
try {
  console.log(crypto)
} catch (error) {
  console.log('不支持 crypto')
}

// MD5加密
function EncryptMD5 (data) {
    let encryptMD5 = crypto.createHash('md5')
    encryptMD5.update(data)
    return encryptMD5.digest('hex')
}


// DES加密、解密,用来加密信息字段,无需App端解密
// 私有方法
function cipheriv (en, code, data) {
    let buf1 = en.update(data, code)
    let buf2 = en.final()
    let r = new Buffer(buf1.length + buf2.length)
    buf1.copy(r)
    buf2.copy(r, buf1.length)
    return r
}

// DES加密
function DESEncrypt (data, key, vi) {
    return data = cipheriv(crypto.createCipheriv('des', key, vi), 'utf8', data).toString('base64')
}

// DES解密
function DESDecrypt (data, key, vi) {
    return data = cipheriv(crypto.createDecipheriv('des', key, vi), 'base64', data).toString('utf8')
}

// AES加密
function AESEncrypt (data, secretKey) {
    let cipher = crypto.createCipher('aes-128-ecb', secretKey)
    return cipher.update(data, 'utf8', 'hex') + cipher.final('hex')
}

// AES 解密
function AESDecrypt (data, secretKey) {
    let cipher = crypto.creatDecipher('aes-128-ecb', secretKey)
    return cipher.update(data, 'hex', 'utf8') + cipher.final('utf8')
}

export {
    EncryptMD5,
    DESEncrypt,
    DESDecrypt,
    AESEncrypt,
    AESDecrypt
}
    原文作者:AlexZ33
    原文地址: https://segmentfault.com/a/1190000015738223
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞