|
| 1 | +/* eslint-disable require-await */ |
1 | 2 | 'use strict'
|
2 | 3 |
|
3 | 4 | const { Buffer } = require('buffer')
|
| 5 | +const multihash = require('multihashes') |
4 | 6 |
|
5 | 7 | const crypto = self.crypto || self.msCrypto
|
6 | 8 |
|
7 |
| -module.exports = (algorithm) => { |
| 9 | +const digest = async (data, alg) => { |
8 | 10 | if (typeof self === 'undefined' || (!self.crypto && !self.msCrypto)) {
|
9 | 11 | throw new Error(
|
10 | 12 | 'Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context'
|
11 | 13 | )
|
12 | 14 | }
|
13 |
| - |
14 |
| - return async (data) => { |
15 |
| - switch (algorithm) { |
16 |
| - case 'sha1': |
17 |
| - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-1' }, data)) |
18 |
| - case 'sha2-256': |
19 |
| - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, data)) |
20 |
| - case 'sha2-512': |
21 |
| - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-512' }, data)) |
22 |
| - case 'dbl-sha2-256': { |
23 |
| - const d = await crypto.subtle.digest({ name: 'SHA-256' }, data) |
24 |
| - return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, d)) |
25 |
| - } |
26 |
| - default: |
27 |
| - throw new Error(`${algorithm} is not a supported algorithm`) |
| 15 | + switch (alg) { |
| 16 | + case 'sha1': |
| 17 | + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-1' }, data)) |
| 18 | + case 'sha2-256': |
| 19 | + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, data)) |
| 20 | + case 'sha2-512': |
| 21 | + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-512' }, data)) |
| 22 | + case 'dbl-sha2-256': { |
| 23 | + const d = await crypto.subtle.digest({ name: 'SHA-256' }, data) |
| 24 | + return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, d)) |
28 | 25 | }
|
| 26 | + default: |
| 27 | + throw new Error(`${alg} is not a supported algorithm`) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +module.exports = { |
| 32 | + factory: (alg) => async (data) => { |
| 33 | + return digest(data, alg) |
| 34 | + }, |
| 35 | + digest, |
| 36 | + multihashing: async (buf, alg, length) => { |
| 37 | + const h = await digest(buf, alg, length) |
| 38 | + return multihash.encode(h, alg, length) |
29 | 39 | }
|
30 | 40 | }
|
0 commit comments