Skip to content

Instantly share code, notes, and snippets.

@teidesu
Created June 22, 2021 13:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teidesu/9162403a4d32d3adc6234c6db0a2bf81 to your computer and use it in GitHub Desktop.
Save teidesu/9162403a4d32d3adc6234c6db0a2bf81 to your computer and use it in GitHub Desktop.
JavaScript Base32 implementation
// 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