• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2022 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 #include "compos_key.h"
18 
19 #include <openssl/digest.h>
20 #include <openssl/hkdf.h>
21 #include <openssl/mem.h>
22 
23 using android::base::ErrnoError;
24 using android::base::Error;
25 using android::base::Result;
26 using compos_key::Ed25519KeyPair;
27 using compos_key::Signature;
28 
29 // Used to ensure the key we derive is distinct from any other.
30 constexpr const char* kSigningKeyInfo = "CompOS signing key";
31 
32 namespace compos_key {
deriveKeyFromSecret(const uint8_t * secret,size_t secret_size)33 Result<Ed25519KeyPair> deriveKeyFromSecret(const uint8_t* secret, size_t secret_size) {
34     // Ed25519 private keys are derived from a 32 byte seed:
35     // https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5
36     std::array<uint8_t, 32> seed;
37 
38     // We derive the seed from the secret using HKDF - see
39     // https://datatracker.ietf.org/doc/html/rfc5869#section-2.
40     if (!HKDF(seed.data(), seed.size(), EVP_sha256(), secret, secret_size, /*salt=*/nullptr,
41               /*salt_len=*/0, reinterpret_cast<const uint8_t*>(kSigningKeyInfo),
42               strlen(kSigningKeyInfo))) {
43         return Error() << "HKDF failed";
44     }
45 
46     Ed25519KeyPair result;
47     ED25519_keypair_from_seed(result.public_key.data(), result.private_key.data(), seed.data());
48     return result;
49 }
50 
sign(const PrivateKey & private_key,const uint8_t * data,size_t data_size)51 Result<Signature> sign(const PrivateKey& private_key, const uint8_t* data, size_t data_size) {
52     Signature result;
53     if (!ED25519_sign(result.data(), data, data_size, private_key.data())) {
54         return Error() << "Failed to sign";
55     }
56     return result;
57 }
58 
verify(const PublicKey & public_key,const Signature & signature,const uint8_t * data,size_t data_size)59 bool verify(const PublicKey& public_key, const Signature& signature, const uint8_t* data,
60             size_t data_size) {
61     return ED25519_verify(data, data_size, signature.data(), public_key.data()) == 1;
62 }
63 } // namespace compos_key
64