[Angular] Using the Argon 2 Hashing Function In Our Sign Up Backend Service

本文介绍了使用Argon2作为密码哈希算法的最佳实践,并展示了如何在Node.js中实现密码验证与存储。通过安装argon2模块并结合password-validator进行密码强度检查,确保了应用的安全性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Which hash algorithom to choose for new application:

https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet

We can use this package:

https://github.com/ranisalt/node-argon2

 

Install:

npm install argon2 --save

 

Code:

import {Request, Response} from 'express';
import {db} from './database';
import {USERS} from './database-data';

import * as argon from 'argon2';

export function createUser (req: Request, res: Response) {

  const credentials = req.body;

  argon.hash(credentials.password)
    .then(passwordDigest => {

      const user = db.createUser(credentials.email, passwordDigest);

      console.log(USERS);
      res.status(200).json({id: user.id, email: user.email});
    });

};

  

It would be good to add some password validations. So that user cannot enter the password as simple as '123456'...

 

Valid password:

npm install --save password-validatory

 

password-validation.ts:

import * as passwordValidator from 'password-validator';

// Create a schema
const schema = new passwordValidator();

// Add properties to it
schema
  .is().min(7)                                    // Minimum length 7
  .has().uppercase()                              // Must have uppercase letters
  .has().lowercase()                              // Must have lowercase letters
  .has().digits()                                 // Must have digits
  .has().not().spaces()                           // Should not have spaces
  .is().not().oneOf(['Passw0rd', 'Password123']); // Blacklist these values

export function validatePassword(password: string) {
  return schema.validate(password, {list: true});
}

 

Update code:

import {Request, Response} from 'express';
import {db} from './database';
import {USERS} from './database-data';

import * as argon from 'argon2';
import {validatePassword} from './password-validation';

export function createUser (req: Request, res: Response) {

  const credentials = req.body;

  const errors = validatePassword(credentials);

  if (errors.length > 0) {
    res.status(400).json({
      errors
    });
  } else {
    argon.hash(credentials.password)
      .then(passwordDigest => {

        const user = db.createUser(credentials.email, passwordDigest);

        console.log(USERS);
        res.status(200).json({id: user.id, email: user.email});
      });
  }
};

 

转载于:https://www.cnblogs.com/Answer1215/p/7355639.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值