I'm trying to use bcrypt with Angular7 to store an encrypted password in MySQL.
I have used npm install bcrypt to install bcrypt and importing it like so
import * as bcrypt from 'bcrypt';.
Everything is compiling fine till this point; it fails to do so when I add bcrypt.hash()
The entire code for the login.component.ts file is below:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import * as bcrypt from 'bcrypt';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm : FormGroup;
success = false;
loginFailed = false;
constructor(private formBuilder : FormBuilder) { }
ngOnInit() : void {
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });
}
DoLogin()
{
    console.log(this.loginForm.value);
    pass = bcrypt.hash('Pass@123', 10); // App is not compliling when I add this line //
}
How do I call the methods in bcrypt?
You can install bcryptjs (npm install bcryptjs) and use the following code:
import * as bcrypt from 'bcryptjs';
const salt = bcrypt.genSaltSync(10);
pass = bcrypt.hashSync(this.loginForm.value.password, salt);
Your code must look like:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import * as bcrypt from 'bcryptjs';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
loginForm : FormGroup;
success = false;
loginFailed = false;
constructor(private formBuilder : FormBuilder) { }
ngOnInit() : void {
    this.loginForm = this.formBuilder.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });
}
DoLogin()
{
    console.log(this.loginForm.value);
    const salt = bcrypt.genSaltSync(10);
    pass = bcrypt.hashSync('Pass@123', 10);
}
After that, if you get an Module not found: Error: Can't resolve 'crypto'... error, you must add this code into packaje.json file:
"browser": {
    "fs": false,
    "path": false,
    "os": false,
    "crypto": false,
    "stream": false,
    "http": false,
    "tls": false,
    "zlib": false,
    "https": false,
    "net": false
  }
Hope it helps to someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With