Created
June 22, 2021 13:11
-
-
Save teidesu/9162403a4d32d3adc6234c6db0a2bf81 to your computer and use it in GitHub Desktop.
JavaScript Base32 implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This file is licensed under LGPLv3 | |
// (c) teidesu 2020 | |
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' | |
const padLength = [0, 1, 3, 4, 6] | |
const padChar = '=' | |
function encode (buf) { | |
let arr = [...buf] | |
let len = arr.length | |
let ret = '' | |
let i = 0 | |
while (arr.length % 5) arr.push(0) | |
while (i < len) { | |
let c1 = arr[i++] | |
let c2 = arr[i++] | |
let c3 = arr[i++] | |
let c4 = arr[i++] | |
let c5 = arr[i++] | |
ret += alphabet[(c1 >> 3)] | |
ret += alphabet[((c1 & 0x07) << 2) | (c2 >> 6)] | |
ret += alphabet[((c2 & 0x3F) >> 1)] | |
ret += alphabet[((c2 & 0x01) << 4) | (c3 >> 4)] | |
ret += alphabet[((c3 & 0x0F) << 1) | (c4 >> 7)] | |
ret += alphabet[((c4 & 0x7F) >> 2)] | |
ret += alphabet[((c4 & 0x03) << 3) | (c5 >> 5)] | |
ret += alphabet[(c5 & 0x1F)] | |
} | |
if (i > len) { | |
i = padLength[i - len] | |
ret = ret.substr(0, ret.length - i) | |
while (ret.length % 8 !== 0) ret += padChar | |
} | |
return ret | |
} | |
function decode (str) { | |
let ret = [] | |
let len = str.length | |
let bits = 0 | |
let charBuffer = 0 | |
while (len > 0 && str[len - 1] === padChar) --len | |
for (let i = 0; i < len; i++) { | |
charBuffer = (charBuffer << 5) | alphabet.indexOf(str[i]) | |
bits += 5 | |
if (bits >= 8) { | |
ret.push((charBuffer >> (bits - 8)) & 0xff) | |
bits -= 8 | |
} | |
} | |
return Buffer.from(ret) | |
} | |
module.exports = { | |
encode, | |
decode | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment