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.
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
};