-
Notifications
You must be signed in to change notification settings - Fork 2
/
openssl_base64.cc
112 lines (83 loc) · 2.21 KB
/
openssl_base64.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include "openssl_utils.hpp"
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include <gtest/gtest.h>
// base64 encode
auto base64_encode(const std::string &plain) -> std::string
{
std::string base64;
BIO *bio = BIO_new(BIO_f_base64());
if (bio == nullptr) {
openssl_error();
return base64;
}
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO *bmem = BIO_new(BIO_s_mem());
if (bmem == nullptr) {
openssl_error();
BIO_free(bio);
return base64;
}
bio = BIO_push(bio, bmem);
if (BIO_write(bio, plain.c_str(), static_cast<int>(plain.size()))
!= static_cast<int>(plain.size())) {
openssl_error();
BIO_free_all(bio);
return base64;
}
if (BIO_flush(bio) != 1) {
openssl_error();
BIO_free_all(bio);
return base64;
}
BUF_MEM *bptr = nullptr;
BIO_get_mem_ptr(bio, &bptr);
base64.assign(bptr->data, bptr->length);
BIO_free_all(bio);
return base64;
}
// base64 decode
auto base64_decode(const std::string &base64) -> std::string
{
std::string plain;
BIO *bio = BIO_new(BIO_f_base64());
if (bio == nullptr) {
openssl_error();
return plain;
}
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO *bmem = BIO_new_mem_buf(base64.c_str(), static_cast<int>(base64.size()));
if (bmem == nullptr) {
openssl_error();
BIO_free(bio);
return plain;
}
bio = BIO_push(bio, bmem);
plain.resize(base64.size());
int len = BIO_read(bio, &plain[0], static_cast<int>(plain.size()));
if (len < 0) {
openssl_error();
BIO_free_all(bio);
return plain;
}
plain.resize(len);
BIO_free_all(bio);
return plain;
}
TEST(openssl_base64, base64)
{
std::string plain = "hello world";
std::cout << "plain: " << plain << '\n';
std::string base64 = base64_encode(plain);
std::cout << "base64: " << base64 << '\n';
std::string decode = base64_decode(base64);
std::cout << "decode: " << decode << '\n';
EXPECT_EQ(plain, decode);
}
auto main() -> int
{
openssl_version();
testing::InitGoogleTest();
return RUN_ALL_TESTS();
}