blob: b572e7160db2952ef35bde3e1c62deae356b69d4 [file] [edit]
// 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.
//
// Common conversions for working with OpenSSL CBS structs
#ifndef THIRD_PARTY_CREDENTIO_CRYPTO_CBS_UTILS_H_
#define THIRD_PARTY_CREDENTIO_CRYPTO_CBS_UTILS_H_
#include <cstddef>
#include <cstdint>
#include <string>
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "openssl/base.h"
#include "openssl/bytestring.h" // IWYU pragma: keep, CBS in base.h is incomplete
#include "openssl/mem.h" // IWYU pragma: keep, `bssl::UniquePtr` in base.h is incomplete
namespace credentio {
inline absl::string_view ToStringView(const CBS& cbs) {
return absl::string_view(reinterpret_cast<const char*>(cbs.data), cbs.len);
}
// Returns a CBS that points to the same underlying array as `sv`, Caller must
// ensure that the backing array outlives the returned CBS.
inline CBS FromStringView(absl::string_view sv) {
CBS cbs;
CBS_init(&cbs, reinterpret_cast<const uint8_t*>(sv.data()), sv.length());
return cbs;
}
// Finishes `cbb` and copies the final content to a string.
inline absl::StatusOr<std::string> FinishToString(CBB* cbb) {
uint8_t* data;
size_t len;
if (!CBB_finish(cbb, &data, &len)) {
return absl::InternalError("CBB_finish(...) failed");
}
bssl::UniquePtr<uint8_t> data_uniq(data);
return std::string(reinterpret_cast<char*>(data), len);
}
} // namespace credentio
#endif // THIRD_PARTY_CREDENTIO_CRYPTO_CBS_UTILS_H_