js如何实现自定义base64的加解密

function customBase64Encode(input) {
    const customAlphabet = "Dkdpgh2ZmsQB80/MfvV36XI1R45-WUAlEixNLwoqYTOPuzKFjJnry79HbGcaStCe";
    let encoded = '';
    for (let i = 0; i < input.length; i += 3) {
        let b1, b2, b3;
        b1 = input.charCodeAt(i);
        b2 = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
        b3 = i + 2 < input.length ? input.charCodeAt(i + 2) : 0;

        let buffer = (b1 << 16) | (b2 << 8) | b3;
        encoded += customAlphabet[(buffer >>> 18) & 63];
        encoded += customAlphabet[(buffer >>> 12) & 63];
        if (i + 1 < input.length) {
            encoded += customAlphabet[(buffer >>> 6) & 63];
        } else {
            encoded += '='; // padding
        }
        if (i + 2 < input.length) {
            encoded += customAlphabet[buffer & 63];
        } else {
            encoded += '='; // padding
        }
    }
    return encoded;
}

function customBase64Decode(input) {
    const customAlphabet = "Dkdpgh2ZmsQB80/MfvV36XI1R45-WUAlEixNLwoqYTOPuzKFjJnry79HbGcaStCe";
    const base64 = input.replace(/=/g, '');
    let decoded = '';
    const len = base64.length;
    let i = 0;

    while (i < len) {
        const c1 = customAlphabet.indexOf(base64[i++]);
        const c2 = customAlphabet.indexOf(base64[i++]);
        const c3 = customAlphabet.indexOf(base64[i++]);
        const c4 = customAlphabet.indexOf(base64[i++]);

        const buffer = (c1 << 18) | (c2 << 12) | (c3 << 6) | c4;

        const b1 = (buffer >> 16) & 0xff;
        const b2 = (buffer >> 8) & 0xff;
        const b3 = buffer & 0xff;

        if (c2 >= 0) decoded += String.fromCharCode(b1);
        if (c3 >= 0) decoded += String.fromCharCode(b2);
        if (c4 >= 0) decoded += String.fromCharCode(b3);
    }

    return decoded;
}
posted @ 2024-12-27 18:05  公众号python学习开发  阅读(9)  评论(0)    收藏  举报