1 /*
2  * Copyright 2017 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 #ifndef HARDWARE_INTERFACES_KEYMASTER_4_0_SUPPORT_OPENSSL_UTILS_H_
18 #define HARDWARE_INTERFACES_KEYMASTER_4_0_SUPPORT_OPENSSL_UTILS_H_
19 
20 #include <android/hardware/keymaster/4.0/types.h>
21 #include <openssl/evp.h>
22 #include <openssl/x509.h>
23 
24 template <typename T, void (*F)(T*)>
25 struct UniquePtrDeleter {
operatorUniquePtrDeleter26     void operator()(T* p) const { F(p); }
27 };
28 
29 typedef UniquePtrDeleter<EVP_PKEY, EVP_PKEY_free> EVP_PKEY_Delete;
30 
31 #define MAKE_OPENSSL_PTR_TYPE(type) \
32     typedef std::unique_ptr<type, UniquePtrDeleter<type, type##_free>> type##_Ptr;
33 
34 MAKE_OPENSSL_PTR_TYPE(ASN1_OBJECT)
35 MAKE_OPENSSL_PTR_TYPE(EVP_PKEY)
36 MAKE_OPENSSL_PTR_TYPE(RSA)
37 MAKE_OPENSSL_PTR_TYPE(X509)
38 MAKE_OPENSSL_PTR_TYPE(BN_CTX)
39 
40 typedef std::unique_ptr<BIGNUM, UniquePtrDeleter<BIGNUM, BN_free>> BIGNUM_Ptr;
41 
openssl_digest(android::hardware::keymaster::V4_0::Digest digest)42 inline const EVP_MD* openssl_digest(android::hardware::keymaster::V4_0::Digest digest) {
43     switch (digest) {
44         case android::hardware::keymaster::V4_0::Digest::NONE:
45             return nullptr;
46         case android::hardware::keymaster::V4_0::Digest::MD5:
47             return EVP_md5();
48         case android::hardware::keymaster::V4_0::Digest::SHA1:
49             return EVP_sha1();
50         case android::hardware::keymaster::V4_0::Digest::SHA_2_224:
51             return EVP_sha224();
52         case android::hardware::keymaster::V4_0::Digest::SHA_2_256:
53             return EVP_sha256();
54         case android::hardware::keymaster::V4_0::Digest::SHA_2_384:
55             return EVP_sha384();
56         case android::hardware::keymaster::V4_0::Digest::SHA_2_512:
57             return EVP_sha512();
58     }
59     return nullptr;
60 }
61 
62 #endif  // HARDWARE_INTERFACES_KEYMASTER_4_0_SUPPORT_OPENSSL_UTILS_H_
63