kmh

Types

Errors that can occur when validating a hasher.

pub type Error {
  TooLargePrime
  TooLargeRandom
  NotAPrime
  InvalidModularInverse
}

Constructors

  • TooLargePrime
  • TooLargeRandom
  • NotAPrime
  • InvalidModularInverse

A hash function that generates obfuscated values according to Donald Knuth’s multiplicative hashing algorithm.

  • The hash function is bijective, meaning that it maps a number to a number between 0 and the maximum value.
  • The hash function is deterministic, meaning that it always generates the same output for the same input.
  • The hash function is collision resistant, meaning that it is impossible to find two different numbers that map to the same encoded value.
  • The hash function is “one-way”, in the sense that it is infeasible to find the number that maps to a given encoded value (without knowing the hash parameters).
pub opaque type Hasher(validated)
pub type Unvalidated
pub type Valid

Functions

pub fn decode(h: Hasher(Valid), number: Int) -> Int

Decode a number.

The encoded value must be between 0 and the maximum value.

pub fn encode(h: Hasher(Valid), number: Int) -> Int

Encode a number.

The number must be between 0 and the maximum value.

pub fn max_size(
  h: Hasher(Unvalidated),
  max_size: Int,
) -> Hasher(Unvalidated)

Set the maximum size (in bits) of the values that can be generated.

Defaults to 31 bits, leading to a maximum value of 2^31 - 1.

Note: This must be called before validate.

pub fn new(
  prime prime: Int,
  mod_inverse mod_inverse: Int,
  random random: Int,
) -> Hasher(Unvalidated)

Create a new hasher.

The prime, mod_inverse and random values must be chosen such that the following conditions are met:

  • The prime is a prime number.
  • The mod_inverse is the modular multiplicative inverse of the prime.
  • The random value is a random number between 0 and the maximum value.
pub fn unsafe_decode(h: Hasher(a), number: Int) -> Int

Unsafe version of decode.

This function bypasses the validation of the hasher. Only use this if you know what you are doing.

pub fn unsafe_encode(h: Hasher(a), number: Int) -> Int

Unsafe version of encode.

This function bypasses the validation of the hasher. Only use this if you know what you are doing.

pub fn validate(
  h: Hasher(Unvalidated),
) -> Result(Hasher(Valid), Error)

Validate the hasher.

Returns an error if the hasher was not created with valid parameters. Returns the hasher if it was valid.

Search Document