11import { createHash } from 'node:crypto' ;
22import {
3- ByteSequence ,
43 type Item ,
5- isByteSequence ,
64 isInnerList ,
75 parseDictionary ,
86 serializeDictionary ,
@@ -62,14 +60,7 @@ export function createContentDigestHeader(
6260 algorithms . map ( ( algo ) => {
6361 return [
6462 algo ,
65- [
66- new ByteSequence (
67- createHash ( nodeAlgo ( algo ) )
68- . update ( body || '' )
69- . digest ( 'base64' ) ,
70- ) ,
71- new Map ( ) ,
72- ] ,
63+ [ toArrayBuffer ( hashBody ( body , algo ) ) , new Map ( ) ] ,
7364 ] as readonly [ string , Item ] ;
7465 } ) ,
7566 ) ,
@@ -89,17 +80,28 @@ export function verifyContentDigest(
8980) {
9081 const digests = parseDictionary ( digestHeader ) ;
9182 for ( const [ algo , digest ] of digests ) {
92- if ( isInnerList ( digest ) || ! isByteSequence ( digest [ 0 ] ) ) {
83+ if ( isInnerList ( digest ) || ! ( digest [ 0 ] instanceof ArrayBuffer ) ) {
9384 throw new Error (
9485 `Invalid value for digest with algorithm key of '${ algo } '` ,
9586 ) ;
9687 }
97- const hash = createHash ( nodeAlgo ( algo ) )
98- . update ( body || '' )
99- . digest ( 'base64' ) ;
100- if ( digest [ 0 ] . toBase64 ( ) !== hash ) {
88+ const hash = hashBody ( body , algo ) ;
89+ if ( ! hash . equals ( Buffer . from ( digest [ 0 ] ) ) ) {
10190 return false ;
10291 }
10392 }
10493 return true ;
10594}
95+
96+ function hashBody ( body : string | Buffer | undefined , algo : string ) : Buffer {
97+ return createHash ( nodeAlgo ( algo ) )
98+ . update ( body || '' )
99+ . digest ( ) ;
100+ }
101+
102+ function toArrayBuffer ( buffer : Buffer ) : ArrayBuffer {
103+ return buffer . buffer . slice (
104+ buffer . byteOffset ,
105+ buffer . byteOffset + buffer . byteLength ,
106+ ) ;
107+ }
0 commit comments