@@ -101,6 +101,54 @@ describe('Hash', function () {
101101 )
102102 } )
103103
104+ describe ( 'BaseHash padding and endianness' , ( ) => {
105+ it ( 'encodes length in big-endian for SHA1' , ( ) => {
106+ const sha1 = new ( hash as any ) . SHA1 ( )
107+ ; ( sha1 as any ) . pendingTotal = 12345
108+ const pad = ( sha1 as any ) . _pad ( ) as number [ ]
109+ const padLength = ( sha1 as any ) . padLength as number
110+ const lengthBytes = pad . slice ( - padLength )
111+
112+ const totalBits = BigInt ( 12345 ) * 8n
113+ const expected = new Array < number > ( padLength )
114+ let tmp = totalBits
115+ for ( let i = padLength - 1 ; i >= 0 ; i -- ) {
116+ expected [ i ] = Number ( tmp & 0xffn )
117+ tmp >>= 8n
118+ }
119+
120+ expect ( lengthBytes ) . toEqual ( expected )
121+ } )
122+
123+ it ( 'encodes length in little-endian for RIPEMD160' , ( ) => {
124+ const ripemd = new ( hash as any ) . RIPEMD160 ( )
125+ ; ( ripemd as any ) . pendingTotal = 12345
126+ const pad = ( ripemd as any ) . _pad ( ) as number [ ]
127+ const padLength = ( ripemd as any ) . padLength as number
128+ const lengthBytes = pad . slice ( - padLength )
129+
130+ const totalBits = BigInt ( 12345 ) * 8n
131+ const expected = new Array < number > ( padLength )
132+ let tmp = totalBits
133+ for ( let i = 0 ; i < padLength ; i ++ ) {
134+ expected [ i ] = Number ( tmp & 0xffn )
135+ tmp >>= 8n
136+ }
137+
138+ expect ( lengthBytes ) . toEqual ( expected )
139+ } )
140+
141+ it ( 'throws when message length exceeds maximum encodable bits' , ( ) => {
142+ const sha1 = new ( hash as any ) . SHA1 ( )
143+ ; ( sha1 as any ) . padLength = 1
144+ ; ( sha1 as any ) . pendingTotal = 40
145+
146+ expect ( ( ) => {
147+ ; ( sha1 as any ) . _pad ( )
148+ } ) . toThrow ( new Error ( 'Message too long for this hash function' ) )
149+ } )
150+ } )
151+
104152 describe ( 'PBKDF2 vectors' , ( ) => {
105153 for ( let i = 0 ; i < PBKDF2Vectors . length ; i ++ ) {
106154 const v = PBKDF2Vectors [ i ]
0 commit comments