Skip to content

Commit

Permalink
Fix decoding of UTF8-encoded tokens (#297)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcospassos authored Dec 16, 2022
1 parent 2e83f81 commit 3f93924
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
14 changes: 12 additions & 2 deletions src/base64Url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,19 @@ function base64Escape(value: string): string {
}

export function base64UrlEncode(value: string): string {
return base64Escape(window.btoa(value));
return base64Escape(
window.btoa(
window.encodeURIComponent(value)
.replace(/%([0-9A-F]{2})/g, (_, p1) => String.fromCharCode(Number.parseInt(p1, 16))),
),
);
}

export function base64UrlDecode(value: string): string {
return window.atob(base64Unescape(value));
return window.decodeURIComponent(
Array.prototype.map.call(
window.atob(base64Unescape(value)),
(char: string) => `%${(`00${char.charCodeAt(0).toString(16)}`).slice(-2)}`,
).join(''),
);
}
7 changes: 1 addition & 6 deletions test/base64Url.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,14 @@ import {base64UrlDecode, base64UrlEncode} from '../src/base64Url';
describe('A base64 URL encoder/decoder function', () => {
const encodeTests = [
['000000', 'MDAwMDAw'],
['\0\0\0\0', 'AAAAAA'],
['\xff', '_w'],
['\xff\xff', '__8'],
['\xff\xff\xff', '____'],
['\xff\xff\xff\xff', '_____w'],
['\xfb', '-w'],
['', ''],
['f', 'Zg'],
['fo', 'Zm8'],
['foo', 'Zm9v'],
['foob', 'Zm9vYg'],
['fooba', 'Zm9vYmE'],
['foobar', 'Zm9vYmFy'],
['Jacaré', 'SmFjYXLDqQ'],
];

it.each(encodeTests)('should encode "%s" as "%s"', (decoded: string, encoded: string) => {
Expand Down

0 comments on commit 3f93924

Please sign in to comment.