Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs crypto in typescript file

I have created my own hash.js file that requires crypto and exports two functions that use crypto. It works fine in my api.js file when I hash passwords. However Now I am trying to import this file in my user.service.ts file so that I can send the hashed version of the password as a query parameter instead of the password itself. When I try to do so I always get a TypeScript error telling me that the functions crypto uses are not functions. However I can still console log the object I import and it looks legit to me. I looked at other java script files in the node_modules folder and I cannot see anything that should be wrong with my file.

I have also found out that there seems to be some definition file that I need to create but I have also had many attempts at creating such a file but nothing seems to work

A few hours of googling and the lack of knowledge amongst lack of time on this project led me to this post, it is my first stackoverflow post and I hope that it is not to unclear and I am glad to provide any information needed to help me resolve this issue.

Error code from console

LoginComponent.html:18 ERROR TypeError: crypto.randomBytes is not a function
at Object.genRandomString (hash.js:12)
at UserService.loginUser (user.service.ts:82)
at LoginComponent.getUser (login.component.ts:54)
at LoginComponent.onSubmit (login.component.ts:44)
at Object.eval [as handleEvent] (LoginComponent.html:18)
at handleEvent (core.es5.js:12014)
at callWithDebugContext (core.es5.js:13475)
at Object.debugHandleEvent [as handleEvent] (core.es5.js:13063)
at dispatchEvent (core.es5.js:8607)
at core.es5.js:10775

LoginComponent.html:18 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 31, nodeDef: {…}, elDef: {…}, elView: {…}}

the hash.js file


   'use strict';
    var crypto = require('crypto');

    /**
     * generates random string of characters i.e salt
     * @function
     * @param {number} length - Length of the random string.
     */
    function genRandomString (length){
        return crypto.randomBytes(Math.ceil(length/2))
                .toString('hex') /** convert to hexadecimal format */
                .slice(0,length);   /** return required number of characters */
    };

    /**
     * hash password with sha512.
     * @function
     * @param {string} password - List of required fields.
     * @param {string} salt - Data to be validated.
     */
    function sha512(password, salt){
        var hash = crypto.createHmac('sha512', salt); /** Hashing algorithm sha512 */
        hash.update(password);
        var value = hash.digest('hex');
        return {
            salt:salt,
            passwordHash:value
        };
    };

    module.exports = {
        genRandomString: genRandomString,
        sha512: sha512
    };

like image 512
Unnsteinn Garðarsson Avatar asked Jan 04 '18 11:01

Unnsteinn Garðarsson


People also ask

Is TypeScript good for Nodejs?

TypeScript is well-established in the Node. js world and used by many companies, open-source projects, tools and frameworks. Some of the notable examples of open-source projects using TypeScript are: NestJS - robust and fully-featured framework that makes creating scalable and well-architected systems easy and pleasant.

Is crypto built into Nodejs?

crypto is built into Node. js, so it doesn't require rigorous implementation process and configurations. Unlike other modules, you don't need to install Crypto before you use it in your Node. js application.

What is CryptoJS in node JS?

Crypto is a module in Node. js which deals with an algorithm that performs data encryption and decryption. This is used for security purpose like user authentication where storing the password in Database in the encrypted form. Crypto module provides set of classes like hash, HMAC, cipher, decipher, sign, and verify.


2 Answers

There seems to be some confusion mixing JavaScript and TypeScript, but since I came across this issue myself, here is how I solved it.

First, your hash.js file should be hash.ts. Then you can import crypto and use it normally. Related code below:

import * as crypto from "crypto";

  public setEncryptionKeyDES(sKey: string) {
    const desIV = Buffer.alloc(8);
    this.encLobby.cipher = crypto.createCipheriv(
      "des-cbc",
      Buffer.from(sKey, "hex"),
      desIV,
    );
    this.encLobby.cipher.setAutoPadding(false);
    this.encLobby.decipher = crypto.createDecipheriv(
      "des-cbc",
      Buffer.from(sKey, "hex"),
      desIV,
    );
    this.encLobby.decipher.setAutoPadding(false);

    this.isSetupComplete = true;
  }

Edit1: Adding @attdona's answer from below, make sure you install @types/node into your project as well, or you will receive many errors related to node modules not being found.

like image 193
Drazisil Avatar answered Sep 24 '22 15:09

Drazisil


Just hitted this issue (node v13.12.0, tsc v3.8.3). In my case the import:

import * as crypto from "crypto";

gives the error:

error TS2307: Cannot find module 'crypto'

because I have to install types definition for node: it includes crypto ambient declarations.

npm install @types/node

Note: If you have a global install of @types/node then you have to explicitly declare the path where @types are located with --typesRoot option. See here for details.

like image 30
attdona Avatar answered Sep 26 '22 15:09

attdona