1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <aidl/android/hardware/security/keymint/Digest.h>
20 
21 #include <openssl/evp.h>
22 #include <openssl/x509.h>
23 
24 namespace aidl::android::hardware::security::keymint {
25 
26 template <typename T, void (*F)(T*)>
27 struct UniquePtrDeleter {
operatorUniquePtrDeleter28     void operator()(T* p) const { F(p); }
29 };
30 
31 typedef UniquePtrDeleter<EVP_PKEY, EVP_PKEY_free> EVP_PKEY_Delete;
32 
33 #define MAKE_OPENSSL_PTR_TYPE(type) \
34     typedef std::unique_ptr<type, UniquePtrDeleter<type, type##_free>> type##_Ptr;
35 
36 MAKE_OPENSSL_PTR_TYPE(ASN1_OBJECT)
37 MAKE_OPENSSL_PTR_TYPE(BN_CTX)
38 MAKE_OPENSSL_PTR_TYPE(EC_GROUP)
39 MAKE_OPENSSL_PTR_TYPE(EC_KEY)
40 MAKE_OPENSSL_PTR_TYPE(EC_POINT)
41 MAKE_OPENSSL_PTR_TYPE(EVP_PKEY)
42 MAKE_OPENSSL_PTR_TYPE(EVP_PKEY_CTX)
43 MAKE_OPENSSL_PTR_TYPE(RSA)
44 MAKE_OPENSSL_PTR_TYPE(X509)
45 MAKE_OPENSSL_PTR_TYPE(X509_NAME)
46 
47 typedef std::unique_ptr<BIGNUM, UniquePtrDeleter<BIGNUM, BN_free>> BIGNUM_Ptr;
48 
openssl_digest(Digest digest)49 inline const EVP_MD* openssl_digest(Digest digest) {
50     switch (digest) {
51         case Digest::NONE:
52             return nullptr;
53         case Digest::MD5:
54             return EVP_md5();
55         case Digest::SHA1:
56             return EVP_sha1();
57         case Digest::SHA_2_224:
58             return EVP_sha224();
59         case Digest::SHA_2_256:
60             return EVP_sha256();
61         case Digest::SHA_2_384:
62             return EVP_sha384();
63         case Digest::SHA_2_512:
64             return EVP_sha512();
65     }
66     return nullptr;
67 }
68 
69 }  // namespace aidl::android::hardware::security::keymint
70