'Generate a secure numeric hash from string in Node
I would like to generate a secure digit code of fixed length from a string in Node. The interface would look something like:
hashStringToNumericCode("arandomhash", 6) => "041558"
The idea would be to use the generated code as a type of password. So it doesn't need to be unique, but it should be randomly distributed. Assume that the input string is the output of a SHA-1 hash function. In other words, assume that the input string is randomly distributed.
How could that be implemented?
Solution 1:[1]
function hashStringToNumericCode (word, length) {
let num = 1
for (let i = 0; i < word.length; i++) {
const bufferValue = Buffer.from(word[i])
const intValue = parseInt(bufferValue.toString('hex'), 16)
num *= intValue
}
let modulusNumber = ''
for (let i = 0; i < length; i++) {
modulusNumber += '9'
}
modulusNumber = parseInt(modulusNumber)
num %= modulusNumber
console.log(num)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cWerning |
