1 /* 2 * Copyright 2014 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 SYSTEM_KEYMASTER_OPENSSL_UTILS_H_ 18 #define SYSTEM_KEYMASTER_OPENSSL_UTILS_H_ 19 20 #include <openssl/bn.h> 21 #include <openssl/evp.h> 22 #include <openssl/ec.h> 23 #include <openssl/rsa.h> 24 #include <openssl/x509.h> 25 26 #include <UniquePtr.h> 27 28 #include <hardware/keymaster_defs.h> 29 30 namespace keymaster { 31 32 struct KeymasterKeyBlob; 33 34 struct EVP_PKEY_Delete { 35 void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); } 36 }; 37 38 struct BIGNUM_Delete { 39 void operator()(BIGNUM* p) const { BN_free(p); } 40 }; 41 42 struct BN_CTX_Delete { 43 void operator()(BN_CTX* p) const { BN_CTX_free(p); } 44 }; 45 46 struct PKCS8_PRIV_KEY_INFO_Delete { 47 void operator()(PKCS8_PRIV_KEY_INFO* p) const { PKCS8_PRIV_KEY_INFO_free(p); } 48 }; 49 50 struct RSA_Delete { 51 void operator()(RSA* p) { RSA_free(p); } 52 }; 53 54 struct EC_GROUP_Delete { 55 void operator()(EC_GROUP* p) { EC_GROUP_free(p); } 56 }; 57 58 struct EC_Delete { 59 void operator()(EC_KEY* p) { EC_KEY_free(p); } 60 }; 61 62 /** 63 * Many OpenSSL APIs take ownership of an argument on success but don't free the argument on 64 * failure. This means we need to tell our scoped pointers when we've transferred ownership, without 65 * triggering a warning by not using the result of release(). 66 */ 67 template <typename T, typename Delete_T> 68 inline void release_because_ownership_transferred(UniquePtr<T, Delete_T>& p) { 69 T* val __attribute__((unused)) = p.release(); 70 } 71 72 keymaster_error_t convert_pkcs8_blob_to_evp(const uint8_t* key_data, size_t key_length, 73 keymaster_algorithm_t expected_algorithm, 74 UniquePtr<EVP_PKEY, EVP_PKEY_Delete>* pkey); 75 76 keymaster_error_t KeyMaterialToEvpKey(keymaster_key_format_t key_format, 77 const KeymasterKeyBlob& key_material, 78 keymaster_algorithm_t expected_algorithm, 79 UniquePtr<EVP_PKEY, EVP_PKEY_Delete>* evp_pkey); 80 81 keymaster_error_t EvpKeyToKeyMaterial(const EVP_PKEY* evp_pkey, KeymasterKeyBlob* key_blob); 82 83 } // namespace keymaster 84 85 #endif // SYSTEM_KEYMASTER_OPENSSL_UTILS_H_ 86