Search code examples
javascripttypescriptstringnumbersgenerator

Generate fixed length unique string from 2


I have two numbers 919572562474827787 and 359678229096955904

I need to generate a unique string with fixed length so I can regenerate it again and get the same value. How can I do it?


Solution

  • You can do this with built-in functions from SubtleCrypto.

    This function will return a cryptographically secure SHA-256 hash of the numbers. This will work independent of the system you run this with, and return the same output for the same input.

    const hash = async (number1, number2) => btoa(String.fromCharCode.apply(null, new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(number1+number2)))))
    
    hash("919572562474827787","359678229096955904").then(console.log)
    // => XG14mUazSAw/JpETwqHsijVgVdjdCOnczr5MMBU6qBc=