OpenSSL 使用 base64 编码/解码

作者: 一去、二三里
个人微信号: iwaleon
微信公众号: 高效程序员

关于 OpenSSL 的介绍及安装请参见:Windows 下编译 OpenSSL

下面主要介绍有关 OpenSSL 使用 base64 编码/解码。

编码/解码

#include <openssl/evp.h>  
#include <openssl/bio.h>  
#include <openssl/buffer.h>    
#include <string>  
#include <iostream> 

using namespace std;

char * base64Encode(const char *buffer, int length, bool newLine);
char * base64Decode(char *input, int length, bool newLine);

int main(int argc, char* argv[])
{
	bool newLine = false;
	string input = "Hello World!";
	
	char * encode = base64Encode(input.c_str(), input.length(), newLine);
	char * decode = base64Decode(encode, strlen(encode), newLine);

	cout << "Base64 Encoded : " << encode << endl;
	cout << "Base64 Decoded : " << decode << endl;

	cin.get();
}

// base64 编码
char * base64Encode(const char *buffer, int length, bool newLine)
{
	BIO *bmem = NULL;
	BIO *b64 = NULL;
	BUF_MEM *bptr;

	b64 = BIO_new(BIO_f_base64());
	if (!newLine) {
		BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
	}
	bmem = BIO_new(BIO_s_mem());
	b64 = BIO_push(b64, bmem);
	BIO_write(b64, buffer, length);
	BIO_flush(b64);
	BIO_get_mem_ptr(b64, &bptr);
	BIO_set_close(b64, BIO_NOCLOSE);

	char *buff = (char *)malloc(bptr->length + 1);
	memcpy(buff, bptr->data, bptr->length);
	buff[bptr->length] = 0;
	BIO_free_all(b64);

	return buff;
}

// base64 解码
char * base64Decode(char *input, int length, bool newLine)
{
	BIO *b64 = NULL;
	BIO *bmem = NULL;
	char *buffer = (char *)malloc(length);
	memset(buffer, 0, length);
	b64 = BIO_new(BIO_f_base64());
	if (!newLine) {
		BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
	}
	bmem = BIO_new_mem_buf(input, length);
	bmem = BIO_push(b64, bmem);
	BIO_read(bmem, buffer, length);
	BIO_free_all(bmem);

	return buffer;
}

输出如下所示:

Base64 Encoded : SGVsbG8gV29ybGQh
Base64 Decoded : Hello World!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一去丶二三里

有收获,再打赏!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值