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::Seed;
28 using compos_key::Signature;
29 
30 namespace compos_key {
keyFromSeed(const Seed & seed)31 Result<Ed25519KeyPair> keyFromSeed(const Seed& seed) {
32     Ed25519KeyPair result;
33     ED25519_keypair_from_seed(result.public_key.data(), result.private_key.data(), seed.data());
34     return result;
35 }
36 
sign(const PrivateKey & private_key,const uint8_t * data,size_t data_size)37 Result<Signature> sign(const PrivateKey& private_key, const uint8_t* data, size_t data_size) {
38     Signature result;
39     if (!ED25519_sign(result.data(), data, data_size, private_key.data())) {
40         return Error() << "Failed to sign";
41     }
42     return result;
43 }
44 
verify(const PublicKey & public_key,const Signature & signature,const uint8_t * data,size_t data_size)45 bool verify(const PublicKey& public_key, const Signature& signature, const uint8_t* data,
46             size_t data_size) {
47     return ED25519_verify(data, data_size, signature.data(), public_key.data()) == 1;
48 }
49 } // namespace compos_key
50