1 /* 2 * Copyright (C) 2019 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 #include "adb/crypto/key.h" 18 19 #include <android-base/logging.h> 20 #include <openssl/bn.h> 21 #include <openssl/pem.h> 22 #include <openssl/rsa.h> 23 24 namespace adb { 25 namespace crypto { 26 27 // static 28 std::string Key::ToPEMString(EVP_PKEY* pkey) { 29 bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_mem())); 30 int rc = PEM_write_bio_PKCS8PrivateKey(bio.get(), pkey, nullptr, nullptr, 0, nullptr, nullptr); 31 if (rc != 1) { 32 LOG(ERROR) << "PEM_write_bio_PKCS8PrivateKey failed"; 33 return ""; 34 } 35 36 BUF_MEM* mem = nullptr; 37 BIO_get_mem_ptr(bio.get(), &mem); 38 if (!mem || !mem->data || !mem->length) { 39 LOG(ERROR) << "BIO_get_mem_ptr failed"; 40 return ""; 41 } 42 43 return std::string(mem->data, mem->length); 44 } 45 46 } // namespace crypto 47 } // namespace adb 48