effa299fbf7c0f396b2d840490a519ffcd74b289
[awesomized/libmemcached] / src / libhashkit / encrypt.cc
1 /*
2 +--------------------------------------------------------------------+
3 | libmemcached-awesome - C/C++ Client Library for memcached |
4 +--------------------------------------------------------------------+
5 | Redistribution and use in source and binary forms, with or without |
6 | modification, are permitted under the terms of the BSD license. |
7 | You should have received a copy of the license in a bundled file |
8 | named LICENSE; in case you did not receive a copy you can review |
9 | the terms online at: https://opensource.org/licenses/BSD-3-Clause |
10 +--------------------------------------------------------------------+
11 | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ |
12 | Copyright (c) 2020-2021 Michael Wallner https://awesome.co/ |
13 +--------------------------------------------------------------------+
14 */
15
16 #include "libhashkit/common.h"
17
18 #ifdef HAVE_OPENSSL_CRYPTO
19 # include <openssl/evp.h>
20 #endif
21
22 hashkit_string_st *hashkit_encrypt(hashkit_st *kit, const char *source, size_t source_length) {
23 #ifdef HAVE_OPENSSL_CRYPTO
24 return aes_encrypt((encryption_context_t *) kit->_key,
25 (const unsigned char *) source, source_length);
26 #else
27 return aes_encrypt((aes_key_t *) kit->_key, source,
28 source_length);
29 #endif
30 }
31
32 hashkit_string_st *hashkit_decrypt(hashkit_st *kit, const char *source, size_t source_length) {
33 #ifdef HAVE_OPENSSL_CRYPTO
34 return aes_decrypt((encryption_context_t *) kit->_key,
35 (const unsigned char *) source, source_length);
36 #else
37 return aes_decrypt((aes_key_t *)kit->_key, source, source_length);
38 #endif
39 }
40
41 #ifdef HAVE_OPENSSL_CRYPTO
42 bool hashkit_key(hashkit_st *kit, const char *key, const size_t key_length) {
43 kit->_key = (encryption_context_t *) malloc(sizeof(encryption_context_t));
44 ((encryption_context_t *) kit->_key)->encryption_context = EVP_CIPHER_CTX_new();
45 ((encryption_context_t *) kit->_key)->decryption_context = EVP_CIPHER_CTX_new();
46 if (((encryption_context_t *) kit->_key)->encryption_context == NULL
47 || ((encryption_context_t *) kit->_key)->decryption_context == NULL)
48 {
49 return false;
50 }
51 return aes_initialize((const unsigned char *) key, key_length,
52 (encryption_context_t *) kit->_key);
53 }
54 #else
55 bool hashkit_key(hashkit_st *kit, const char *key, const size_t key_length) {
56 if (kit->_key) {
57 free(kit->_key);
58 }
59
60 kit->_key = aes_create_key(key, key_length);
61
62 return bool(kit->_key);
63 }
64 #endif