c++ 基于 openssl 做base64编码
时间: 2023-07-18 12:26:11 浏览: 59
下面是一个使用 OpenSSL 库实现 Base64 编码的 C++ 代码示例:
```cpp
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <string>
std::string base64_encode(const std::string& input) {
BIO *bio, *b64;
BUF_MEM *bufferPtr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio, input.c_str(), input.length());
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bufferPtr);
std::string output(bufferPtr->data, bufferPtr->length);
BIO_free_all(bio);
return output;
}
```
这段代码将输入字符串 `input` 进行 Base64 编码,并返回编码后的字符串。你可以通过调用 `base64_encode` 函数来实现你的需求,例如:
```cpp
std::string input = "Hello, world!";
std::string output = base64_encode(input);
std::cout << output << std::endl; // 输出 "SGVsbG8sIHdvcmxkIQ=="
```
注意:为了避免输出的编码字符串中包含换行符,这里使用了 `BIO_set_flags` 函数将 `BIO` 对象的标志设置为 `BIO_FLAGS_BASE64_NO_NL`。如果你需要输出包含换行符的编码字符串,可以不调用这个函数。