base64

Base64编码机制

在C语言中实现Base64编码,你可以使用以下步骤:

1:将输入数据每6位分组并扩展为8位。

2:根据Base64编码表(下面给出)转换每个8位组。

3:如果输入数据不是3的倍数,则需要填充(pad)到3的倍数长度。

Base64编码表:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

编码流程:

/**
 * @function name:	base64_table
 * @brief  使用base64编码对应字符串
 * @param  @:const unsigned char in   需转型字符串
           @:转出数据存储数组
           @:字符串长度
 * @retval 函数返回类型说明
 * @date 2024/06/11
 * @version 1.0 :版本       
 * @note   补充 注意 说明
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Base64编码表
static const char base64_table[] = {
    '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', '+', '/'
};

// 将3个字节转换为4个6位Base64编码字符
void encode_block(const unsigned char in[3], char out[4], int len) {
    out[0] = base64_table[(in[0] & 0xfc) >> 2];
    out[1] = base64_table[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
    out[2] = base64_table[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)];
    out[3] = base64_table[in[2] & 0x3f];
    // 如果输入不足3个字节,则填充'='
    if (len < 3) out[3] = '=';
    if (len < 2) out[2] = '=';
    if (len < 1) out[0] = '=';
}

// Base64编码函数
char* base64_encode(const unsigned char* data, size_t input_length) {
    // 计算输出长度,需要4/3的输入长度
    size_t output_length = (input_length + 2) / 3 * 4;
    char* result = (char*)malloc(output_length + 1);
    char* output = result;

    // 对于输入数据的每3个字节进行编码
    int i;
    for (i = 0; i < input_length; i += 3) {
        encode_block(data + i, output, (int)input_length - i);
        output += 4;
    }
     
    // 添加字符串终止符
    *output = '\0';
     
    return result;

}

int main() {
    const char* text = "Man"; // 需要编码的字符串
    size_t text_length = strlen(text);
    char* encoded = base64_encode((const unsigned char*)text, text_length);
    printf("Encoded: %s\n", encoded);
    free(encoded); // 释放动态分配的内存
    return 0;

}
posted @ 2024-06-11 20:38  Zeratul$$$  阅读(45)  评论(0)    收藏  举报