2

I want to hash a string, but I don't want to implement the hashing algorithm. Is there a built-in JavaScript function or a dependable npm package to hash strings? If so, how do I use it to hash a string?

For example, if I have

const string = "password";

I want to run it through some kind of ready-made function or method, like this

const hash = hashFunction( string );

then get a hash from it, like this

console.log( hash ); //5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

NOTE: I'm aware that this question is similar to this question, but the chosen answer there implements hashing. I'm specifically looking for ready-built dependable functions or methods that hash.

2
  • You want a cryptographic hash? There are libraries like CryptoJS that can do that. Commented Dec 16, 2022 at 20:55
  • openbase.com/categories/js/… Commented Dec 16, 2022 at 20:57

1 Answer 1

7

I believe can simply use the built-in object.

It provides cryptographic functionality that includes the ability to hash strings.

const crypto = require('crypto');
const string = "password";
const hash = crypto.createHash('sha256').update(string).digest('hex'); 

console.log(hash);
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

Or as what @Spectric has mentioned, you can use the CryptoJS library.

const CryptoJS = require("crypto-js");

const string = "password";
const hash = CryptoJS.SHA256(string).toString();

console.log(hash);
Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

I hope this helps! :)

Sign up to request clarification or add additional context in comments.

3 Comments

keep in mind, the author hasn't specified if they're looking for a node or browser based solution.
@PatrykCieszkowski They tagged it node.js.
@gre_gor which doesn't say much, since they also tagged it #javascript and #hash. Node is used for compiling client-side apps. They're covering all possibilities.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.