-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAES_cipher.cpp
More file actions
executable file
·87 lines (68 loc) · 2.6 KB
/
AES_cipher.cpp
File metadata and controls
executable file
·87 lines (68 loc) · 2.6 KB
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
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <iostream>
#include <vector>
void handleErrors() {
ERR_print_errors_fp(stderr);
abort();
}
// AES-256-CTR шифрование/дешифрование (в CTR режиме операции одинаковы)
int aes256_ctr_crypt(const unsigned char *input, int input_len,
const unsigned char *key, const unsigned char *iv,
std::vector<unsigned char> &output) {
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
if (!ctx) handleErrors();
if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_ctr(), NULL, key, iv))
handleErrors();
output.resize(input_len + EVP_CIPHER_block_size(EVP_aes_256_ctr()));
int len = 0;
int output_len = 0;
// В CTR режиме EncryptUpdate и DecryptUpdate делают одно и то же,
// здесь используем EncryptUpdate и EncryptFinal
if (1 != EVP_EncryptUpdate(ctx, output.data(), &len, input, input_len))
handleErrors();
output_len = len;
if (1 != EVP_EncryptFinal_ex(ctx, output.data() + len, &len))
handleErrors();
output_len += len;
EVP_CIPHER_CTX_free(ctx);
output.resize(output_len);
return output_len;
}
int main() {
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
std::string input;
std::cout << "Введите текст: ";
std::getline(std::cin, input);
unsigned char key[32];
unsigned char iv[16];
if (!RAND_bytes(key, sizeof(key)) || !RAND_bytes(iv, sizeof(iv)))
handleErrors();
std::vector<unsigned char> ciphertext;
int ciphertext_len = aes256_ctr_crypt(
reinterpret_cast<const unsigned char*>(input.data()), input.size(),
key, iv, ciphertext
);
std::cout << "Key: ";
for (auto b : key) printf("%02x", b);
std::cout << std::endl;
std::cout << "IV: ";
for (auto b : iv) printf("%02x", b);
std::cout << std::endl;
std::cout << "Encrypted: ";
for (auto b : ciphertext) printf("%02x", b);
std::cout << std::endl;
// Дешифруем (в CTR режиме шифрование и дешифрование — одинаковы)
std::vector<unsigned char> decrypted;
int decrypted_len = aes256_ctr_crypt(
ciphertext.data(), ciphertext_len,
key, iv, decrypted
);
decrypted.push_back('\0');
std::cout << "Decrypted: " << reinterpret_cast<char*>(decrypted.data()) << std::endl;
EVP_cleanup();
ERR_free_strings();
return 0;
}