文档地址:http://nodejs.cn/api/crypto.html
使用crypto.createHash(algorithm [,options])
这个方法,该创建并返回一个Hash对象,该对象可用于使用给定的哈希摘要生成哈希摘要algorithm
。其中algorithm
取决于平台上OpenSSL版本支持的可用算法。不只支持sha1和md5这两种,还支持sha256、
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复制代码