diff --git a/src/hashes/digest.ts b/src/hashes/digest.ts index 93a7709a..e70d12e1 100644 --- a/src/hashes/digest.ts +++ b/src/hashes/digest.ts @@ -1,5 +1,6 @@ import { coerce, equals as equalBytes } from '../bytes.js' import * as varint from '../varint.js' +import { identity } from './identity.js' import type { MultihashDigest } from './interface.js' /** @@ -30,6 +31,9 @@ export function decode (multihash: Uint8Array): MultihashDigest { if (digest.byteLength !== size) { throw new Error('Incorrect length') } + if (code === 0x0 && size > identity.DefaultMaxIdentityDigestSize) { + throw new Error(`Identity digest exceeds maximum size of ${identity.DefaultMaxIdentityDigestSize} bytes`) + } return new Digest(code, size, digest, bytes) } diff --git a/src/hashes/identity.ts b/src/hashes/identity.ts index d13d575b..bafc2ab8 100644 --- a/src/hashes/identity.ts +++ b/src/hashes/identity.ts @@ -5,6 +5,8 @@ import type { DigestOptions } from './hasher.js' const code: 0x0 = 0x0 const name = 'identity' +const DefaultMaxIdentityDigestSize = 128 + const encode: (input: Uint8Array) => Uint8Array = coerce function digest (input: Uint8Array, options?: DigestOptions): Digest.Digest { @@ -16,7 +18,11 @@ function digest (input: Uint8Array, options?: DigestOptions): Digest.Digest DefaultMaxIdentityDigestSize) { + throw new Error(`Identity digest exceeds maximum size of ${DefaultMaxIdentityDigestSize} bytes`) + } + return Digest.create(code, encode(input)) } -export const identity = { code, name, encode, digest } +export const identity = { code, name, encode, digest, DefaultMaxIdentityDigestSize } diff --git a/test/test-multihash.spec.ts b/test/test-multihash.spec.ts index 31a57bcd..50ca08da 100644 --- a/test/test-multihash.spec.ts +++ b/test/test-multihash.spec.ts @@ -2,7 +2,7 @@ import { hash as slSha256 } from '@stablelib/sha256' import { hash as slSha512 } from '@stablelib/sha512' -import { assert } from 'aegir/chai' +import { assert, expect } from 'aegir/chai' import { sha1 as chSha1 } from 'crypto-hash' import { fromHex, fromString } from '../src/bytes.js' import { decode as decodeDigest, create as createDigest, hasCode as digestHasCode } from '../src/hashes/digest.js' @@ -172,6 +172,11 @@ describe('multihash', () => { assert.deepStrictEqual(hash2.bytes, hash.bytes) }) + it('hash identity oversized', () => { + const oversized = new Uint8Array(129).fill(0x61) + expect(() => identity.digest(oversized)).to.throw(/Identity digest exceeds maximum size of 128 bytes/) + }) + it('hash identity truncated', async () => { const hash = identity.digest(fromString('test'), { truncate: 2