@libp2p/crypto
Version:
Crypto primitives for libp2p
36 lines (30 loc) • 862 B
text/typescript
import webcrypto from '../webcrypto/index.js'
import lengths from './lengths.js'
const hashTypes = {
SHA1: 'SHA-1',
SHA256: 'SHA-256',
SHA512: 'SHA-512'
}
const sign = async (key: CryptoKey, data: Uint8Array): Promise<Uint8Array> => {
const buf = await webcrypto.get().subtle.sign({ name: 'HMAC' }, key, data)
return new Uint8Array(buf, 0, buf.byteLength)
}
export async function create (hashType: 'SHA1' | 'SHA256' | 'SHA512', secret: Uint8Array): Promise<{ digest(data: Uint8Array): Promise<Uint8Array>, length: number }> {
const hash = hashTypes[hashType]
const key = await webcrypto.get().subtle.importKey(
'raw',
secret,
{
name: 'HMAC',
hash: { name: hash }
},
false,
['sign']
)
return {
async digest (data: Uint8Array) {
return sign(key, data)
},
length: lengths[hashType]
}
}