Added alphabet check before decoding #7
18
node-atob.js
18
node-atob.js
|
@ -1,6 +1,24 @@
|
|||
"use strict";
|
||||
|
||||
// var b64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
|
||||
|
||||
function toCharCode(ch) {
|
||||
return ch.charCodeAt(0);
|
||||
}
|
||||
|
||||
function isValidB64Char(charCode) {
|
||||
return charCode >= toCharCode('A') && charCode <= toCharCode('Z')
|
||||
|| charCode >= toCharCode('a') && charCode <= toCharCode('z')
|
||||
|| charCode >= toCharCode('0') && charCode <= toCharCode('9')
|
||||
|| charCode === toCharCode('+')
|
||||
|| charCode === toCharCode('/')
|
||||
|| charCode === toCharCode('=');
|
||||
}
|
||||
|
||||
function atob(str) {
|
||||
for (var idx in str)
|
||||
if (!isValidB64Char(str.charCodeAt(idx)))
|
||||
throw new Error('Invalid character ' + str.charAt(idx) + ' in base64 String');
|
||||
return Buffer.from(str, 'base64').toString('binary');
|
||||
}
|
||||
|
||||
|
|
11
test.js
11
test.js
|
@ -2,8 +2,9 @@
|
|||
"use strict";
|
||||
|
||||
var atob = require('.');
|
||||
var encoded = "SGVsbG8sIFdvcmxkIQ=="
|
||||
var encoded = "SGVsbG8sIFdvcmxkIQ==";
|
||||
var unencoded = "Hello, World!";
|
||||
var malformed = "SGVsbG8s{";
|
||||
/*
|
||||
, encoded = "SGVsbG8sIBZM"
|
||||
, unencoded = "Hello, 世界"
|
||||
|
@ -14,5 +15,13 @@
|
|||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var decoded = atob(malformed);
|
||||
console.log('[FAIL]', malformed, decoded);
|
||||
return;
|
||||
} catch (_) {
|
||||
/* pass */
|
||||
}
|
||||
|
||||
console.log('[PASS] all tests pass');
|
||||
}());
|
||||
|
|
Loading…
Reference in New Issue