/********************************************
编译:
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;
}
使用openssl进行Base64编解码
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 四、对解压结果进行Base64解码 解码函数:[ref] Base64原理:简单来说就是把原本的数据每三个字符(3...
- 寒假马上来啦,爸爸妈妈们要准备点陪玩存货,才好应付在家闲得发慌的孩子啊。 不知道从哪里入手?不如就从鸡年的创意手工...