本文最后更新于2017年8月26日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!
=Start=
缘由:
学习、提高需要
正文:
参考解答:
#include
#include
#include
#include
#include
#include
#include
#include
//base64_encode
int base64_encode(const char *input, int input_size, int with_new_line, char *buff, int buff_size)
{
if (input == NULL || input_size <= 0 || buff == NULL || buff_size <= 0) {
return -1;
}
BIO *bmem = NULL;
BUF_MEM *bptr = NULL;
BIO *b64 = NULL;
b64 = BIO_new(BIO_f_base64());
if(!with_new_line) {
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
}
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
BIO_write(b64, input, input_size);
BIO_flush(b64);
BIO_get_mem_ptr(b64, &bptr);
if (buff_size < (bptr->length + 1)) {
fprintf(stderr, "base64_encode output buff too small, need %ld, now %d\n", bptr->length + 1, buff_size);
BIO_free_all(b64);
return -1;
}
// char *buff = (char *)malloc(bptr->length + 1);
memcpy(buff, bptr->data, bptr->length);
buff[bptr->length] = 0;
BIO_free_all(b64);
return 0;
}
//base64_decode
int base64_decode(char *input, int input_size, int with_new_line, char *buff, int buff_size)
{
if (input == NULL || input_size <= 0 || buff == NULL || buff_size <= 0) {
return -1;
}
memset(buff, 0, buff_size);
BIO *bmem = NULL;
BIO *b64 = NULL;
b64 = BIO_new(BIO_f_base64());
if(!with_new_line) {
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
}
bmem = BIO_new_mem_buf(input, input_size);
bmem = BIO_push(b64, bmem);
BIO_read(bmem, buff, input_size);
BIO_free_all(bmem);
CRYPTO_cleanup_all_ex_data();//free crypto_malloc
return 0;
}
// int base64_encode(const char *input, int input_size, int with_new_line, char *buff, int buff_size);
// int base64_decode(char *input, int input_size, int with_new_line, char *buff, int buff_size);
// $ gcc openssl_base64.c -lcrypto
int main(int argc, char const *argv[])
{
if (argc < 2) {
printf("Usage:\n\t%s str_to_be_base64_encode\n\n", argv[0]);
return 0;
}
char buff[1024] = "\0";
int ret = -1;
ret = base64_encode(argv[1], strlen(argv[1]), 0, buff, sizeof(buff));
if (ret == 0) {
printf("input = %s\n", argv[1]);
printf("base64_encode = %s\n", buff);
}
char buff_decode[1024] = "\0";
ret = base64_decode(buff, strlen(buff), 0, buff_decode, sizeof(buff_decode));
if (ret == 0) {
printf("input = %s\n", buff);
printf("buff_decode = %s\n", buff_decode);
}
return 0;
}
参考链接:
=END=