p256/
lib.rs

1#![no_std]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3#![doc = include_str!("../README.md")]
4#![doc(
5    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg",
6    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg"
7)]
8#![forbid(unsafe_code)]
9#![warn(
10    clippy::mod_module_files,
11    clippy::unwrap_used,
12    missing_docs,
13    rust_2018_idioms,
14    unused_lifetimes,
15    unused_qualifications
16)]
17
18//! ## `serde` support
19//!
20//! When the `serde` feature of this crate is enabled, `Serialize` and
21//! `Deserialize` are impl'd for the following types:
22//!
23//! - [`AffinePoint`]
24//! - [`Scalar`]
25//! - [`ecdsa::VerifyingKey`]
26//!
27//! Please see type-specific documentation for more information.
28
29#[cfg(feature = "arithmetic")]
30mod arithmetic;
31
32#[cfg(feature = "ecdh")]
33pub mod ecdh;
34
35#[cfg(feature = "ecdsa-core")]
36pub mod ecdsa;
37
38#[cfg(any(feature = "test-vectors", test))]
39pub mod test_vectors;
40
41pub use elliptic_curve::{self, bigint::U256, consts::U32};
42
43#[cfg(feature = "arithmetic")]
44pub use arithmetic::{scalar::Scalar, AffinePoint, ProjectivePoint};
45
46#[cfg(feature = "expose-field")]
47pub use arithmetic::field::FieldElement;
48
49#[cfg(feature = "pkcs8")]
50pub use elliptic_curve::pkcs8;
51
52use elliptic_curve::{
53    bigint::ArrayEncoding, consts::U33, generic_array::GenericArray, FieldBytesEncoding,
54};
55
56/// Order of NIST P-256's elliptic curve group (i.e. scalar modulus) serialized
57/// as hexadecimal.
58///
59/// ```text
60/// n = FFFFFFFF 00000000 FFFFFFFF FFFFFFFF BCE6FAAD A7179E84 F3B9CAC2 FC632551
61/// ```
62///
63/// # Calculating the order
64/// One way to calculate the order is with `GP/PARI`:
65///
66/// ```text
67/// p = (2^224) * (2^32 - 1) + 2^192 + 2^96 - 1
68/// b = 41058363725152142129326129780047268409114441015993725554835256314039467401291
69/// E = ellinit([Mod(-3, p), Mod(b, p)])
70/// default(parisize, 120000000)
71/// n = ellsea(E)
72/// isprime(n)
73/// ```
74const ORDER_HEX: &str = "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551";
75
76/// NIST P-256 elliptic curve.
77///
78/// This curve is also known as prime256v1 (ANSI X9.62) and secp256r1 (SECG)
79/// and is specified in [NIST SP 800-186]:
80/// Recommendations for Discrete Logarithm-based Cryptography:
81/// Elliptic Curve Domain Parameters.
82///
83/// It's included in the US National Security Agency's "Suite B" and is widely
84/// used in protocols like TLS and the associated X.509 PKI.
85///
86/// Its equation is `y² = x³ - 3x + b` over a ~256-bit prime field where `b` is
87/// the "verifiably random"† constant:
88///
89/// ```text
90/// b = 41058363725152142129326129780047268409114441015993725554835256314039467401291
91/// ```
92///
93/// † *NOTE: the specific origins of this constant have never been fully disclosed
94///   (it is the SHA-1 digest of an unknown NSA-selected constant)*
95///
96/// [NIST SP 800-186]: https://csrc.nist.gov/publications/detail/sp/800-186/final
97#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
98pub struct NistP256;
99
100impl elliptic_curve::Curve for NistP256 {
101    /// 32-byte serialized field elements.
102    type FieldBytesSize = U32;
103
104    /// 256-bit integer type used for internally representing field elements.
105    type Uint = U256;
106
107    /// Order of NIST P-256's elliptic curve group (i.e. scalar modulus).
108    const ORDER: U256 = U256::from_be_hex(ORDER_HEX);
109}
110
111impl elliptic_curve::PrimeCurve for NistP256 {}
112
113impl elliptic_curve::point::PointCompression for NistP256 {
114    /// NIST P-256 points are typically uncompressed.
115    const COMPRESS_POINTS: bool = false;
116}
117
118impl elliptic_curve::point::PointCompaction for NistP256 {
119    /// NIST P-256 points are typically uncompressed.
120    const COMPACT_POINTS: bool = false;
121}
122
123#[cfg(feature = "jwk")]
124impl elliptic_curve::JwkParameters for NistP256 {
125    const CRV: &'static str = "P-256";
126}
127
128#[cfg(feature = "pkcs8")]
129impl pkcs8::AssociatedOid for NistP256 {
130    const OID: pkcs8::ObjectIdentifier = pkcs8::ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
131}
132
133/// Blinded scalar.
134#[cfg(feature = "arithmetic")]
135pub type BlindedScalar = elliptic_curve::scalar::BlindedScalar<NistP256>;
136
137/// Compressed SEC1-encoded NIST P-256 curve point.
138pub type CompressedPoint = GenericArray<u8, U33>;
139
140/// NIST P-256 SEC1 encoded point.
141pub type EncodedPoint = elliptic_curve::sec1::EncodedPoint<NistP256>;
142
143/// NIST P-256 field element serialized as bytes.
144///
145/// Byte array containing a serialized field element value (base field or scalar).
146pub type FieldBytes = elliptic_curve::FieldBytes<NistP256>;
147
148impl FieldBytesEncoding<NistP256> for U256 {
149    fn decode_field_bytes(field_bytes: &FieldBytes) -> Self {
150        U256::from_be_byte_array(*field_bytes)
151    }
152
153    fn encode_field_bytes(&self) -> FieldBytes {
154        self.to_be_byte_array()
155    }
156}
157
158/// Non-zero NIST P-256 scalar field element.
159#[cfg(feature = "arithmetic")]
160pub type NonZeroScalar = elliptic_curve::NonZeroScalar<NistP256>;
161
162/// NIST P-256 public key.
163#[cfg(feature = "arithmetic")]
164pub type PublicKey = elliptic_curve::PublicKey<NistP256>;
165
166/// NIST P-256 secret key.
167pub type SecretKey = elliptic_curve::SecretKey<NistP256>;
168
169#[cfg(not(feature = "arithmetic"))]
170impl elliptic_curve::sec1::ValidatePublicKey for NistP256 {}
171
172/// Bit representation of a NIST P-256 scalar field element.
173#[cfg(feature = "bits")]
174pub type ScalarBits = elliptic_curve::scalar::ScalarBits<NistP256>;
175
176#[cfg(feature = "voprf")]
177impl elliptic_curve::VoprfParameters for NistP256 {
178    /// See <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-19.html#section-4.3>.
179    const ID: &'static str = "P256-SHA256";
180
181    /// See <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-4.3-1.2>.
182    type Hash = sha2::Sha256;
183}