1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "util/crypto/digest_sign.h"
6
7 namespace openscreen {
8
SignData(const EVP_MD * digest,EVP_PKEY * private_key,absl::Span<const uint8_t> data)9 ErrorOr<std::string> SignData(const EVP_MD* digest,
10 EVP_PKEY* private_key,
11 absl::Span<const uint8_t> data) {
12 bssl::ScopedEVP_MD_CTX ctx;
13 if (!EVP_DigestSignInit(ctx.get(), nullptr, digest, nullptr, private_key)) {
14 return Error::Code::kEVPInitializationError;
15 }
16 size_t signature_length = 0;
17 if ((EVP_DigestSign(ctx.get(), nullptr, &signature_length, data.data(),
18 data.size()) != 1) ||
19 signature_length == 0) {
20 return Error::Code::kEVPInitializationError;
21 }
22
23 std::string signature(signature_length, 0);
24 if (EVP_DigestSign(ctx.get(), reinterpret_cast<uint8_t*>(&signature[0]),
25 &signature_length, data.data(), data.size()) != 1) {
26 return Error::Code::kCreateSignatureFailed;
27 }
28 return signature;
29 }
30
31 } // namespace openscreen
32