1.

    1. import * as crypto from 'crypto';
    2. /**
    3. * Make salt
    4. */
    5. export function makeSalt(): string {
    6. return crypto.randomBytes(3).toString('base64');
    7. }
    8. /**
    9. * Encrypt password
    10. * @param password 解密前的密码
    11. * @param salt 密码盐
    12. */
    13. export function encryptPassword(password: string, salt: string): string {
    14. if (!password || !salt) {
    15. return '';
    16. }
    17. const tempSalt = Buffer.from(salt, 'base64');
    18. return (
    19. // 10000 代表迭代次数 16代表长度
    20. crypto.pbkdf2Sync(password, tempSalt, 10000, 16, 'sha1').toString('base64')
    21. );
    22. }

    2.

    1. import { compare, genSalt, hash } from 'bcryptjs';
    2. export function makeSalt(): string {
    3. return genSalt(10);
    4. }
    5. /**
    6. * Encrypt password
    7. * @param password 解密前的密码
    8. * @param salt 密码盐
    9. */
    10. export function encryptPassword(password: string, salt: string): string {
    11. if (!password || !salt) {
    12. return '';
    13. }
    14. return hash(password, salt);
    15. }
    16. export function comparePassword(loginPassword: string, userPassword: string): boolean {
    17. return compare(loginPassword, userPassword);
    18. }