美文网首页程序员
TypeScript版加密工具PasswordEncoder

TypeScript版加密工具PasswordEncoder

作者: 码道功臣 | 来源:发表于2022-07-25 10:31 被阅读0次

安装依赖

>npm i bcryptjs --save

添加代码PasswordEncoder.ts

const bcrypt = require('bcryptjs');

/**
 * 加密。加上前缀{bcrypt},为了兼容多种加密算法,这里暂时只实现bcrypt算法
 */
export function encrypt(password) {
  const salt = bcrypt.genSaltSync(5);
  const hash = bcrypt.hashSync(password, salt, 64);
  return '{bcrypt}' + hash;
}

/**
 * 解密
 */
export function decrypt(password, hash) {
  if (hash.indexOf('{bcrypt}') === 0) {
    hash = hash.slice(8);
  }
  return bcrypt.compareSync(password, hash);
}

使用

const p = encrypt('123456');
const flag = decrypt('123456', p);
console.log(p);
console.log(flag);

相关文章

网友评论

    本文标题:TypeScript版加密工具PasswordEncoder

    本文链接:https://www.haomeiwen.com/subject/jbvjirtx.html