Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / third_party / betocore / crypto_provider / src / ecdsa.rs

ecdsa.rs231 lines · 8.7 KiBRaw
1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use tinyvec::ArrayVec;
16
17/// The maximum length of a DER-encoded ecdsa `Signature`, in bytes.
18pub const SIGNATURE_MAX_LENGTH: usize = 72;
19
20/// The length of an ecdsa `PrivateKey`, in bytes.
21pub const PRIVATE_KEY_LENGTH: usize = 32;
22
23/// The length of a sec1 ecdsa `PublicKey`, in bytes.
24pub const PUBLIC_KEY_LENGTH: usize = 65;
25
26/// A byte buffer the size of a P256 ecdsa `Signature`.
27pub type RawP256Signature = ArrayVec<[u8; SIGNATURE_MAX_LENGTH]>;
28
29/// A byte buffer the size of a ecdsa `PublicKey`.
30pub type RawP256PublicKey = [u8; PUBLIC_KEY_LENGTH];
31
32/// A byte buffer the size of a ecdsa `PrivateKey`.
33pub type RawP256PrivateKey = [u8; PRIVATE_KEY_LENGTH];
34
35/// A permission token which may be supplied to methods which allow
36/// converting private keys to/from raw bytes.
37///
38/// In general, operations of this kind should only be done in
39/// development-tools, tests, or in credential storage layers
40/// to prevent accidental exposure of the private key.
41pub struct RawPrivateKeyPermit {
42 _marker: (),
43}
44
45impl RawPrivateKeyPermit {
46 /// Allows for internal construction of a private key permit to
47 /// allow accessing a raw private key.
48 fn new() -> Self {
49 Self { _marker: () }
50 }
51}
52
53/// This implementation is behind a feature flag to allow auditing of uses for
54/// constructing a private key from raw bytes.
55#[cfg(feature = "raw_private_key_permit")]
56impl core::default::Default for RawPrivateKeyPermit {
57 fn default() -> Self {
58 Self::new()
59 }
60}
61
62/// A crypto-provider-independent representation of the private
63/// key of a P256 ECDSA key-pair, kept in such a way that
64/// it does not permit de-structuring it into raw bytes,
65/// nor constructing one from raw bytes.
66pub struct P256PrivateKey {
67 key: RawP256PrivateKey,
68}
69
70impl P256PrivateKey {
71 /// This must be kept private in order to ensure safety of the private key material.
72 /// [Self::from_raw_private_key] adds a [RawPrivateKeyPermit] to allow auditing of usages to
73 /// ensure that proper precautions are taken when handling the raw key material.
74 fn new(key: RawP256PrivateKey) -> Self {
75 Self { key }
76 }
77
78 /// Derives the public key corresponding to this private key.
79 pub fn derive_public_key<E: P256EcdsaProvider>(&self) -> impl PublicKey {
80 let key_pair = E::P256KeyPair::from_private_key(self);
81 key_pair.public_key()
82 }
83
84 /// Sign the given message and return a digital signature
85 pub fn sign<E: P256EcdsaProvider>(&self, msg: &[u8]) -> impl Signature {
86 let key_pair = E::P256KeyPair::from_private_key(self);
87 key_pair.sign(msg)
88 }
89
90 /// Generate an ecdsa private key from a CSPRNG
91 /// generate is not available in `no-std`.
92 #[cfg(feature = "std")]
93 pub fn generate<E: P256EcdsaProvider>() -> Self {
94 let key_pair = E::P256KeyPair::generate();
95 (&key_pair).into()
96 }
97
98 /// Returns the raw bytes of this private key.
99 /// This operation is only possible while holding a [`RawPrivateKeyPermit`].
100 pub fn raw_private_key(&self, _permit: &RawPrivateKeyPermit) -> RawP256PrivateKey {
101 self.key
102 }
103
104 /// Constructs a private key from the raw bytes of the key.
105 /// This operation is only possible while holding a [`RawPrivateKeyPermit`].
106 pub fn from_raw_private_key(wrapped: RawP256PrivateKey, _permit: &RawPrivateKeyPermit) -> Self {
107 P256PrivateKey::new(wrapped)
108 }
109}
110
111/// Error returned when bad bytes are used to instantiate a private key.
112#[derive(Debug)]
113pub struct InvalidPrivateKeyBytes;
114
115/// error returned when bad bytes are provided to generate keypair
116#[derive(Debug)]
117pub struct InvalidPublicKeyBytes;
118
119/// Error returned invalid bytes are used to instantiate a signature.
120#[derive(Debug)]
121pub struct InvalidSignatureBytes;
122
123/// Error returned if the verification on the signature + message fails
124#[derive(Debug)]
125pub struct VerifyError;
126
127/// Collection of types used to provide an implementation of ecdsa.
128pub trait P256EcdsaProvider {
129 /// The internal representation of a keypair which includes both public and secret halves of an asymmetric key.
130 type P256KeyPair: KeyPair<
131 P256PublicKey = Self::P256PublicKey,
132 P256Signature = Self::P256Signature,
133 >;
134 /// The internal representation of an ecdsa public key, used when verifying a message
135 type P256PublicKey: PublicKey<Signature = Self::P256Signature>;
136 /// The internal representation of an ecdsa signature which is the result of signing a message
137 type P256Signature: Signature;
138}
139
140/// The keypair which includes both public and secret halves of an asymmetric key.
141/// This is different from [Self::P256PublicKey] as it includes operations to create a raw private
142/// key as well. The private key operations are contained in this trait, and the public key can be
143/// extracted from the private key to be used for verification. This trait is what providers
144/// implement to add ECDSA-P256 functionality.
145pub trait KeyPair: Sized {
146 /// The ecdsa public key, used when verifying a message
147 type P256PublicKey: PublicKey;
148
149 /// The ecdsa signature returned when signing a message
150 type P256Signature: Signature;
151
152 /// Returns the private key bytes of the `KeyPair`.
153 /// This operation is only possible while holding a [`RawPrivateKeyPermit`].
154 fn raw_private_key(&self, _permit: &RawPrivateKeyPermit) -> RawP256PrivateKey;
155
156 /// Builds a key-pair from a `RawPrivateKey` array of bytes.
157 /// This operation is only possible while holding a [`RawPrivateKeyPermit`].
158 fn from_raw_private_key(bytes: &RawP256PrivateKey, _permit: &RawPrivateKeyPermit) -> Self
159 where
160 Self: Sized;
161
162 /// Sign the given message and return a digital signature
163 fn sign(&self, msg: &[u8]) -> Self::P256Signature;
164
165 /// Generate an ecdsa keypair from a CSPRNG
166 /// generate is not available in `no-std`
167 #[cfg(feature = "std")]
168 fn generate() -> Self;
169
170 /// Builds a key-pair from a [`P256PrivateKey`], given in an opaque form.
171 fn from_private_key(private_key: &P256PrivateKey) -> Self
172 where
173 Self: Sized,
174 {
175 // We're okay to reach in and construct an instance from
176 // the bytes of the private key, since the way that they
177 // were originally expressed would still require a valid
178 // [`RawPrivateKeyPermit`] to access them.
179 let raw_private_key = &private_key.key;
180 Self::from_raw_private_key(raw_private_key, &RawPrivateKeyPermit::new())
181 }
182
183 /// Getter function for the Public Key of the key pair
184 fn public_key(&self) -> Self::P256PublicKey;
185}
186
187impl<K> From<&K> for P256PrivateKey
188where
189 K: KeyPair,
190{
191 fn from(value: &K) -> Self {
192 // We're okay to reach in and grab the bytes of the private key,
193 // since the way that we're exposing it would require a valid
194 // [`RawPrivateKeyPermit`] to extract them again.
195 let wrapped = value.raw_private_key(&RawPrivateKeyPermit::new());
196 P256PrivateKey::new(wrapped)
197 }
198}
199
200/// An ecdsa signature
201pub trait Signature: Sized {
202 /// Create a new signature from a fixed size byte array. This represents a container for the
203 /// byte serialization of an ECDSA signature, and does not necessarily represent well-formed
204 /// field or curve elements.
205 ///
206 /// Signature verification libraries are expected to reject invalid field
207 /// elements at the time a signature is verified (not constructed).
208 fn from_bytes(bytes: &RawP256Signature) -> Result<Self, InvalidSignatureBytes>;
209
210 /// Returns a slice of the signature bytes
211 fn to_bytes(&self) -> RawP256Signature;
212}
213
214/// An ecdsa public key.
215pub trait PublicKey {
216 /// The signature type being used by verify
217 type Signature: Signature;
218
219 /// Builds this public key from an array of bytes in
220 /// the SEC1 format.
221 fn from_bytes(bytes: &RawP256PublicKey) -> Result<Self, InvalidPublicKeyBytes>
222 where
223 Self: Sized;
224
225 /// Yields the bytes of the public key in a SEC1 format.
226 fn to_bytes(&self) -> RawP256PublicKey;
227
228 /// Succeeds if the signature was a valid signature created by this Keypair on the prehashed_message.
229 fn verify_strict(&self, message: &[u8], signature: &Self::Signature)
230 -> Result<(), VerifyError>;
231}