Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
var RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'
var CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
function createAlphabet (str) {
var lookup = {}
for (var i = 0; i < str.length; i++) {
lookup[str.charAt(i)] = i
}
return lookup
}

var RFC4648 = createAlphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567')
var RFC4648_HEX = createAlphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV')
var CROCKFORD = Object.assign(
createAlphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),
createAlphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'.toLowerCase()),
{
'o': 0,
'O': 0,
'i': 1,
'I': 1,
'l': 1,
'L': 1
}
)

function readChar (alphabet, char) {
var idx = alphabet.indexOf(char)
var idx = alphabet[char]

if (idx === -1) {
if (idx === undefined) {
throw new Error('Invalid character found: ' + char)
}

Expand All @@ -27,7 +46,7 @@ module.exports = function base32Decode (input, variant) {
break
case 'Crockford':
alphabet = CROCKFORD
input = input.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')
input = input.replace(/-+|([*~$=u]$)/ig, '')
break
default:
throw new Error('Unknown base32 variant: ' + variant)
Expand Down
16 changes: 15 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,27 @@ var testCases = [
['Crockford', '61', 'c4'],
['Crockford', '74657374', 'EHJQ6X0'],
['Crockford', '74657374', 'EHJQ6XO'],
['Crockford', '74657374', 'ehjq6xo'],
['Crockford', '6c696e7573', 'DHMPWXBK'],
['Crockford', '6c696e7573', 'DhmPWXbK'],
['Crockford', '666f6f626172', 'CSQPYRK1E8'],
['Crockford', '666f6f626172', 'CSQPYRKLE8'],
['Crockford', '666f6f626172', 'CSQPYRKIE8']
['Crockford', '666f6f626172', 'CSQPYRKIE8'],
['Crockford', '666f6f626172', 'csqpyrk1e8'],
['Crockford', '666f6f626172', 'csqpyrkle8'],
['Crockford', '666f6f626172', 'csqpyrkie8'],
['Crockford', '666f6f626172', 'csq-pyr---kle8--'],
['Crockford', '666f6f626172', 'csqpyrkie8*'],
['Crockford', '666f6f626172', 'csqpyrkie8~'],
['Crockford', '666f6f626172', 'csqpyrkie8$'],
['Crockford', '666f6f626172', 'csqpyrkie8='],
['Crockford', '666f6f626172', 'csqpyrkie8u'],
['Crockford', '666f6f626172', 'csqpyrkie8U']
]

testCases.forEach(function (testCase) {
assert(isEqual(base32Decode(testCase[2], testCase[0]), hexToArrayBuffer(testCase[1])))
})

assert.throws(function () { base32Decode('&', 'RFC4648-HEX') })
assert.throws(function () { base32Decode('&', 'Crockford') })