【问题标题】:decode base64url as uint8array将 base64url 解码为 uint8array
【发布时间】:2022-01-10 13:01:13
【问题描述】:

我正在尝试将 JWT 令牌签名字符串转换为 uint8array。

lX_aBSgGVYWd2FL6elRHoPJ2nab0IkmmX600cwZPCyK_SazZ-pzBUGDDQ0clthPVAtoS7roHg14xpEJlcSJUZBA7VTlPiDCOrkie_Hmulj765qS44t3kxAYduLhNQ-VN

预期的结果应该是如下,大小为96(base64url编码)

[149, 127, 218, 5, 40, 6, 85, 133, 157, 216, 82, 250, 122, 84, 71, 160, 242, 118, 157, 166, 244, 34, 73, 166, 95, 173, 52, 115, 6, 79, 11, 34, 191, 73, 172, 217, 250, 156, 193, 80, 96, 195, 67, 71, 37, 182, 19, 213, 2, 218, 18, 238, 186, 7, 131, 94, 49, 164, 66, 101, 113, 34, 84, 100, 16, 59, 85, 57, 79, 136, 48, 142, 174, 72, 158, 252, 121, 174, 150, 62, 250, 230, 164, 184, 226, 221, 228, 196, 6, 29, 184, 184, 77, 67, 229, 77]

但我无法对其进行逆向工程,我一直得到 64 的大小

[103, 10, 34, 6, 104, 125, 101, 234, 5, 23, 143, 198, 138, 228, 164, 134, 170, 116, 240, 159, 82, 223, 58, 73, 9, 49, 70, 51, 52, 229, 241, 5, 45, 146, 219, 135, 53, 177, 148, 181, 210, 164, 145, 59, 99, 95, 35, 46, 212, 62, 247, 142, 115, 234, 186, 88, 173, 148, 16, 157, 235, 29, 62, 93

这是我最初用于 base16 的函数,我现在尝试修改它以适用于 base64url

        const convert = (str) => {
            const segmented = str.match(/.{1,2}/g);
            const arr = segmented.map((segment, i) => {
                const powers = [16,1]; 
                const alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; 
                const two_bits = segment.split(''); 

                const result_arr = two_bits.map((hex, i) => {
                    const decimal = alphabets.indexOf(hex);
                    const sum_of_power = powers[i] * decimal;
                    return sum_of_power;
                });

                const result = result.reduce((a, b) => a + b);

                return result;
            });

            return new Uint8Array(arr);

        };

任何帮助将不胜感激!

【问题讨论】:

    标签: encoding jwt cryptography digital-signature uint8array


    【解决方案1】:

    这是 base64url 解码代码,取自我的 jose 通用 javascript 模块,我建议您将其用于任何和所有 JOSE 功能,而不是自己编写。

    const decodeBase64 = (encoded) => {
        return new Uint8Array(atob(encoded)
            .split('')
            .map((c) => c.charCodeAt(0)));
    };
    
    const decode = (input) => {
        try {
            return decodeBase64(input.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, ''));
        }
        catch (_a) {
            throw new TypeError('The input to be decoded is not correctly encoded.');
        }
    };
    
    decode('lX_aBSgGVYWd2FL6elRHoPJ2nab0IkmmX600cwZPCyK_SazZ-pzBUGDDQ0clthPVAtoS7roHg14xpEJlcSJUZBA7VTlPiDCOrkie_Hmulj765qS44t3kxAYduLhNQ-VN')
    

    【讨论】:

    • 非常感谢!我能问一下为什么我们需要替换这些字符吗? input.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '')?这个过程叫什么,我可以自己更深入地研究它?
    • 它将base64url改回常规base64(尽管没有填充),以便可以将其传递给atob
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2017-08-17
    • 2017-07-27
    • 2011-07-11
    • 2017-08-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多