Skip to content

Commit 2640412

Browse files
committed
refactor: changed to bigint to avoid overflow
1 parent 3315c6f commit 2640412

File tree

2 files changed

+9
-9
lines changed

2 files changed

+9
-9
lines changed

packages/utilities/src/hmac.ts

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,18 @@ import crypto from 'crypto';
33
const CHARSET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
44

55
/**
6-
* Encodes number to base62.
6+
* Encodes BigInt to base62.
77
* To avoid new dependency, this function was copied from https://github.com/base62/base62.js/blob/master/lib/ascii.js
88
*/
9-
function encodeBase62(num: number) {
10-
if (num === 0) {
9+
function encodeBase62(num: bigint) {
10+
if (num === 0n) {
1111
return CHARSET[0];
1212
}
1313

1414
let res = '';
15-
while (num > 0) {
16-
res = CHARSET[num % 62] + res;
17-
num = Math.floor(num / 62);
15+
while (num > 0n) {
16+
res = CHARSET[Number(num % 62n)] + res;
17+
num /= 62n;
1818
}
1919
return res;
2020
}
@@ -33,5 +33,5 @@ export function createHmacSignature(secretKey: string, message: string): string
3333
.digest('hex')
3434
.substring(0, 30);
3535

36-
return encodeBase62(parseInt(signature, 16));
36+
return encodeBase62(BigInt(`0x${signature}`));
3737
}

test/hmac.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,14 @@ describe('createHmacSignature()', () => {
44
it('should create a valid HMAC signature', () => {
55
const secretKey = 'hmac-secret-key';
66
const message = 'hmac-message-to-be-authenticated';
7-
expect(createHmacSignature(secretKey, message)).toBe('pcVagAsud2gqKY2qCy2G');
7+
expect(createHmacSignature(secretKey, message)).toBe('pcVagAsudj8dFqdlg7mG');
88
});
99

1010
it('should create same HMAC signature, when secretKey and message are same', () => {
1111
const secretKey = 'hmac-same-secret-key';
1212
const message = 'hmac-same-message-to-be-authenticated';
1313
for (let i = 0; i < 5; i++) {
14-
expect(createHmacSignature(secretKey, message)).toBe('FYMcmTIm2sQ68EcG8yyQ');
14+
expect(createHmacSignature(secretKey, message)).toBe('FYMcmTIm3idXqleF1Sw5');
1515
}
1616
});
1717
});

0 commit comments

Comments
 (0)