security.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #include "security.hpp"
  2. #include <openssl/conf.h>
  3. #include <openssl/err.h>
  4. #include <openssl/evp.h>
  5. // AES
  6. #include <openssl/aes.h>
  7. // ECDH
  8. #include <openssl/ec.h>
  9. #include <openssl/pem.h>
  10. #include <stdexcept>
  11. using namespace binom;
  12. void Security::handleErrors() {
  13. ERR_print_errors_fp(stderr);
  14. throw std::runtime_error("Security error");
  15. }
  16. EVP_PKEY* Security::genKey() {
  17. EVP_PKEY* key_pair = nullptr;
  18. EVP_PKEY_CTX* param_gen_ctx = nullptr;
  19. EVP_PKEY_CTX* key_gen_ctx = nullptr;
  20. EVP_PKEY* params= nullptr;
  21. if(!(param_gen_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_EC, NULL))) handleErrors();
  22. if(!EVP_PKEY_paramgen_init(param_gen_ctx)) handleErrors();
  23. if(!EVP_PKEY_CTX_set_ec_paramgen_curve_nid(param_gen_ctx, NID_X9_62_prime256v1))
  24. handleErrors();
  25. if(!EVP_PKEY_paramgen(param_gen_ctx, &params)) handleErrors();
  26. if(!(key_gen_ctx = EVP_PKEY_CTX_new(params, nullptr))) handleErrors();
  27. if(!EVP_PKEY_keygen_init(key_gen_ctx)) handleErrors();
  28. if(!EVP_PKEY_keygen(key_gen_ctx, &key_pair)) handleErrors();
  29. EVP_PKEY_CTX_free(param_gen_ctx);
  30. EVP_PKEY_CTX_free(key_gen_ctx);
  31. return key_pair;
  32. }
  33. void Security::freeKey(EVP_PKEY* key) {EVP_PKEY_free(key);}
  34. ByteArray Security::extractPublicKey(EVP_PKEY* key_pair) {
  35. ByteArray data(i2d_PublicKey(key_pair, nullptr));
  36. unsigned char* ptr = data.begin();
  37. i2d_PublicKey(key_pair, &ptr);
  38. return data;
  39. }
  40. ByteArray Security::extractPrivateKey(EVP_PKEY* key_pair) {
  41. EC_KEY* ec_key = EVP_PKEY_get1_EC_KEY(key_pair);
  42. const BIGNUM* ec_priv = EC_KEY_get0_private_key(ec_key);
  43. int length = BN_bn2mpi(ec_priv, nullptr);
  44. ByteArray data(length);
  45. BN_bn2mpi(ec_priv, data.begin());
  46. return data;
  47. }
  48. EVP_PKEY* Security::getKeyPair(ByteArray priv_key_raw, ByteArray pub_key_raw) {
  49. EVP_PKEY* key_pair = EVP_PKEY_new();
  50. EC_KEY *ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  51. const EC_GROUP* ec_group = EC_KEY_get0_group(ec_key);
  52. EC_POINT* ec_point = EC_POINT_new(ec_group);
  53. EC_POINT_oct2point(ec_group, ec_point, pub_key_raw.begin(), pub_key_raw.length(), nullptr);
  54. EC_KEY_set_public_key(ec_key, ec_point);
  55. EC_POINT_free(ec_point);
  56. BIGNUM* priv = BN_mpi2bn(priv_key_raw.begin(), priv_key_raw.length(), nullptr);
  57. EC_KEY_set_private_key(ec_key, priv);
  58. BN_free(priv);
  59. EVP_PKEY_set1_EC_KEY(key_pair, ec_key);
  60. EC_KEY_free(ec_key);
  61. return key_pair;
  62. }
  63. Security::AES_t Security::getSecret(ByteArray peer_key, EVP_PKEY* key_pair) {
  64. EC_KEY *temp_ec_key = nullptr;
  65. EVP_PKEY *peerkey = nullptr;
  66. temp_ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  67. if(temp_ec_key == nullptr)
  68. handleErrors();
  69. if(EC_KEY_oct2key(temp_ec_key, peer_key.begin(), peer_key.length(), NULL) != 1)
  70. handleErrors();
  71. if(EC_KEY_check_key(temp_ec_key) != 1) handleErrors();
  72. peerkey = EVP_PKEY_new();
  73. if(peerkey == NULL)
  74. handleErrors();
  75. if(EVP_PKEY_assign_EC_KEY(peerkey, temp_ec_key)!= 1)
  76. handleErrors();
  77. // Getting secret
  78. EVP_PKEY_CTX *derivation_ctx = EVP_PKEY_CTX_new(key_pair, NULL);
  79. EVP_PKEY_derive_init(derivation_ctx);
  80. EVP_PKEY_derive_set_peer(derivation_ctx, peerkey);
  81. size_t lenght;
  82. void* ptr;
  83. if(1 != EVP_PKEY_derive(derivation_ctx, NULL, &lenght)) handleErrors();
  84. if(NULL == (ptr = OPENSSL_malloc(lenght))) handleErrors();
  85. if(1 != (EVP_PKEY_derive(derivation_ctx, (unsigned char*)ptr, &lenght))) handleErrors();
  86. EVP_PKEY_CTX_free(derivation_ctx);
  87. EVP_PKEY_free(peerkey);
  88. AES_t aes_key;
  89. EVP_MD_CTX *mdctx;
  90. if((mdctx = EVP_MD_CTX_new()) == NULL)
  91. handleErrors();
  92. if(1 != EVP_DigestInit_ex(mdctx, EVP_sha384(), NULL))
  93. handleErrors();
  94. if(1 != EVP_DigestUpdate(mdctx, ptr, lenght))
  95. handleErrors();
  96. unsigned int length;
  97. if(1 != EVP_DigestFinal_ex(mdctx, (unsigned char*)&aes_key, &length))
  98. handleErrors();
  99. EVP_MD_CTX_free(mdctx);
  100. OPENSSL_free(ptr);
  101. return aes_key;
  102. }
  103. Security::AES_t Security::createAES256Key(ByteArray data) {
  104. AES_t aes_key;
  105. EVP_MD_CTX *mdctx;
  106. if((mdctx = EVP_MD_CTX_new()) == NULL)
  107. handleErrors();
  108. if(1 != EVP_DigestInit_ex(mdctx, EVP_sha3_384(), NULL))
  109. handleErrors();
  110. if(1 != EVP_DigestUpdate(mdctx, data.begin(), data.length()))
  111. handleErrors();
  112. unsigned int length;
  113. if(1 != EVP_DigestFinal_ex(mdctx, (unsigned char*)&aes_key, &length))
  114. handleErrors();
  115. EVP_MD_CTX_free(mdctx);
  116. return aes_key;
  117. }
  118. ByteArray Security::getHashOf(ByteArray data, HashMethod hash_method) {return getHashOf(std::move(data), ByteArray(), hash_method);}
  119. ByteArray Security::getHashOf(ByteArray data, ByteArray salt, Security::HashMethod hash_method) {
  120. auto getHashMethod = [](HashMethod hash_method)->const EVP_MD* {
  121. switch (hash_method) {
  122. case Security::HashMethod::sha1: return EVP_sha1();
  123. case Security::HashMethod::sha224: return EVP_sha224();
  124. case Security::HashMethod::sha256: return EVP_sha256();
  125. case Security::HashMethod::sha384: return EVP_sha384();
  126. case Security::HashMethod::sha512: return EVP_sha512();
  127. case Security::HashMethod::sha512_224: return EVP_sha512_224();
  128. case Security::HashMethod::sha512_256: return EVP_sha512_256();
  129. case Security::HashMethod::sha3_224: return EVP_sha3_224();
  130. case Security::HashMethod::sha3_256: return EVP_sha3_256();
  131. case Security::HashMethod::sha3_384: return EVP_sha3_384();
  132. case Security::HashMethod::sha3_512: return EVP_sha3_512();
  133. case Security::HashMethod::shake128: return EVP_shake128();
  134. case Security::HashMethod::shake256: return EVP_shake256();
  135. default: return EVP_sha3_512();
  136. }
  137. };
  138. auto getHashSize = [](HashMethod hash_method)->size_t {
  139. switch (hash_method) {
  140. case Security::HashMethod::sha1: return 20;
  141. case Security::HashMethod::sha224: return 28;
  142. case Security::HashMethod::sha256: return 32;
  143. case Security::HashMethod::sha384: return 48;
  144. case Security::HashMethod::sha512: return 64;
  145. case Security::HashMethod::sha512_224: return 28;
  146. case Security::HashMethod::sha512_256: return 32;
  147. case Security::HashMethod::sha3_224: return 28;
  148. case Security::HashMethod::sha3_256: return 32;
  149. case Security::HashMethod::sha3_384: return 48;
  150. case Security::HashMethod::sha3_512: return 64;
  151. case Security::HashMethod::shake128: return 16;
  152. case Security::HashMethod::shake256: return 32;
  153. default: return 64;
  154. }
  155. };
  156. data.pushBack(std::move(salt));
  157. ByteArray hash(getHashSize(hash_method));
  158. EVP_MD_CTX *mdctx;
  159. if((mdctx = EVP_MD_CTX_new()) == NULL)
  160. handleErrors();
  161. if(1 != EVP_DigestInit_ex(mdctx, getHashMethod(hash_method), NULL))
  162. handleErrors();
  163. if(1 != EVP_DigestUpdate(mdctx, data.begin(), data.length()))
  164. handleErrors();
  165. unsigned int length;
  166. if(1 != EVP_DigestFinal_ex(mdctx, hash.begin(), &length))
  167. handleErrors();
  168. EVP_MD_CTX_free(mdctx);
  169. return hash;
  170. }
  171. ByteArray Security::encodeBase64(ByteArray decoded) {
  172. ByteArray encoded((4*((decoded.length()+2)/3)) + 1);
  173. EVP_EncodeBlock(encoded.begin(), decoded.begin(), decoded.length());
  174. return encoded;
  175. }
  176. ByteArray Security::decodeBase64(ByteArray encoded) {
  177. ByteArray decoded((3*encoded.length()/4) + 1);
  178. size_t recived_data_size = EVP_DecodeBlock(decoded.begin(), encoded.begin(), encoded.length());
  179. if(recived_data_size < decoded.length())
  180. decoded.resize(recived_data_size);
  181. return decoded;
  182. }
  183. binom::ByteArray Security::encrypt(binom::ByteArray plain_text, AES_t aes_struct) {
  184. /* max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE -1 bytes */
  185. ByteArray ciphertext(plain_text.length() % AES_BLOCK_SIZE == 0
  186. ? plain_text.length()
  187. : (plain_text.length() / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE);
  188. EVP_CIPHER_CTX *ctx;
  189. if(!(ctx = EVP_CIPHER_CTX_new()))
  190. handleErrors();
  191. if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, aes_struct.key, aes_struct.init_vector))
  192. handleErrors();
  193. int f_length, s_length;
  194. if(1 != EVP_EncryptUpdate(ctx, ciphertext.begin(), &f_length, plain_text.begin(), plain_text.length()))
  195. handleErrors();
  196. if(ui64(f_length) == ciphertext.length())
  197. ciphertext.addSize(AES_BLOCK_SIZE);
  198. elif(ui64(f_length) > ciphertext.length())
  199. throw std::runtime_error("Predicted ciphertext size lower then actual!");
  200. if(1 != EVP_EncryptFinal_ex(ctx, ciphertext.begin() + f_length, &s_length))
  201. handleErrors();
  202. if(ui64 reuired_length = f_length + s_length;reuired_length < ciphertext.length())
  203. ciphertext.resize(f_length + s_length);
  204. elif(reuired_length > ciphertext.length())
  205. throw std::runtime_error("Predicted ciphertext size lower then actual!");
  206. EVP_CIPHER_CTX_free(ctx);
  207. return ciphertext;
  208. }
  209. ByteArray Security::decrypt(ByteArray ciphertext, Security::AES_t aes_struct) {
  210. EVP_CIPHER_CTX *ctx;
  211. ByteArray plain_text(ciphertext.length());
  212. if(!(ctx = EVP_CIPHER_CTX_new()))
  213. handleErrors();
  214. if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, aes_struct.key, aes_struct.init_vector))
  215. handleErrors();
  216. int f_length, s_length;
  217. if(1 != EVP_DecryptUpdate(ctx, plain_text.begin(), &f_length, ciphertext.begin(), ciphertext.length()))
  218. handleErrors();
  219. if(1 != EVP_DecryptFinal_ex(ctx, plain_text.begin() + f_length, &s_length))
  220. handleErrors();
  221. plain_text.resize(f_length + s_length);
  222. EVP_CIPHER_CTX_free(ctx);
  223. return plain_text;
  224. }
  225. std::string uuid::generateUUIDv4() {
  226. std::stringstream ss;
  227. int i;
  228. ss << std::hex;
  229. for (i = 0; i < 8; i++) {
  230. ss << dis(gen);
  231. }
  232. ss << "-";
  233. for (i = 0; i < 4; i++) {
  234. ss << dis(gen);
  235. }
  236. ss << "-4";
  237. for (i = 0; i < 3; i++) {
  238. ss << dis(gen);
  239. }
  240. ss << "-";
  241. ss << dis2(gen);
  242. for (i = 0; i < 3; i++) {
  243. ss << dis(gen);
  244. }
  245. ss << "-";
  246. for (i = 0; i < 12; i++) {
  247. ss << dis(gen);
  248. };
  249. return ss.str();
  250. }