jiangts / JS-OTP

100% Javascript Implementation of HOTP and TOTP for Two-Factor Authentication.
https://jiangts.github.io/JS-OTP
MIT License
256 stars 70 forks source link

Base64 implementation is broken #15

Closed duoduobingbing closed 2 years ago

duoduobingbing commented 2 years ago

The implementation for Base64ToHex in this project is broken for Base64 strings that do not amount to a multiply of eight.

Replacing base32tohex in jsOTP.js fixes those issues:

base32tohex(base32) {

            let base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
            let bits = [];

            for (let i = 0; i < base32.length; i++) {
                let intVal = base32chars.indexOf(base32.charAt(i).toUpperCase());

                if (intVal === -1 || intVal === null) {
                    throw new Error("Invalid B64 char: " + base32.charAt(i));
                }

                let binaryRep = intVal.toString(2);
                let diffLen = 5 - binaryRep.length;

                for (let j = 0; j < diffLen; j++) {
                    bits.push("0");
                }

                for (let j = 0; j < binaryRep.length; j++) {
                    bits.push(binaryRep[j]);
                }
            }

            let hexstr = "";
            for (let i = 0; i < bits.length; i += 8) {
                let binByte = bits.slice(i, i + 8).join("");
                if (binByte.length < 8) {
                    continue;
                }
                let hexn = parseInt(binByte, 2).toString(16);

                hexstr += hexn.length === 2 ? hexn : "0" + hexn;
            }

            return hexstr;
}