c base64 encode/decode implement by openssl
void b64_encode(const byte *inbuf, size_t inlen, byte **outbuf, size_t *outlen);
void b64_decode(const byte *inbuf, size_t inlen, byte **outbuf, size_t *outlen);
/************************************************************************* | |
> File Name: base64.c | |
> Author: jige003 | |
> Created Time: Thu 25 Apr 2019 03:12:24 PM CST | |
************************************************************************/ | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <assert.h> | |
#include <errno.h> | |
#include <stdint.h> | |
#include <sys/time.h> | |
#include <sys/resource.h> | |
#include <openssl/evp.h> | |
#include <openssl/err.h> | |
#include <openssl/rand.h> | |
#include <openssl/bio.h> | |
#include <openssl/buffer.h> | |
typedef unsigned char byte; | |
void b64_encode(const byte *inbuf, size_t inlen, byte **outbuf, size_t *outlen){ | |
BIO *buff, *b64; | |
BUF_MEM *ptr; | |
b64 = BIO_new(BIO_f_base64()); | |
buff = BIO_new(BIO_s_mem()); | |
buff = BIO_push(b64, buff); | |
BIO_set_flags(buff, BIO_FLAGS_BASE64_NO_NL); | |
BIO_set_close(buff, BIO_CLOSE); | |
BIO_write(buff, inbuf, inlen); | |
BIO_flush(buff); | |
BIO_get_mem_ptr(buff, &ptr); | |
(*outlen) = ptr->length; | |
(*outbuf) = BUF_strdup(ptr->data); | |
BIO_free_all(buff); | |
} | |
void b64_decode(const byte *inbuf, size_t inlen, byte **outbuf, size_t *outlen){ | |
BIO *buff, *b64; | |
b64 = BIO_new(BIO_f_base64()); | |
buff = BIO_new_mem_buf((void *)inbuf, inlen); | |
buff = BIO_push(b64, buff); | |
BIO_set_flags(buff, BIO_FLAGS_BASE64_NO_NL); | |
BIO_set_close(buff, BIO_CLOSE); | |
BIO_write(buff, inbuf, inlen); | |
BIO_flush(buff); | |
(*outbuf) = (byte *)malloc(inlen * sizeof(byte)); | |
(*outlen) = BIO_read(b64, (*outbuf), inlen); | |
(*outbuf) = (byte *)realloc((void*)(*outbuf), ((*outlen + 1) * sizeof(byte))); | |
(*outbuf)[(*outlen)] = '\0'; | |
BIO_free_all(buff); | |
} | |
void xfree(void *ptr){ | |
if (ptr != ((void*)0)) free(ptr); | |
} | |
int main(void){ | |
unsigned char inbuf[] = "this is a test string"; | |
unsigned char *outbuf; | |
size_t inlen, outlen; | |
inlen = strlen(inbuf); | |
unsigned char *plainbuf; | |
size_t plen; | |
/* use to test memory leak */ | |
#ifdef LOOP | |
while(1){ | |
#endif | |
b64_encode(inbuf, inlen, &outbuf, &outlen); | |
printf("inbuf:%s outbuf:%s\n", inbuf, outbuf); | |
b64_decode(outbuf, outlen, &plainbuf, &plen); | |
printf("base64buf:%s plainbuf:%s\n", outbuf, plainbuf); | |
assert( strcmp(plainbuf, inbuf) == 0 ); | |
xfree(plainbuf); | |
xfree(outbuf); | |
#ifdef LOOP | |
} | |
#endif | |
return 0; | |
} |