使用nodejs crypto模块进行sha1、md5加密

2019-03-07  本文已影响0人  shibin

文档地址:http://nodejs.cn/api/crypto.html

使用crypto.createHash(algorithm [,options])这个方法,该创建并返回一个Hash对象,该对象可用于使用给定的哈希摘要生成哈希摘要algorithm。其中algorithm取决于平台上OpenSSL版本支持的可用算法。

const {createHash}= require('crypto');
/**
 * @param {string} algorithm
 * @param {any} content
 *  @return {string}
 */
const encrypt = (algorithm, content) => {
  let hash = createHash(algorithm)
  hash.update(content)
  return hash.digest('hex')
}
/**
 * @param {any} content
 *  @return {string}
 */
const sha1 = (content) => encrypt('sha1', content)
/**
 * @param {any} content
 *  @return {string}
 */
const md5 = (content) => encrypt('md5', content)

module.exports={sha1,md5,encrypt}

下面是使用es6的方法进行导出

import {createHash} from 'crypto'

/**
 * @param {string} algorithm
 * @param {any} content
 *  @return {string}
 */
export const encrypt = (algorithm, content) => {
    let hash = createHash(algorithm)
    hash.update(content)
    return hash.digest('hex')
}

/**
 * @param {any} content
 *  @return {string}
 */
export const sha1 = (content) => encrypt('sha1', content)

/**
 * @param {any} content
 *  @return {string}
 */
export const md5 = (content) => encrypt('md5', content)

export default encrypt
上一篇 下一篇

猜你喜欢

热点阅读