blob: d0ea3c71ad56613a2144696d287dbb9186b38f3a [file] [log] [blame]
Yifan Hong1deca4b2021-09-10 16:16:44 -07001/*
2 * Copyright (C) 2021 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#define LOG_TAG "RpcCertificateUtils"
18#include <log/log.h>
19
20#include <binder/RpcCertificateUtils.h>
21
22#include "Utils.h"
23
24namespace android {
25
26namespace {
27
28bssl::UniquePtr<X509> fromPem(const std::vector<uint8_t>& cert) {
29 if (cert.size() > std::numeric_limits<int>::max()) return nullptr;
30 bssl::UniquePtr<BIO> certBio(BIO_new_mem_buf(cert.data(), static_cast<int>(cert.size())));
31 return bssl::UniquePtr<X509>(PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
32}
33
34} // namespace
35
36bssl::UniquePtr<X509> deserializeCertificate(const std::vector<uint8_t>& cert,
37 CertificateFormat format) {
38 switch (format) {
39 case CertificateFormat::PEM:
40 return fromPem(cert);
41 }
42 LOG_ALWAYS_FATAL("Unsupported format %d", static_cast<int>(format));
43}
44
45std::vector<uint8_t> serializeCertificate(X509* x509, CertificateFormat format) {
46 bssl::UniquePtr<BIO> certBio(BIO_new(BIO_s_mem()));
47 switch (format) {
48 case CertificateFormat::PEM: {
49 TEST_AND_RETURN({}, PEM_write_bio_X509(certBio.get(), x509));
50 } break;
51 default: {
52 LOG_ALWAYS_FATAL("Unsupported format %d", static_cast<int>(format));
53 }
54 }
55 const uint8_t* data;
56 size_t len;
57 TEST_AND_RETURN({}, BIO_mem_contents(certBio.get(), &data, &len));
58 return std::vector<uint8_t>(data, data + len);
59}
60
61} // namespace android