Skip to content

Commit a9f021c

Browse files
committed
feat(hex): utility function for getting hex version of digest
1 parent c8ddf48 commit a9f021c

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) hashes.
2121
* [`Integrity#concat`](#integrity-concat)
2222
* [`Integrity#toString`](#integrity-to-string)
2323
* [`Integrity#pickAlgorithm`](#integrity-pick-algorithm)
24+
* [`IntegrityMetadata#hexDigest`](#integrity-metadata-hex-digest)
2425
* Integrity Generation
2526
* [`fromData`](#from-data)
2627
* [`fromStream`](#from-stream)
@@ -215,6 +216,17 @@ may intentionally deprioritize algorithms with known vulnerabilities.
215216
ssri.parse('sha1-WEakDigEST sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1').pickAlgorithm() // sha512
216217
```
217218

219+
#### <a name="integrity-metadata-hex-digest"></a> `> IntegrityMetadata#hexDigest() -> String`
220+
221+
Called on an *individual* `IntegrityMetadata` object, will convert its `digest`
222+
to a hex representation of the base64 data.
223+
224+
##### Example
225+
226+
```javascript
227+
ssri.parse('sha1-deadbeef', {single: true}).hexDigest() // '75e69d6de79f'
228+
```
229+
218230
#### <a name="from-data"></a> `> ssri.fromData(data, [opts]) -> Integrity`
219231

220232
Creates an `Integrity` object from either string or `Buffer` data, calculating

index.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ class IntegrityMetadata {
2929
const rawOpts = match[3]
3030
this.options = rawOpts ? rawOpts.slice(1).split('?') : []
3131
}
32+
hexDigest () {
33+
return this.digest && (
34+
Buffer.from
35+
? Buffer.from(this.digest, 'base64')
36+
: new Buffer(this.digest, 'base64')
37+
).toString('hex')
38+
}
3239
toString (opts) {
3340
if (opts && opts.strict) {
3441
// Strict mode enforces the standard as close to the foot of the

test/integrity.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,17 @@ test('pickAlgorithm()', t => {
8181
t.done()
8282
})
8383

84+
test('IntegrityMetadata.hexDigest()', t => {
85+
const sri = ssri.parse('sha512-bar', {single: true})
86+
t.equal(
87+
sri.hexDigest(),
88+
(
89+
Buffer.from ? Buffer.from('bar', 'base64') : new Buffer('bar', 'base64')
90+
).toString('hex'),
91+
'returned hex version of base64 digest')
92+
t.done()
93+
})
94+
8495
test('semi-private', t => {
8596
t.equal(ssri.Integrity, undefined, 'Integrity class is module-private.')
8697
t.done()

0 commit comments

Comments
 (0)