1 /*
2  * Copyright 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 #pragma once
18 
19 #include <utility>
20 
21 #include <keymaster/km_openssl/asymmetric_key.h>
22 #include <keymaster/km_openssl/openssl_utils.h>
23 
24 namespace keymaster {
25 
26 // OpenSSL uses 64-byte private keys for the APIs in curve25519.h, and the
27 // first 32 bytes hold the seed (as per RFC 8032).  The EVP_PKEY_* functions
28 // also only expect to deal with the seed.
29 constexpr int ED25519_SEED_LEN = 32;
30 
31 // Determine whether the key characteristics indicate the presence of an Ed25519 key.
32 bool IsEd25519Key(const AuthorizationSet& hw_enforced, const AuthorizationSet& sw_enforced);
33 
34 // Determine whether the key characteristics indicate the presence of an X25519 key.
35 bool IsX25519Key(const AuthorizationSet& hw_enforced, const AuthorizationSet& sw_enforced);
36 
37 class Curve25519Key : public AsymmetricKey {
38   public:
Curve25519Key(AuthorizationSet hw_enforced,AuthorizationSet sw_enforced,const KeyFactory * factory)39     Curve25519Key(AuthorizationSet hw_enforced, AuthorizationSet sw_enforced,
40                   const KeyFactory* factory)
41         : AsymmetricKey(std::move(hw_enforced), std::move(sw_enforced), factory) {}
Curve25519Key(AuthorizationSet hw_enforced,AuthorizationSet sw_enforced,const KeyFactory * factory,const KeymasterKeyBlob & key_material)42     Curve25519Key(AuthorizationSet hw_enforced, AuthorizationSet sw_enforced,
43                   const KeyFactory* factory, const KeymasterKeyBlob& key_material)
44         : AsymmetricKey(std::move(hw_enforced), std::move(sw_enforced), factory) {
45         key_material_ = key_material;
46     }
47 
48     EVP_PKEY_Ptr InternalToEvp() const override;
49     bool EvpToInternal(const EVP_PKEY* pkey) override;
50 };
51 
52 class Ed25519Key : public Curve25519Key {
53   public:
54     using Curve25519Key::Curve25519Key;
evp_key_type()55     int evp_key_type() const override { return EVP_PKEY_ED25519; }
56 };
57 
58 class X25519Key : public Curve25519Key {
59   public:
60     using Curve25519Key::Curve25519Key;
evp_key_type()61     int evp_key_type() const override { return EVP_PKEY_X25519; }
62 };
63 
64 }  // namespace keymaster
65