gleam/crypto

Set of cryptographic functions.

Types

pub type HashAlgorithm {
  Sha224
  Sha256
  Sha384
  Sha512
}

Constructors

  • Sha224
  • Sha256
  • Sha384
  • Sha512

Functions

pub external fn hash(HashAlgorithm, BitString) -> BitString

Computes a digest of the input bit string.

pub fn hmac(data: BitString, algorithm: HashAlgorithm, key: BitString) -> BitString

Calculates the HMAC (hash-based message authentication code) for a bit string.

Based on the Erlang crypto:mac function.

pub fn secure_compare(left: BitString, right: BitString) -> Bool

Compares the two binaries in constant-time to avoid timing attacks.

For more details see: http://codahale.com/a-lesson-in-timing-attacks/

pub fn sign_message(message: BitString, secret: BitString, digest_type: HashAlgorithm) -> String

Sign a message which can later be verified using the verify_signed_message function to detect if the message has been tampered with.

A web application could use this verifier to sign HTTP cookies. The data can be read by the user, but cannot be tampered with.

pub external fn strong_random_bytes(Int) -> BitString

Generates N bytes randomly uniform 0..255, and returns the result in a binary.

Uses a cryptographically secure prng seeded and periodically mixed with operating system provided entropy. By default this is the RAND_bytes method from OpenSSL.

https://erlang.org/doc/man/crypto.html#strong_rand_bytes-1

pub fn verify_signed_message(message: String, secret: BitString) -> Result(
  BitString,
  Nil,
)

Verify a message created by the sign_message function.