Search code examples
algorithmdynamichashencodingvariable-length

Algorithm to hash a string to a dynamic number of characters


I'm looking for a way to hash a string to a dynamic number of characters. I don't want to trim an existing hash (such as SHA) but generate a hash that you can specify the number of output characters for. It should also work if the input is less than the number of characters. It doesn't need to be cryptographic, it only needs to guarantee the same hash for the same input. I've been going through the hash functions on wiki but they all seem to have a fixed length of a dynamic length depending on the input.


Solution

  • What you are looking for might be Extendable Output Functions (XOF's)!

    Those hash functions don't have predefined output length and might use sponge functions for construction.

    The SHA-3 family consists of four cryptographic hash functions, [...], and two extendable-output functions (XOFs), called SHAKE128 and SHAKE256.

    You can try out both under https://emn178.github.io/online-tools/. For the output bits choose your desired number or characters.

    For a Java implementation see the Bouncy Castle Crypto Library which supports both algorithms https://www.bouncycastle.org/specifications.html

    But be aware of collisions if the hash length is to small.