C语言 base32与base64加解密

概述

        Base32、Base64编码就是分别用32个、64个可打印字符表示二进制数据。

运行环境:Microsoft Visual Studio Community 2022 (64 位) - Current  版本 17.6.4

 一、Base32规则

        32 = 2^5,所以需要5 Bit来表示一个base32字符。一个字节8 Bit,5和8的最小公倍数是40。编码的过程中,以5个字节为一组转为8个base32字符,不足5个字节以0代替。为方便转换,以一个无符号64位整数(uint64_t)为中间载体。先由高位到低位将这5个字节填充到这个整数中,然后由高位到低位依次读取5位,获取对应数值的字母,共读取8次。如下图所示。解码的过程是上述的逆过程。

二、示例

1、base32.h

#ifndef _BASE32_H
#define _BASE32_H

#include <stdint.h>


char *base32_encode(const char *str, uint64_t len);
char *base32_parse(const char *base32Str, uint64_t len);

#endif //_BASE32_H

2、base32.c

#include "base32.h"
#include <stdlib.h>

#ifndef CEIL_POS
#define CEIL_POS(X) (X > (uint64_t)(X) ? (uint64_t)(X+1) : (uint64_t)(X))
#endif

static const char BASE32_MAP[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=";
static const uint8_t BASE32_REVERSE_MAP[] = {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
};

char *base32_encode(const char *str, uint64_t len) 
{
    uint64_t length = CEIL_POS(len * 8 / 5) + 1;
    char *base32Chars = (char *) malloc(sizeof(char) * length);
    uint64_t idx = 0;

    for (uint64_t i = 0; i < len; i += 5) {
        uint64_t byte1 = (uint8_t) str[i];
        uint64_t byte2 = (i + 1 < len) ? (uint8_t) str[i + 1] : 0;
        uint32_t byte3 = (i + 2 < len) ? (uint8_t) str[i + 2] : 0;
        uint16_t byte4 = (i + 3 < len) ? (uint8_t) str[i + 3] : 0;
        uint8_t byte5 = (i + 4 < len) ? (uint8_t) str[i + 4] : 0;

        uint64_t quintuple = (byte1 << 32) | (byte2 << 24) | (byte3 << 16) | (byte4 << 8) | byte5;

        for (uint64_t j = 0; (j < 8) && (i + j * 0.625 < len); j++) {
            base32Chars[idx] = BASE32_MAP[(quintuple >> (5 * (7 - j))) & 0x1f];
            idx++;
        }
    }

    char paddingChar = BASE32_MAP[32];
    if (paddingChar) {
        while (idx % 8) {
            base32Chars[idx] = paddingChar;
            idx++;
        }
    }
    base32Chars[idx] = 0;
    return base32Chars;
}

char *base32_parse(const char *base32Str, uint64_t len) 
{
    while (base32Str[len - 1] == BASE32_MAP[32]) {
        len--;
    }
    uint64_t length = CEIL_POS(len * 5 / 8) + 1;
    char *str = (char *) malloc(sizeof(char) * length);
    uint64_t idx = 0;

    for (uint64_t i = 0; i < len; i += 8) {
        uint64_t quintuple = 0;
        for (uint8_t j = 0; j < 8; ++j) {
            if (i + j < len) quintuple = (quintuple << 5) | ((uint8_t) BASE32_REVERSE_MAP[base32Str[i + j]] & 0x1f);
            else quintuple = quintuple << 5;
        }
        for (uint8_t j = 0; (j < 5); ++j) {
            str[idx] = (quintuple >> (8 * (4 - j))) & 0xff;
            idx++;
        }
    }
    str[idx] = 0;
    return str;
}

3、main.c

#include <stdio.h>
#include <string.h>
#include "base32.h"
#include "stdlib.h"


int main(void)
{

char str1[] = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
    char *encoded = base32_encode(str1, strlen(str1));
    printf("encode:%s \r\n",encoded);

    char str2[] = "JVQW4IDJOMQGI2LTORUW4Z3VNFZWQZLEFQQG433UEBXW43DZEBRHSIDINFZSA4TFMFZW63RMEBRHK5BAMJ4SA5DINFZSA43JNZTXK3DBOIQHAYLTONUW63RAMZZG63JAN52GQZLSEBQW42LNMFWHGLBAO5UGSY3IEBUXGIDBEBWHK43UEBXWMIDUNBSSA3LJNZSCYIDUNBQXIIDCPEQGCIDQMVZHGZLWMVZGC3TDMUQG6ZRAMRSWY2LHNB2CA2LOEB2GQZJAMNXW45DJNZ2WKZBAMFXGIIDJNZSGKZTBORUWOYLCNRSSAZ3FNZSXEYLUNFXW4IDPMYQGW3TPO5WGKZDHMUWCAZLYMNSWKZDTEB2GQZJAONUG64TUEB3GK2DFNVSW4Y3FEBXWMIDBNZ4SAY3BOJXGC3BAOBWGKYLTOVZGKLQ=";
    char *decoded = base32_parse(str2, strlen(str2));
    printf("decoded:%s \r\n",decoded);

return 0;

}

4、运行结果

一、Base64规则

        64 = 2^6,所以需要6 Bit来表示一个base64字符。一个字节8 Bit,6和8的最小公倍数是24。编码的过程中,以3个字节为一组转为4个base64字符,不足3个字节以0代替。为方便转换,以一个无符号32位整数(uint32_t)为中间载体。先由高位到低位将这三个字节填充到这个整数中,然后由高位到低位依次读取6位,获取对应数值的字母,共读取4次。如下图所示。解码的过程是上述的逆过程。

二、示例

1、base64.h

#ifndef _BASE64_H
#define _BASE64_H

#include <stdint.h>


char *base64_encode(const char *str, uint64_t len);
char *base64_parse(const char *base64Str, uint64_t len);

#endif //_BASE64_H


2、base64.c

#include "base64.h"
#include <stdlib.h>
#include <stdint.h>

#ifndef CEIL_POS
// 正数向上取整 CEIL_POS(2.345) => 3
#define CEIL_POS(X) (X > (uint64_t)(X) ? (uint64_t)(X+1) : (uint64_t)(X))
#endif


static const char BASE64_MAP[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
static const uint8_t BASE64_REVERSE_MAP[] = {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 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,
};

char *base64_encode(const char *str, uint64_t len) {
    uint64_t length = CEIL_POS(len * 4 / 3) + 1;
    char *base64Chars = (char *) malloc(sizeof(char) * length);
    uint64_t idx = 0;

    for (uint64_t i = 0; i < len; i += 3) {
        uint32_t byte1 = (uint8_t) str[i];
        uint16_t byte2 = (i + 1 < len) ? (uint8_t) str[i + 1] : 0;
        uint8_t byte3 = (i + 2 < len) ? (uint8_t) str[i + 2] : 0;

        uint32_t triplet = (byte1 << 16) | (byte2 << 8) | byte3;

        for (uint64_t j = 0; (j < 4) && (i + j * 0.75 < len); j++) {
            base64Chars[idx] = BASE64_MAP[(triplet >> (6 * (3 - j))) & 0x3f];
            idx++;
        }
    }

    char paddingChar = BASE64_MAP[64];
    if (paddingChar) {
        while (idx % 4) {
            base64Chars[idx] = paddingChar;
            idx++;
        }
    }
    base64Chars[idx] = 0;
    return base64Chars;
}

char *base64_parse(const char *base64Str, uint64_t len) {
    while (base64Str[len - 1] == BASE64_MAP[64]) {
        len--;
    }
    uint64_t length = CEIL_POS(len * 3 / 4) + 1;
    char *str = (char *) malloc(sizeof(char) * length);
    uint64_t idx = 0;

    for (uint64_t i = 0; i < len; i += 4) {
        uint32_t triplet = 0;
        for (uint8_t j = 0; j < 4; ++j) {
            if (i + j < len) triplet = (triplet << 6) | ((uint8_t) BASE64_REVERSE_MAP[base64Str[i + j]] & 0x3f);
            else triplet = triplet << 6;
        }
        for (uint8_t j = 0; (j < 3); ++j) {
            str[idx] = (triplet >> (8 * (2 - j))) & 0xff;
            idx++;
        }
    }
    str[idx] = 0;
    return str;
}

3、main.c

#include <stdio.h>
#include <string.h>
#include "base64.h"
#include "stdlib.h"


int main(void)
{

char str1[] = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
    char *encoded = base64_encode(str1, strlen(str1));
    printf("encode:%s \r\n",encoded);

    char str2[] = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";
    char *decoded = base64_parse(str2, strlen(str2));
    printf("decoded:%s \r\n",decoded);

return 0;

}

4、运行结果

三、总结

        希望能帮助到需要帮助的攻城狮,加油哦!!! 

参考链接

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C语言中没有内置的Base64加解密函数,但可以通过调用第三方库来实现。 一个常用的第三方库是openssl,使用它可以很方便地进行Base64编码和解码。 以下是一个示例程序,展示了如何使用openssl库进行Base64编码和解码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/bio.h> #include <openssl/evp.h> int base64_encode(const char *input, int input_len, char *output, int output_size) { BIO *bmem = NULL; BIO *b64 = NULL; BUF_MEM *bptr = NULL; b64 = BIO_new(BIO_f_base64()); if (b64 == NULL) { return -1; } bmem = BIO_new(BIO_s_mem()); if (bmem == NULL) { BIO_free(b64); return -1; } b64 = BIO_push(b64, bmem); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (BIO_write(b64, input, input_len) <= 0) { BIO_free_all(b64); return -1; } if (BIO_flush(b64) <= 0) { BIO_free_all(b64); return -1; } BIO_get_mem_ptr(b64, &bptr); if (bptr->length > output_size) { BIO_free_all(b64); return -1; } memcpy(output, bptr->data, bptr->length); output[bptr->length] = '\0'; BIO_free_all(b64); return bptr->length; } int base64_decode(const char *input, int input_len, char *output, int output_size) { BIO *bmem = NULL; BIO *b64 = NULL; b64 = BIO_new(BIO_f_base64()); if (b64 == NULL) { return -1; } bmem = BIO_new_mem_buf((void *)input, input_len); if (bmem == NULL) { BIO_free(b64); return -1; } bmem = BIO_push(b64, bmem); int len = BIO_read(bmem, output, output_size); if (len < 0) { BIO_free_all(bmem); return -1; } output[len] = '\0'; BIO_free_all(bmem); return len; } int main() { char input[] = "hello world"; char encoded[100]; char decoded[100]; printf("Original: %s\n", input); int len = base64_encode(input, strlen(input), encoded, sizeof(encoded)); printf("Encoded: %s (%d)\n", encoded, len); len = base64_decode(encoded, len, decoded, sizeof(decoded)); printf("Decoded: %s (%d)\n", decoded, len); return 0; } ``` 运行结果如下: ``` Original: hello world Encoded: aGVsbG8gd29ybGQ= (16) Decoded: hello world (11) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ch_champion

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值