Guide to incorporating bcrypt into an Angular 6 application

Hey there, I've been attempting to hash a key using the bcrypt npm package but have encountered some errors. Here's the code I've tried so far:

import * as bcrypt from 'bcrypt';

export class LowLevelEncryption {

    encrypt(key: string){
        console.log(bcrypt);
         bcrypt.hash(key, 19, function(err, hash) {
           Store hash in your password DB.
         });
    }

}

I'm getting an error that looks like this:

Module not found: Error: Can't resolve 'tls' in '/home/ec2-user/environment/passcript/node_modules/tunnel-agent'

If anyone can offer assistance or knows of another library that may work better, I would greatly appreciate it. Thanks!

Answer №1

If you're looking to implement encryption in your Angular project, you might consider using crypto-js library and tailor it to your specific needs. Here is an example:

    import { Injectable } from '@angular/core';
    import * as crypto from 'crypto-js';

    @Injectable()
    export class CryptoService {

    constructor() {
    }


   encrypt(key: any, privateKey: any) {
     const cryptkey = crypto.enc.Utf8.parse(privateKey);
     const encrypted = crypto.AES.encrypt(key, cryptkey, {
      iv: crypto.enc.Hex.parse('00000000000000000000000000000000'),
      mode: crypto.mode.ECB,
      padding: crypto.pad.Pkcs7
   });
   return encrypted.toString();
  }


  decrypt(cryptedKey: any, privateKey: any) {
    const cryptoPrivateKey = crypto.enc.Utf8.parse(privateKey);
    const encryptedKey = crypto.enc.Base64.parse(cryptedKey);
    const decrypted = crypto.AES.decrypt({ciphertext: encryptedKey}, cryptoPrivateKey, {
      iv: crypto.enc.Hex.parse('00000000000000000000000000000000'),
      mode: crypto.mode.ECB,
      padding: crypto.pad.Pkcs7
   });
   return decrypted.toString(crypto.enc.Utf8);
  }
}

An even simpler approach for encryption could be:

const encryptedPassword = crypto.AES.encrypt(value, 'password');

and for decryption:

const bytes  = crypto.AES.decrypt(encryptedPassword, 'password');
const decryptedPassword = bytes.toString(crypto.enc.Utf8);

I hope this explanation proves helpful for your encryption needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we effectively manage the array of objects passed to the Angular mat-select-search drop-down component and ensure proper control over the function execution?

After successfully implementing the mat-select-search component with live search functionality by following guides on Angular ngx-mat-select-search Custom Component and the documentation for ngx-mat-select-search, everything was working smoothly until I tr ...

Share a coded photo with various android apps

Currently, I am working on an Android application that encrypts images using the Bouncy Castle library. Encryption is successful, but I am facing an issue where the encrypted image file cannot be recognized as an actual image by other applications like W ...

On localhost, Angular 2 route parameters are automatically converted to lowercase, while they stay capitalized on the server

I am currently working on a .NET Angular 2 program that has a route set up like this: <ControllerName>/:id While running it on localhost with IIS Express, the id route parameter automatically gets converted to lowercase in the URL without any addi ...

Creating a specialized Angular validator that detects null values and returns the associated FormControl

I'm currently working on an Angular Reactive form group that includes a custom validator. My form includes 2 date pickers and I need to ensure that if a user selects a date from one picker, they must also select a date from the other. However, I am en ...

Error encountered when pushing Angular data to Django for user login form: 'Unexpected token < in JSON at position 2' while attempting to parse the JSON

I believe the < symbol is appearing because the response is in HTML or XML format. This is the section of my code where the login process is failing. public login(user) { this.http.post('/api-token-auth/', JSON.stringify(user), this.ht ...

Can dynamic forms in Angular 2 support nested forms without relying on formBuilder?

I'm familiar with implementing nested forms in reactive form, but I'm unsure about how to do it in dynamic form within Angular 2. Can nested forms be implemented in dynamic forms in Angular 2? ...

The function may not always be triggered when bound to a click event

My angular material autocomplete input for addresses is calling a custom function called fillAddress upon click. However, the issue is that the fillAddress function is not executed every time the span element is clicked, triggering the default autocomplete ...

Learn how to easily set a radio button using Angular 4 and JavaScript

It seems like a simple task, but I am looking for a solution without using jQuery. I have the Id of a specific radio button control that I need to set. I tried the following code: let radiobutton = document.getElementById("Standard"); radiobutton.checke ...

Is it possible to have an interface, function, and variable all sharing the same name in a declaration?

Is it possible to have an interface, function, and variable all with the same name? For example, I would like to define the function as follows: declare function someName(...args: any[]); someName('foo'); The interface would look like this: ...

Transforming file location to base64 encoded format using TypeScript

I have the path of an image and need to convert it to base64 format, similar to this data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUg... function encodeImageToBase64(url, callback) { var xhr = new XMLHttpRequest(); xhr.onload = function() { va ...

Typescript error: The overload signature does not match its implementation signature

I am facing an issue with the code below. It seems to work fine without including setCurrentTab in the return interface useTabsReturnType, but as soon as I add it, the code stops working and I'm not sure why. interface useTabsReturnType<T> { c ...

Turn off the button and add a CSS class to it when sending a message

I have an Angular 7 component with a form that includes the following TypeScript code: export class MessageComponent implements OnInit { message: FormGroup; constructor(private formBuilder: FormBuilder, private messageService: MessageService) { } ...

Convert normal text to clickable links in chat messages within an angular application automatically

I'm working on incorporating a chat feature into an Angular application. One of my goals is to automatically detect URLs in the text that users enter and display them as clickable links when sent. So far, I have attempted to achieve this by using: & ...

React components need to refresh after fetching data from an API

I am currently working on a React application using TypeScript and integrating JSONPlaceholder for simulating API calls. I have successfully set up everything I need, but I am encountering an issue with re-rendering components that display response data fr ...

Swiper moves through different sections, while the navigation bar acts as pagination

I am currently utilizing next.js, typescript, and swiper. My goal is to highlight the current slide or section in the navigation bar. I was successful in achieving this with vanilla javascript at https://codepen.io/ms9ntQfa/pen/eYrxLxV but I'm unsure ...

After filtering the array in JavaScript, perform an additional process as a second step

My task involves manipulating an array through two methods in sequence: Filter the array Then, sort it The filter method I am using is as follows: filterArray(list){ return list.filter(item => !this.myCondition(item)); } The sort method I a ...

Angular version compatibility

I'm still learning about Angular builds, and I encountered an issue when updating our package.json file with the following content: { "name": "webapp", "version": "0.0.0", "scripts": { " ...

In Angular, the process of duplicating an array by value within a foreach function is not

I have been attempting to duplicate an array within another array and make modifications as needed. this.question?.labels.forEach((element) => { element["options"] = [...this.question?.options]; // I've tried json.stringify() as wel ...

"Encountering a 404 (Not Found) error when attempting to access local backend APIs through Angular

Recently, I integrated Angular Universal into my project to enhance performance and improve SEO. Everything was working smoothly when I ran 'ng serve', with the app able to communicate with the backend. However, when I tried running 'npm run ...

Getting the event of a directive in a dynamic component can be achieved by setting @HostDirective()

Check out this code snippet for dynamically creating a component: @Component({ selector: 'app-dynamic', template: `{{ message }}`, standalone: true, hostDirectives: [ { directive: OneDirective, outputs: ['change: mess ...