Skip to content

Support truncated hashes #328

@achingbrain

Description

@achingbrain

It's common practice to truncate some message digests (see 5.1 of Recommendation for Applications
Using Approved Hash Algorithms
).

This proposal is to add a truncate option to hasher.digest and also enforcing min/max hash lengths:

const sha512 = from({
  name: 'sha2-512',
  code: 0x13,
  encode: input => coerce(crypto.createHash('sha512').update(input).digest()),

  // constrain digest truncation - default options are shown, inspired by
  // https://github.com/ipfs/boxo/blob/main/verifcid/cid.go#L17-L20
  // minDigestLength: 20,
  // maxDigestLength: 128

  // use default minDigestLength but constrain max to value specific to hash algorithm
  maxDigestLength: 64
})

// input data
const buf = Uint8Array.from([0, 1, 2, 3])

// sha2-512 hash truncated to 32 bytes
const digest = await sha512.digest(buf, {

  // passing < minDigestLength or > maxDigestLength would cause this to throw
  truncate: 32
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions