| // Copyright 2026 Google LLC |
| // |
| // Licensed under the Apache License, Version 2.0 (the "License"); |
| // you may not use this file except in compliance with the License. |
| // You may obtain a copy of the License at |
| // |
| // https://www.apache.org/licenses/LICENSE-2.0 |
| // |
| // Unless required by applicable law or agreed to in writing, software |
| // distributed under the License is distributed on an "AS IS" BASIS, |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| // See the License for the specific language governing permissions and |
| // limitations under the License. |
| // |
| |
| #include "testing/boringssl_utils.h" |
| |
| #include <cstdint> |
| #include <string> |
| |
| #include "absl/base/nullability.h" |
| #include "absl/log/check.h" |
| #include "absl/log/die_if_null.h" |
| #include "absl/strings/string_view.h" |
| #include "openssl/base.h" |
| #include "openssl/bio.h" |
| #include "openssl/bytestring.h" |
| #include "openssl/mem.h" |
| #include "openssl/obj.h" |
| #include "openssl/pem.h" |
| #include "openssl/x509.h" |
| |
| namespace credentio { |
| |
| bssl::UniquePtr<X509> absl_nullable PemToCertificate(absl::string_view pem) { |
| bssl::UniquePtr<BIO> bio( |
| BIO_new_mem_buf(const_cast<char*>(pem.data()), pem.size())); |
| X509* x509 = PEM_read_bio_X509(bio.get(), nullptr /* existing key */, |
| nullptr /* password callback */, |
| nullptr /* password */); |
| return bssl::UniquePtr<X509>(x509); |
| } |
| |
| bssl::UniquePtr<EVP_PKEY> absl_nullable PemToKey(absl::string_view pem) { |
| bssl::UniquePtr<BIO> bio( |
| BIO_new_mem_buf(const_cast<char*>(pem.data()), pem.size())); |
| EVP_PKEY* pkey = PEM_read_bio_PrivateKey( |
| bio.get(), nullptr /* existing key */, nullptr /* password callback */, |
| nullptr /* password */); |
| return bssl::UniquePtr<EVP_PKEY>(pkey); |
| } |
| |
| std::string PemToDer(absl::string_view pem) { |
| bssl::UniquePtr<BIO> bio(ABSL_DIE_IF_NULL( |
| BIO_new_mem_buf(const_cast<char*>(pem.data()), pem.size()))); |
| |
| char* name; |
| char* header; |
| uint8_t* data; |
| long len; // NOLINT: Can't use `int64_t` because on ARM that becomes long |
| // long which is incompatible with `PEM_read_bio(...)`. |
| CHECK(PEM_read_bio(bio.get(), &name, &header, &data, &len)); |
| // Smart pointers for clean-up only. |
| bssl::UniquePtr<char> name_uniq(name); |
| bssl::UniquePtr<char> header_uniq(header); |
| bssl::UniquePtr<uint8_t> data_uniq(data); |
| |
| return std::string(reinterpret_cast<const char*>(data), len); |
| } |
| |
| } // namespace credentio |