Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Base64 編解碼原理、C 語言實作與 Linux 命令列用法

編碼原理

Base64 使用 US-ASCII 子集的 64 個字元:26 個大小寫英文字母、0~9、加號與斜線,對應值 0~63:

'A'..'Z'  → 0..25
'a'..'z'  → 26..51
'0'..'9'  → 52..61
'+'       → 62
'/'       → 63

編碼永遠以 3 個字元為一組,每字元 8 位元,共 24 位元,再切成 4 段各 6 位元,每段對應一個 Base64 值。若最後一組不足 3 字元,用 '=' 補齊。

以 "me" 為例:m 的 ASCII 是 109(01101101)、e 是 101(01100101),串接後是 0110110101100101,補零後每 6 位分組得到 011011、010110、010100,對應 27、22、20,也就是 b、W、U;不足 4 位補一個 '=',因此 "me" 的 Base64 是 bWU=。

對照表與 C 語言實作

核心是兩張表:解碼用的 map64(把 ASCII 映射回 0~63,無效字元填 -1)與編碼用的 alphabet64。

static char_t map64[] = {
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    ...
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
    /* 其餘填 -1 */
};

static char_t alphabet64[] = {
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/',
};

解碼:每 4 個字元查 map64 得到 4 個 6 位元值,依位移 18、12、6、0 併入 shiftbuf,再從高位移出 3 個 8 位元位元組。

int websDecode64(char_t *outbuf, char_t *string, int outlen)
{
    unsigned long shiftbuf;
    char_t *cp, *op;
    int c, i, j, shift;

    op = outbuf;
    *op = '\0';
    cp = string;

    while (*cp && *cp != '=') {
        shiftbuf = 0;
        shift = 18;
        for (i = 0; i < 4 && *cp && *cp != '='; i++, cp++) {
            c = map64[*cp & 0xff];
            if (c == -1) {
                error(E_L, E_LOG, T("Bad string: %s"), string);
                return -1;
            }
            shiftbuf = shiftbuf | (c << shift);
            shift -= 6;
        }
        --i;
        if ((op + i) >= &outbuf[outlen]) {
            gstrcpy(outbuf, T("String too big"));
            return -1;
        }
        for (j = 0; j < i; j++)
            *op++ = (char_t)((shiftbuf >> (8 * (2 - j))) & 0xff);
        *op = '\0';
    }
    return 0;
}

編碼則是反向操作:取 3 個字元併成 24 位元,再每 6 位元查 alphabet64 輸出,不足處補 '='。

void websEncode64(char_t *outbuf, char_t *string, int outlen)
{
    unsigned long shiftbuf;
    char_t *cp, *op;
    int x, i, j, shift;

    op = outbuf;
    *op = '\0';
    cp = string;

    while (*cp) {
        shiftbuf = 0;
        for (j = 2; j >= 0 && *cp; j--, cp++)
            shiftbuf |= ((*cp & 0xff) << (j * 8));

        shift = 18;
        for (i = ++j; i < 4 && op < &outbuf[outlen]; i++) {
            *op++ = alphabet64[(shiftbuf >> shift) & 0x3f];
            shift -= 6;
        }
        while (j-- > 0)     /* 補 '=' */
            *op++ = '=';
        *op = '\0';
    }
}

Linux 命令列用法

echo "str"  | base64        # 編碼(含換行)
echo -n "str" | base64       # 編碼(不含換行)
base64 file                     # 編碼檔案內容
base64 -d                       # 從標準輸入解碼
base64 -d -i                    # 解碼並忽略非字母表字元(如換行)
echo "str" | base64 -d         # 解碼字串
base64 -d file                  # 解碼檔案

實務上最常忘記的就是 -n:echo 預設會補一個換行,編碼結果 therefore 多出一段,解回來就多了尾端換行,常被誤判為 bug。

Copyright © Linux教程網 All Rights Reserved