1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 #pragma once
3
4 #include "macro.h"
5
6 #if HAVE_OPENSSL
7 # include <openssl/bio.h>
8 # include <openssl/bn.h>
9 # include <openssl/err.h>
10 # include <openssl/evp.h>
11 # include <openssl/pkcs7.h>
12 # include <openssl/ssl.h>
13 # include <openssl/x509v3.h>
14
15 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(X509*, X509_free, NULL);
16 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(X509_NAME*, X509_NAME_free, NULL);
17 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(EVP_PKEY_CTX*, EVP_PKEY_CTX_free, NULL);
18 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(EVP_PKEY*, EVP_PKEY_free, NULL);
19 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(EVP_CIPHER_CTX*, EVP_CIPHER_CTX_free, NULL);
20 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(EC_POINT*, EC_POINT_free, NULL);
21 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(EC_GROUP*, EC_GROUP_free, NULL);
22 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(BIGNUM*, BN_free, NULL);
23 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(BN_CTX*, BN_CTX_free, NULL);
24 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(ECDSA_SIG*, ECDSA_SIG_free, NULL);
25 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(PKCS7*, PKCS7_free, NULL);
26 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(SSL*, SSL_free, NULL);
27 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(BIO*, BIO_free, NULL);
28 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(EVP_MD_CTX*, EVP_MD_CTX_free, NULL);
29
sk_X509_free_allp(STACK_OF (X509)** sk)30 static inline void sk_X509_free_allp(STACK_OF(X509) **sk) {
31 if (!sk || !*sk)
32 return;
33
34 sk_X509_pop_free(*sk, X509_free);
35 }
36
37 int openssl_hash(const EVP_MD *alg, const void *msg, size_t msg_len, uint8_t *ret_hash, size_t *ret_hash_len);
38
39 int rsa_encrypt_bytes(EVP_PKEY *pkey, const void *decrypted_key, size_t decrypted_key_size, void **ret_encrypt_key, size_t *ret_encrypt_key_size);
40
41 int rsa_pkey_to_suitable_key_size(EVP_PKEY *pkey, size_t *ret_suitable_key_size);
42 #endif
43
44 #if PREFER_OPENSSL
45 /* The openssl definition */
46 typedef const EVP_MD* hash_md_t;
47 typedef const EVP_MD* hash_algorithm_t;
48 typedef int elliptic_curve_t;
49 typedef EVP_MD_CTX* hash_context_t;
50 # define OPENSSL_OR_GCRYPT(a, b) (a)
51
52 #elif HAVE_GCRYPT
53
54 # include <gcrypt.h>
55
56 /* The gcrypt definition */
57 typedef int hash_md_t;
58 typedef const char* hash_algorithm_t;
59 typedef const char* elliptic_curve_t;
60 typedef gcry_md_hd_t hash_context_t;
61 # define OPENSSL_OR_GCRYPT(a, b) (b)
62 #endif
63
64 #if PREFER_OPENSSL
65 int string_hashsum(const char *s, size_t len, hash_algorithm_t md_algorithm, char **ret);
66
string_hashsum_sha224(const char * s,size_t len,char ** ret)67 static inline int string_hashsum_sha224(const char *s, size_t len, char **ret) {
68 return string_hashsum(s, len, EVP_sha224(), ret);
69 }
70
string_hashsum_sha256(const char * s,size_t len,char ** ret)71 static inline int string_hashsum_sha256(const char *s, size_t len, char **ret) {
72 return string_hashsum(s, len, EVP_sha256(), ret);
73 }
74 #endif
75