| // 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 "crypto/default/pem.h" |
| |
| #include <string> |
| #include <vector> |
| |
| #include "absl/status/status.h" |
| #include "absl/status/statusor.h" |
| #include "absl/strings/string_view.h" |
| #include "openssl/bio.h" |
| #include "openssl/mem.h" |
| #include "openssl/pem.h" |
| #include "openssl/x509.h" |
| |
| namespace credentio { |
| |
| absl::StatusOr<std::vector<std::string>> LoadCertsFromPem( |
| absl::string_view pem) { |
| bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(pem.data(), pem.size())); |
| if (bio == nullptr) { |
| return absl::InternalError("Failed to create BIO."); |
| } |
| |
| std::vector<std::string> chain; |
| while (true) { |
| bssl::UniquePtr<X509> cert( |
| PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr)); |
| if (cert == nullptr) { |
| break; |
| } |
| |
| unsigned char* der = nullptr; |
| int len = i2d_X509(cert.get(), &der); |
| if (len < 0) { |
| return absl::InternalError("Failed to convert cert to DER."); |
| } |
| chain.push_back(std::string(reinterpret_cast<char*>(der), len)); |
| OPENSSL_free(der); |
| } |
| |
| if (chain.empty()) { |
| return absl::InvalidArgumentError("No certificates found"); |
| } |
| |
| return chain; |
| } |
| |
| } // namespace credentio |