forked from torusresearch/torus-website
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathintegrity.js
44 lines (36 loc) · 1.06 KB
/
integrity.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import createHash from 'create-hash/browser'
const defaults = (options) => ({
algorithms: options.algorithms || ['sha256'],
delimiter: options.delimiter || ' ',
full: options.full || false,
})
// Generate hash
const digest = (algorithm, data) => createHash(algorithm).update(data, 'utf8').digest('base64')
// Generate list of hashes
const hashes = (options, data) => {
const internalHashes = {}
options.algorithms.forEach((algorithm) => {
internalHashes[algorithm] = digest(algorithm, data)
})
return internalHashes
}
// Build an integrity string
const integrity = (options, sri) => {
let output = ''
// Hash list
output += Object.keys(sri.hashes)
.map((algorithm) => `${algorithm}-${sri.hashes[algorithm]}`)
.join(options.delimiter)
return output
}
const main = (options, data) => {
// Defaults
const finalOptions = defaults(options)
const sri = {
hashes: hashes(finalOptions, data),
integrity: undefined,
}
sri.integrity = integrity(finalOptions, sri)
return finalOptions.full ? sri : sri.integrity
}
export default main