-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
101 lines (75 loc) · 2.62 KB
/
main.cpp
File metadata and controls
101 lines (75 loc) · 2.62 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/types.h>
#include <string.h>
#include <stdio.h>
void handleErrors(void) {
//ERR_print_errors_fp(stderr);
abort();
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key, unsigned char *iv, unsigned char *ciphertext)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
// Create and init the context
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
// Init the encryption
if (1 != EVP_EncryptInit_ex(ctx, EVP_chacha20(), NULL, key, iv))
handleErrors();
// encrypt the message
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
// final encryption
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
// Free context
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
// Create and init the context
if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
// Init the encryption
if (1 != EVP_DecryptInit_ex(ctx, EVP_chacha20(), NULL, key, iv))
handleErrors();
// Decrypt the mesage
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
// final decrypt
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
plaintext_len += len;
// Free context
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
int main(void) {
// Key and IV the dimensions must be corect
unsigned char key[32];
unsigned char iv[12];
// generate random the key and IV
if (!RAND_bytes(key, sizeof(key))) handleErrors();
if (!RAND_bytes(iv, sizeof(iv))) handleErrors();
// Secret mesaje
unsigned char *plaintext = (unsigned char *)"Secret message for NSA ..";
unsigned char ciphertext[128];
unsigned char decryptedtext[128];
int decryptedtext_len, ciphertext_len;
// encrypt
ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key, iv, ciphertext);
// Decrypt
decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);
// add a null-terminator
decryptedtext[decryptedtext_len] = '\0';
// Rezult
printf("Encrypted Text :\n");
BIO_dump_fp(stdout, (const char *)ciphertext, ciphertext_len);
printf("Decrypted Text:\n%s\n", decryptedtext);
return 0;
}