-
Notifications
You must be signed in to change notification settings - Fork 0
/
aes256.cpp
95 lines (81 loc) · 2.64 KB
/
aes256.cpp
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
static const unsigned char iv[] = "0123456789012345";
AES::AES()
{
EVP_CIPHER_CTX_init(&_cipher_ctx);
}
AES::~AES()
{
EVP_CIPHER_CTX_cleanup(&_cipher_ctx);
}
int AES::reset()
{
EVP_CIPHER_CTX_cleanup(&_cipher_ctx);
EVP_CIPHER_CTX_init(&_cipher_ctx);
return 0;
}
int AES::encrypt(const char* key, const char* plain_text, int plain_text_len, char** encrypted, int& encrypted_len)
{
unsigned char iv_copy[sizeof(iv)];
memcpy(iv_copy, iv, sizeof(iv));
int ret = EVP_EncryptInit_ex(&_cipher_ctx, EVP_aes_256_cbc(), nullptr, (const unsigned char*)key, iv_copy);
if (ret != 1) {
LOG_ERROR << "Failed to init encrypt, return=" << ret;
return -1;
}
const int buffer_len = plain_text_len + EVP_MAX_BLOCK_LENGTH;
unsigned char* buffer = (unsigned char*)malloc(buffer_len);
if (nullptr == buffer) {
LOG_ERROR << "Failed to alloc memory. size=" << buffer_len;
return -1;
}
int used_buffer_len = 0;
ret = EVP_EncryptUpdate(&_cipher_ctx, buffer, &used_buffer_len, (const unsigned char*)plain_text, plain_text_len);
if (ret != 1) {
LOG_ERROR << "Failed to encrypt. returned=" << ret;
free(buffer);
return -1;
}
int final_buffer_len = 0;
ret = EVP_EncryptFinal_ex(&_cipher_ctx, buffer + used_buffer_len, &final_buffer_len);
if (ret != 1) {
LOG_ERROR << "Failed to encrypt(final). returned=" << ret;
free(buffer);
return -1;
}
*encrypted = (char*)buffer;
encrypted_len = used_buffer_len + final_buffer_len;
return 0;
}
int AES::decrypt(const char* key, const char* encrypted, int encrypted_len, char** plain_text, int& plain_text_len)
{
unsigned char iv_copy[sizeof(iv)];
memcpy(iv_copy, iv, sizeof(iv));
int ret = EVP_DecryptInit_ex(&_cipher_ctx, EVP_aes_256_cbc(), nullptr, (const unsigned char*)key, iv_copy);
if (ret != 1) {
LOG_ERROR << "Failed to init encrypt, return=" << ret;
return -1;
}
unsigned char* buffer = (unsigned char*)malloc(encrypted_len);
if (nullptr == buffer) {
LOG_ERROR << "Failed to alloc memory. size=" << encrypted_len;
return -1;
}
memset(buffer, 0, encrypted_len);
int used_buffer_len = 0;
ret = EVP_DecryptUpdate(&_cipher_ctx, buffer, &used_buffer_len, (const unsigned char*)encrypted, encrypted_len);
if (ret != 1) {
LOG_ERROR << "Failed to decrypt. return=" << ret;
free(buffer);
return -1;
}
int final_buffer_len = 0;
ret = EVP_DecryptFinal_ex(&_cipher_ctx, buffer + used_buffer_len, &final_buffer_len);
if (ret != 1) {
LOG_ERROR << "Failed to decrypt(final). return=" << ret;
free(buffer);
return -1;
}
*plain_text = (char*)buffer;
plain_text_len = used_buffer_len + final_buffer_len;
return 0;
}