使用openssl进行Base64编解码

/********************************************
编译:
gcc -g -o base64 base64.c -lssl

测试:
./base64 -e 123qwe
base64_encode("123qwe"): MTIzcXdl
 
./base64 -d MTIzcXdl
base64_decode("MTIzcXdl"): 123qwe
*********************************************/
//base64.c:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
 
char *base64_encode(const unsigned char *in, int32_t len)
{
    BIO     *bmem, *b64;
    BUF_MEM *b_ptr;
 
    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new(BIO_s_mem());
    b64 = BIO_push(b64, bmem);
    BIO_write(b64, in, len);
    BIO_flush(b64);
    BIO_get_mem_ptr(b64, &b_ptr);
 
    char *buff = (char *)calloc(1, b_ptr->length);
    if (buff == NULL) {
        printf("alloc memory fail\n");
        return NULL;
    }
 
    memcpy(buff, b_ptr->data, b_ptr->length - 1);
    buff[b_ptr->length - 1] = 0;
 
    BIO_free_all(b64);
 
    return buff;
}
 
char *base64_decode(unsigned char *in, int32_t len)
{
    BIO     *b64, *bmem;
 
    char *buffer = (char *)calloc(1, len);
    if (buffer == NULL) {
        printf("alloc memory fail\n");
        return NULL;
    }
 
    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new_mem_buf(in, len);
    bmem = BIO_push(b64, bmem);
 
    BIO_read(bmem, buffer, len);
 
    BIO_free_all(bmem);
 
    return buffer;
}
 
int main(int argc, char **argv)
{
    char *type = argv[1];
    char *str = NULL;
    char *out = NULL;
 
    if (type[0] == '-' && type[1] == 'e') {
        str = argv[2];
        out = base64_encode(str, strlen(str));
        printf("base64_encode(\"%s\"): %s\n", str, out);
    } else {
        str = (char *)calloc(1, strlen(argv[2]) + 1);
        if (str == NULL) {
            printf("calloc memory fail\n");
            return -1;
        }
        memcpy(str, argv[2], strlen(argv[2]));
        str[strlen(argv[2])] = '\n';
        str[strlen(argv[2])+1] = '\0';
        out = base64_decode(str, strlen(str));
        printf("base64_decode(\"%s\"): %s\n", argv[2], out);
        free(str);
    }
 
    free(out);
 
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容