paulmillr / noble-hashes

Audited & minimal JS implementation of hash functions, MACs and KDFs.
https://paulmillr.com/noble
MIT License
573 stars 46 forks source link

hmac check seems to not work correctly in extension background contexts #38

Closed aulneau closed 2 years ago

aulneau commented 2 years ago

I've been playing around with using some of the noble libs in web extensions, specifically in the background context which is similar to service workers, and this line causes issues:

https://github.com/paulmillr/noble-hashes/blob/8b0fb5fb9485393df2896d380643a978de8714cf/src/hmac.ts#L17

When I console.log the iHash this is what we get:

{
    "blockLen": 64,
    "outputLen": 32,
    "padOffset": 8,
    "isLE": false,
    "finished": true,
    "length": 128,
    "pos": 0,
    "destroyed": false,
    "buffer": {
       // removed for brevity
    },
    "view": {},
    "A": 0,
    "B": 0,
    "C": 0,
    "D": 0,
    "E": 0,
    "F": 0,
    "G": 0,
    "H": 0
}

When I patch-package the hmac file and remove the conditional check, it works as expected.

Curious what we could do to make it work in this context? webcrypto should be fully supported

paulmillr commented 2 years ago

I don't see how background context is related to this line. Perhaps it's something else.

aulneau commented 2 years ago

oh yeah, sorry, the hashing i'm using is sha256:

import { ensureUint8Array } from './common';

import { hmac } from '@noble/hashes/hmac';
import { sha256 } from '@noble/hashes/sha256';

export function hmacSha256(key: Uint8Array, ...messages: Uint8Array[]): Uint8Array {
  const hash = hmac.create(sha256, ensureUint8Array(key));
  for (const message of messages) {
    hash.update(ensureUint8Array(message));
  }
  return Uint8Array.from(hash.digest());
}

so it might be the case that the sha256 class isn't correctly implementing the hash class you have defined on L17?

paulmillr commented 2 years ago

If it wasn't correct, the test wouldn't pass. I'm guessing it something else like some global variable not available in background context.

paulmillr commented 2 years ago

Do you know what is the simplest way to debug background page?

xorgal commented 2 years ago

Hey, I see that source was recently updated to:

if (typeof this.iHash.update !== 'function')

I'm having the same issue with previous equation if (!(this.iHash instanceof Hash)) and dependency that is relaying on @nobles/hashes is failing in production but works flawless with new comparison.

Would be great to update npm package with this change. Thanks!

paulmillr commented 2 years ago

landed in 1.1.3