-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.cpp
75 lines (68 loc) · 2.47 KB
/
crypto.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
#include "crypto.hpp"
using namespace std;
void handleErrors() {
ERR_print_errors_fp(stderr);
abort();
}
string sha(string data) {
unsigned char hash[SHA_DIGEST_LENGTH];
SHA_CTX sha;
SHA1_Init(&sha);
SHA1_Update(&sha, data.c_str(), data.size());
SHA1_Final(hash, &sha);
return toHex(hash, SHA_DIGEST_LENGTH);
}
string sha256(string data) {
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256_CTX sha256;
SHA256_Init(&sha256);
SHA256_Update(&sha256, data.c_str(), data.size());
SHA256_Final(hash, &sha256);
return toHex(hash, SHA256_DIGEST_LENGTH);
}
int aes256_cbc_encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
unsigned char *iv, unsigned char *ciphertext) {
EVP_CIPHER_CTX *ctx;
int len, ciphertext_len;
if(!(ctx = EVP_CIPHER_CTX_new()))
handleErrors();
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
handleErrors();
ciphertext_len += len;
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int aes256_cbc_decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
unsigned char *iv, unsigned char *plaintext) {
EVP_CIPHER_CTX *ctx;
int len, plaintext_len;
if(!(ctx = EVP_CIPHER_CTX_new()))
handleErrors();
if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();
if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
handleErrors();
plaintext_len += len;
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
tuple<string,string> hkdf() {
unsigned char iv[EVP_MAX_IV_LENGTH];
unsigned char key[EVP_MAX_KEY_LENGTH];
const EVP_CIPHER *cipher = EVP_aes_256_cbc();
int ivlen = EVP_CIPHER_iv_length(cipher);
int iklen = EVP_CIPHER_key_length(cipher);
int iter = 1337;
unsigned char *salt = (unsigned char*)password_generator(8).c_str();
PKCS5_PBKDF2_HMAC((const char *)master_pwd.c_str(), -1, salt, 0, 1, EVP_sha512(), iklen, key);
PKCS5_PBKDF2_HMAC((const char *)master_pwd.c_str(), -1, salt, 8, iter, EVP_sha512(), ivlen, iv);
return {toHex(iv, ivlen), toHex(key, iklen)};
}