/********************************************
編譯:
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進(jìn)行Base64編解碼
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 四、對解壓結(jié)果進(jìn)行Base64解碼 解碼函數(shù):[ref] Base64原理:簡單來說就是把原本的數(shù)據(jù)每三個(gè)字符(3...
- 寒假馬上來啦,爸爸媽媽們要準(zhǔn)備點(diǎn)陪玩存貨,才好應(yīng)付在家閑得發(fā)慌的孩子啊。 不知道從哪里入手?不如就從雞年的創(chuàng)意手工...
- 看到一些關(guān)于宮外孕的文章,仿佛看到了曾經(jīng)的自己。慶幸的是我還活著,不幸的是我的身體不再完整了。我常常在想,是不是因...