Implementing crypto hash – Node.js 22 – Angular 18

I already searched within Stack Overflow and in Google for solutions, but none of the solutions work, I always get following error :

Error: Module not found: Error: Can't resolve 'crypto' in ....

I did already:

  • npm update
  • ng update

auth.service.ts : ( not the html component – not in the browser – hidden authentication service )

import { Injectable } from '@angular/core';
import { scrypt, randomBytes, timingSafeEqual } from "crypto";

const keyLength = 32;

@Injectable({
  providedIn: 'root'
})
export class AuthService {

constructor() {};

async login( username: string, password: string ) {
  if ( await AuthService.compare(username, await AuthService.hash(password))) {
    localStorage.setItem('STATE', 'true');
    return true;
  }

  return false;
}
  
async logout() {
    localStorage.setItem('STATE', 'false');

    return true;
}
  
isLoggedIn() {
  const loggedIn = localStorage.getItem('STATE');
  if (loggedIn == 'true')
    return true;
  else
    return false;
}

/**
 * Has a password or a secret with a password hashing algorithm (scrypt)
 * @param {string} password
 * @returns {string} The salt+hash
 */
static async hash( password: string ): Promise<string> {
  return new Promise((resolve, reject) => {
      // generate random 16 bytes long salt - recommended by NodeJS Docs
      const salt = randomBytes(16).toString("hex");

      scrypt(password, salt, keyLength, (err, derivedKey) => {
          if (err) reject(err);
          // derivedKey is of type Buffer
          resolve(`${salt}.${derivedKey.toString("hex")}`);
      });
    });
  };

/**
* Compare a plain text password with a salt+hash password
* @param {string} password The plain text password
* @param {string} hash The hash+salt to check against
* @returns {boolean}
*/
static async compare( password: string, hash: string ): Promise<boolean> {
  return new Promise((resolve, reject) => {
      const [salt, hashKey] = hash.split(".");
      // we need to pass buffer values to timingSafeEqual
      const hashKeyBuff = Buffer.from(hashKey, "hex");
      scrypt(password, salt, keyLength, (err, derivedKey) => {
          if (err) reject(err);
          // compare the new supplied password with the hashed password using timeSafeEqual
          resolve(timingSafeEqual(hashKeyBuff, derivedKey));
      });
    });
  };

}

Crypto module is built-in in Node.js 22.4.1 which I use for my Angular 18:
https://nodejs.org/api/crypto.html#cryptoscryptpassword-salt-keylen-options-callback

The solution is not:

  • npm install crypto (old way)
  • not using Crypto-JS
  • No errors shown in Visual Studio Code (but errors show up when doing “Start debugging”)

3

You’ll need to use something available in browsers like the Web Crypto API.

Hashing could look something like:

static async hash(password: string): Promise<string> {
  const salt = crypto.getRandomValues(new Uint8Array(16))
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(password),
    { name: "PBKDF2" },
    false,
    ["deriveBits"])
  const derivedBits = await crypto.subtle.deriveBits({
    name: "PBKDF2",
    salt,
    iterations: 100000,
    hash: "SHA-256"
  }, key, 256)
  return `${this.bufferToHex(salt)}.${this.bufferToHex(derivedBits)}`
}

Comparing could look something like:

static async compare(password: string, hash: string): Promise<boolean> {
  const [saltHex, storedHashHex] = hash.split('.')
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(password),
    { name: "PBKDF2" },
    false,
    ["deriveBits"]
  )
  const derivedBits = await crypto.subtle.deriveBits({
    name: "PBKDF2",
    salt: this.hexToBuffer(saltHex),
    iterations: 100000,
    hash: "SHA-256"
  }, key, 256)
  return storedHashHex === this.bufferToHex(derivedBits)
}

Shouldn’t need to import anything for this to work. I’m not a security expert so can’t guarantee the security of these algorithms, but PBKDF2 is generally considered acceptable for password hashing.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật