如何利用openssl来进行base64编解码?

时间:2022-08-20 18:24:43

      openssl的用法, 请见之前博文, 下面仅仅给出base64编解码的代码:

#include <iostream>
#include <openssl/evp.h>
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib") // 可以注释掉
using namespace std;

// base64编码
int Base64Encode(const char *encoded, int encodedLength, char *decoded)
{
return EVP_EncodeBlock((unsigned char*)decoded, (const unsigned char*)encoded, encodedLength);
}

// base解码
int Base64Decode(const char *encoded, int encodedLength, char *decoded)
{
return EVP_DecodeBlock((unsigned char*)decoded, (const unsigned char*)encoded, encodedLength);
}

int main()
{
char test[] = "hello";
char result[1000] = {0}; // 编码的结果
cout << Base64Encode(test, strlen(test), result) << endl;
cout << result << endl;

char org[1000] = {0}; // 解码的结果
cout << Base64Decode(result, strlen(result), org) << endl;
cout << org << endl;

return 0;
}
      结果为:

8
aGVsbG8=
6
hello

       经对比, 与其他工具产生的值是相同的, 小有成就感。