C++ openssl 进行base64加密和解密
时间: 2023-07-05 08:23:22 浏览: 366
C++ OpenSSL 库提供了 base64 编码和解码的函数,可以使用以下代码进行加密和解密:
```c++
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
std::string base64_encode(const std::string& input) {
BIO *bio, *b64;
BUF_MEM *bufferPtr;
bio = BIO_new(BIO_s_mem());
b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
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;
}
std::string base64_decode(const std::string& input) {
BIO *bio, *b64;
char buffer[input.size()];
memset(buffer, 0, sizeof(buffer));
bio = BIO_new_mem_buf(input.c_str(), input.size());
b64 = BIO_new(BIO_f_base64());
bio = BIO_push(b64, bio);
BIO_read(bio, buffer, input.size());
BIO_free_all(bio);
return std::string(buffer);
}
```
使用示例:
```c++
int main() {
std::string input = "hello world";
std::string encoded = base64_encode(input);
std::string decoded = base64_decode(encoded);
std::cout << "Input: " << input << std::endl;
std::cout << "Encoded: " << encoded << std::endl;
std::cout << "Decoded: " << decoded << std::endl;
return 0;
}
```
阅读全文