Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
// Copyright 2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! Elliptic curve operations and schemes using Curve25519.
|
||||
|
||||
pub mod ed25519;
|
||||
|
||||
pub mod x25519;
|
||||
|
||||
mod ops;
|
||||
mod scalar;
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
// Copyright 2015-2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! EdDSA Signatures.
|
||||
|
||||
use super::ops::ELEM_LEN;
|
||||
use crate::digest;
|
||||
|
||||
pub mod signing;
|
||||
pub mod verification;
|
||||
|
||||
/// The length of an Ed25519 public key.
|
||||
pub const ED25519_PUBLIC_KEY_LEN: usize = ELEM_LEN;
|
||||
|
||||
pub fn eddsa_digest(signature_r: &[u8], public_key: &[u8], msg: &[u8]) -> digest::Digest {
|
||||
let mut ctx = digest::Context::new(&digest::SHA512);
|
||||
ctx.update(signature_r);
|
||||
ctx.update(public_key);
|
||||
ctx.update(msg);
|
||||
ctx.finish()
|
||||
}
|
||||
Binary file not shown.
+275
@@ -0,0 +1,275 @@
|
||||
// Copyright 2015-2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! EdDSA Signatures.
|
||||
|
||||
use super::{super::ops::*, eddsa_digest, ED25519_PUBLIC_KEY_LEN};
|
||||
use crate::{
|
||||
cpu, digest, error,
|
||||
io::der,
|
||||
pkcs8, rand,
|
||||
signature::{self, KeyPair as SigningKeyPair},
|
||||
};
|
||||
|
||||
/// An Ed25519 key pair, for signing.
|
||||
pub struct Ed25519KeyPair {
|
||||
// RFC 8032 Section 5.1.6 calls this *s*.
|
||||
private_scalar: Scalar,
|
||||
|
||||
// RFC 8032 Section 5.1.6 calls this *prefix*.
|
||||
private_prefix: Prefix,
|
||||
|
||||
// RFC 8032 Section 5.1.5 calls this *A*.
|
||||
public_key: PublicKey,
|
||||
}
|
||||
|
||||
derive_debug_via_field!(Ed25519KeyPair, stringify!(Ed25519KeyPair), public_key);
|
||||
|
||||
impl Ed25519KeyPair {
|
||||
/// Generates a new key pair and returns the key pair serialized as a
|
||||
/// PKCS#8 document.
|
||||
///
|
||||
/// The PKCS#8 document will be a v2 `OneAsymmetricKey` with the public key,
|
||||
/// as described in [RFC 5958 Section 2]; see [RFC 8410 Section 10.3] for an
|
||||
/// example.
|
||||
///
|
||||
/// [RFC 5958 Section 2]: https://tools.ietf.org/html/rfc5958#section-2
|
||||
/// [RFC 8410 Section 10.3]: https://tools.ietf.org/html/rfc8410#section-10.3
|
||||
pub fn generate_pkcs8(
|
||||
rng: &dyn rand::SecureRandom,
|
||||
) -> Result<pkcs8::Document, error::Unspecified> {
|
||||
let cpu_features = cpu::features();
|
||||
let seed: [u8; SEED_LEN] = rand::generate(rng)?.expose();
|
||||
let key_pair = Self::from_seed_(&seed, cpu_features);
|
||||
Ok(pkcs8::wrap_key(
|
||||
&PKCS8_TEMPLATE,
|
||||
&seed[..],
|
||||
key_pair.public_key().as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Constructs an Ed25519 key pair by parsing an unencrypted PKCS#8 v2
|
||||
/// Ed25519 private key.
|
||||
///
|
||||
/// `openssl genpkey -algorithm ED25519` generates PKCS# v1 keys, which
|
||||
/// require the use of `Ed25519KeyPair::from_pkcs8_maybe_unchecked()`
|
||||
/// instead of `Ed25519KeyPair::from_pkcs8()`.
|
||||
///
|
||||
/// The input must be in PKCS#8 v2 format, and in particular it must contain
|
||||
/// the public key in addition to the private key. `from_pkcs8()` will
|
||||
/// verify that the public key and the private key are consistent with each
|
||||
/// other.
|
||||
///
|
||||
/// Some early implementations of PKCS#8 v2, including earlier versions of
|
||||
/// *ring* and other implementations, wrapped the public key in the wrong
|
||||
/// ASN.1 tags. Both that incorrect form and the standardized form are
|
||||
/// accepted.
|
||||
///
|
||||
/// If you need to parse PKCS#8 v1 files (without the public key) then use
|
||||
/// `Ed25519KeyPair::from_pkcs8_maybe_unchecked()` instead.
|
||||
pub fn from_pkcs8(pkcs8: &[u8]) -> Result<Self, error::KeyRejected> {
|
||||
let version = pkcs8::Version::V2Only(pkcs8::PublicKeyOptions {
|
||||
accept_legacy_ed25519_public_key_tag: true,
|
||||
});
|
||||
let (seed, public_key) = unwrap_pkcs8(version, untrusted::Input::from(pkcs8))?;
|
||||
Self::from_seed_and_public_key(
|
||||
seed.as_slice_less_safe(),
|
||||
public_key.unwrap().as_slice_less_safe(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Constructs an Ed25519 key pair by parsing an unencrypted PKCS#8 v1 or v2
|
||||
/// Ed25519 private key.
|
||||
///
|
||||
/// `openssl genpkey -algorithm ED25519` generates PKCS# v1 keys.
|
||||
///
|
||||
/// It is recommended to use `Ed25519KeyPair::from_pkcs8()`, which accepts
|
||||
/// only PKCS#8 v2 files that contain the public key.
|
||||
/// `from_pkcs8_maybe_unchecked()` parses PKCS#2 files exactly like
|
||||
/// `from_pkcs8()`. It also accepts v1 files. PKCS#8 v1 files do not contain
|
||||
/// the public key, so when a v1 file is parsed the public key will be
|
||||
/// computed from the private key, and there will be no consistency check
|
||||
/// between the public key and the private key.
|
||||
///
|
||||
/// Some early implementations of PKCS#8 v2, including earlier versions of
|
||||
/// *ring* and other implementations, wrapped the public key in the wrong
|
||||
/// ASN.1 tags. Both that incorrect form and the standardized form are
|
||||
/// accepted.
|
||||
///
|
||||
/// PKCS#8 v2 files are parsed exactly like `Ed25519KeyPair::from_pkcs8()`.
|
||||
pub fn from_pkcs8_maybe_unchecked(pkcs8: &[u8]) -> Result<Self, error::KeyRejected> {
|
||||
let version = pkcs8::Version::V1OrV2(pkcs8::PublicKeyOptions {
|
||||
accept_legacy_ed25519_public_key_tag: true,
|
||||
});
|
||||
let (seed, public_key) = unwrap_pkcs8(version, untrusted::Input::from(pkcs8))?;
|
||||
if let Some(public_key) = public_key {
|
||||
Self::from_seed_and_public_key(
|
||||
seed.as_slice_less_safe(),
|
||||
public_key.as_slice_less_safe(),
|
||||
)
|
||||
} else {
|
||||
Self::from_seed_unchecked(seed.as_slice_less_safe())
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs an Ed25519 key pair from the private key seed `seed` and its
|
||||
/// public key `public_key`.
|
||||
///
|
||||
/// It is recommended to use `Ed25519KeyPair::from_pkcs8()` instead.
|
||||
///
|
||||
/// The private and public keys will be verified to be consistent with each
|
||||
/// other. This helps avoid misuse of the key (e.g. accidentally swapping
|
||||
/// the private key and public key, or using the wrong private key for the
|
||||
/// public key). This also detects any corruption of the public or private
|
||||
/// key.
|
||||
pub fn from_seed_and_public_key(
|
||||
seed: &[u8],
|
||||
public_key: &[u8],
|
||||
) -> Result<Self, error::KeyRejected> {
|
||||
let pair = Self::from_seed_unchecked(seed)?;
|
||||
|
||||
// This implicitly verifies that `public_key` is the right length.
|
||||
// XXX: This rejects ~18 keys when they are partially reduced, though
|
||||
// those keys are virtually impossible to find.
|
||||
if public_key != pair.public_key.as_ref() {
|
||||
let err = if public_key.len() != pair.public_key.as_ref().len() {
|
||||
error::KeyRejected::invalid_encoding()
|
||||
} else {
|
||||
error::KeyRejected::inconsistent_components()
|
||||
};
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
Ok(pair)
|
||||
}
|
||||
|
||||
/// Constructs a Ed25519 key pair from the private key seed `seed`.
|
||||
///
|
||||
/// It is recommended to use `Ed25519KeyPair::from_pkcs8()` instead. When
|
||||
/// that is not practical, it is recommended to use
|
||||
/// `Ed25519KeyPair::from_seed_and_public_key()` instead.
|
||||
///
|
||||
/// Since the public key is not given, the public key will be computed from
|
||||
/// the private key. It is not possible to detect misuse or corruption of
|
||||
/// the private key since the public key isn't given as input.
|
||||
pub fn from_seed_unchecked(seed: &[u8]) -> Result<Self, error::KeyRejected> {
|
||||
let seed = seed
|
||||
.try_into()
|
||||
.map_err(|_| error::KeyRejected::invalid_encoding())?;
|
||||
Ok(Self::from_seed_(seed, cpu::features()))
|
||||
}
|
||||
|
||||
fn from_seed_(seed: &Seed, cpu_features: cpu::Features) -> Self {
|
||||
let h = digest::digest(&digest::SHA512, seed);
|
||||
let (private_scalar, private_prefix) = h.as_ref().split_at(SCALAR_LEN);
|
||||
|
||||
let private_scalar =
|
||||
MaskedScalar::from_bytes_masked(private_scalar.try_into().unwrap()).into();
|
||||
|
||||
let a = ExtPoint::from_scalarmult_base(&private_scalar, cpu_features);
|
||||
|
||||
Self {
|
||||
private_scalar,
|
||||
private_prefix: private_prefix.try_into().unwrap(),
|
||||
public_key: PublicKey(a.into_encoded_point(cpu_features)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the signature of the message `msg`.
|
||||
pub fn sign(&self, msg: &[u8]) -> signature::Signature {
|
||||
let cpu_features = cpu::features();
|
||||
signature::Signature::new(|signature_bytes| {
|
||||
prefixed_extern! {
|
||||
fn x25519_sc_muladd(
|
||||
s: &mut [u8; SCALAR_LEN],
|
||||
a: &Scalar,
|
||||
b: &Scalar,
|
||||
c: &Scalar,
|
||||
);
|
||||
}
|
||||
|
||||
let (signature_bytes, _unused) = signature_bytes.split_at_mut(ELEM_LEN + SCALAR_LEN);
|
||||
let (signature_r, signature_s) = signature_bytes.split_at_mut(ELEM_LEN);
|
||||
let nonce = {
|
||||
let mut ctx = digest::Context::new(&digest::SHA512);
|
||||
ctx.update(&self.private_prefix);
|
||||
ctx.update(msg);
|
||||
ctx.finish()
|
||||
};
|
||||
let nonce = Scalar::from_sha512_digest_reduced(nonce);
|
||||
|
||||
let r = ExtPoint::from_scalarmult_base(&nonce, cpu_features);
|
||||
signature_r.copy_from_slice(&r.into_encoded_point(cpu_features));
|
||||
let hram_digest = eddsa_digest(signature_r, self.public_key.as_ref(), msg);
|
||||
let hram = Scalar::from_sha512_digest_reduced(hram_digest);
|
||||
unsafe {
|
||||
x25519_sc_muladd(
|
||||
signature_s.try_into().unwrap(),
|
||||
&hram,
|
||||
&self.private_scalar,
|
||||
&nonce,
|
||||
);
|
||||
}
|
||||
|
||||
SIGNATURE_LEN
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl signature::KeyPair for Ed25519KeyPair {
|
||||
type PublicKey = PublicKey;
|
||||
|
||||
fn public_key(&self) -> &Self::PublicKey {
|
||||
&self.public_key
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PublicKey([u8; ED25519_PUBLIC_KEY_LEN]);
|
||||
|
||||
impl AsRef<[u8]> for PublicKey {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
derive_debug_self_as_ref_hex_bytes!(PublicKey);
|
||||
|
||||
fn unwrap_pkcs8(
|
||||
version: pkcs8::Version,
|
||||
input: untrusted::Input,
|
||||
) -> Result<(untrusted::Input, Option<untrusted::Input>), error::KeyRejected> {
|
||||
let (private_key, public_key) = pkcs8::unwrap_key(&PKCS8_TEMPLATE, version, input)?;
|
||||
let private_key = private_key
|
||||
.read_all(error::Unspecified, |input| {
|
||||
der::expect_tag_and_get_value(input, der::Tag::OctetString)
|
||||
})
|
||||
.map_err(|error::Unspecified| error::KeyRejected::invalid_encoding())?;
|
||||
Ok((private_key, public_key))
|
||||
}
|
||||
|
||||
type Prefix = [u8; PREFIX_LEN];
|
||||
const PREFIX_LEN: usize = digest::SHA512_OUTPUT_LEN - SCALAR_LEN;
|
||||
|
||||
const SIGNATURE_LEN: usize = ELEM_LEN + SCALAR_LEN;
|
||||
|
||||
type Seed = [u8; SEED_LEN];
|
||||
const SEED_LEN: usize = 32;
|
||||
|
||||
static PKCS8_TEMPLATE: pkcs8::Template = pkcs8::Template {
|
||||
bytes: include_bytes!("ed25519_pkcs8_v2_template.der"),
|
||||
alg_id_range: core::ops::Range { start: 7, end: 12 },
|
||||
curve_id_index: 0,
|
||||
private_key_index: 0x10,
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
// Copyright 2015-2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! EdDSA Signatures.
|
||||
|
||||
use super::{super::ops::*, eddsa_digest};
|
||||
use crate::{cpu, error, sealed, signature};
|
||||
|
||||
/// Parameters for EdDSA signing and verification.
|
||||
pub struct EdDSAParameters;
|
||||
|
||||
impl core::fmt::Debug for EdDSAParameters {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
|
||||
write!(f, "ring::signature::ED25519")
|
||||
}
|
||||
}
|
||||
|
||||
/// Verification of [Ed25519] signatures.
|
||||
///
|
||||
/// Ed25519 uses SHA-512 as the digest algorithm.
|
||||
///
|
||||
/// [Ed25519]: https://ed25519.cr.yp.to/
|
||||
pub static ED25519: EdDSAParameters = EdDSAParameters {};
|
||||
|
||||
impl signature::VerificationAlgorithm for EdDSAParameters {
|
||||
fn verify(
|
||||
&self,
|
||||
public_key: untrusted::Input,
|
||||
msg: untrusted::Input,
|
||||
signature: untrusted::Input,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let cpu_features = cpu::features();
|
||||
|
||||
let public_key: &[u8; ELEM_LEN] = public_key.as_slice_less_safe().try_into()?;
|
||||
let (signature_r, signature_s) = signature.read_all(error::Unspecified, |input| {
|
||||
let signature_r: &[u8; ELEM_LEN] = input
|
||||
.read_bytes(ELEM_LEN)?
|
||||
.as_slice_less_safe()
|
||||
.try_into()?;
|
||||
let signature_s: &[u8; SCALAR_LEN] = input
|
||||
.read_bytes(SCALAR_LEN)?
|
||||
.as_slice_less_safe()
|
||||
.try_into()?;
|
||||
Ok((signature_r, signature_s))
|
||||
})?;
|
||||
|
||||
let signature_s = Scalar::from_bytes_checked(*signature_s)?;
|
||||
|
||||
let mut a = ExtPoint::from_encoded_point_vartime(public_key)?;
|
||||
a.invert_vartime();
|
||||
|
||||
let h_digest = eddsa_digest(signature_r, public_key, msg.as_slice_less_safe());
|
||||
let h = Scalar::from_sha512_digest_reduced(h_digest);
|
||||
|
||||
let mut r = Point::new_at_infinity();
|
||||
unsafe { x25519_ge_double_scalarmult_vartime(&mut r, &h, &a, &signature_s) };
|
||||
let r_check = r.into_encoded_point(cpu_features);
|
||||
if *signature_r != r_check {
|
||||
return Err(error::Unspecified);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl sealed::Sealed for EdDSAParameters {}
|
||||
|
||||
prefixed_extern! {
|
||||
fn x25519_ge_double_scalarmult_vartime(
|
||||
r: &mut Point,
|
||||
a_coeff: &Scalar,
|
||||
a: &ExtPoint,
|
||||
b_coeff: &Scalar,
|
||||
);
|
||||
}
|
||||
Vendored
+180
@@ -0,0 +1,180 @@
|
||||
// Copyright 2015-2017 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! Elliptic curve operations on the birationally equivalent curves Curve25519
|
||||
//! and Edwards25519.
|
||||
|
||||
pub use super::scalar::{MaskedScalar, Scalar, SCALAR_LEN};
|
||||
use crate::{
|
||||
bssl, cpu, error,
|
||||
limb::{Limb, LIMB_BITS},
|
||||
};
|
||||
use core::{ffi::c_int, marker::PhantomData};
|
||||
|
||||
// Elem<T>` is `fe` in curve25519/internal.h.
|
||||
// Elem<L> is `fe_loose` in curve25519/internal.h.
|
||||
// Keep this in sync with curve25519/internal.h.
|
||||
#[repr(C)]
|
||||
pub struct Elem<E: Encoding> {
|
||||
limbs: [Limb; ELEM_LIMBS], // This is called `v` in the C code.
|
||||
encoding: PhantomData<E>,
|
||||
}
|
||||
|
||||
pub trait Encoding {}
|
||||
pub struct T;
|
||||
impl Encoding for T {}
|
||||
|
||||
const ELEM_LIMBS: usize = 5 * 64 / LIMB_BITS;
|
||||
|
||||
impl<E: Encoding> Elem<E> {
|
||||
fn zero() -> Self {
|
||||
Self {
|
||||
limbs: Default::default(),
|
||||
encoding: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Elem<T> {
|
||||
fn negate(&mut self) {
|
||||
unsafe {
|
||||
x25519_fe_neg(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An encoding of a curve point. If on Curve25519, it should be encoded as
|
||||
// described in Section 5 of [RFC 7748]. If on Edwards25519, it should be
|
||||
// encoded as described in section 5.1.2 of [RFC 8032].
|
||||
//
|
||||
// [RFC 7748] https://tools.ietf.org/html/rfc7748#section-5
|
||||
// [RFC 8032] https://tools.ietf.org/html/rfc8032#section-5.1.2
|
||||
pub type EncodedPoint = [u8; ELEM_LEN];
|
||||
pub const ELEM_LEN: usize = 32;
|
||||
|
||||
// Keep this in sync with `ge_p3` in curve25519/internal.h.
|
||||
#[repr(C)]
|
||||
pub struct ExtPoint {
|
||||
x: Elem<T>,
|
||||
y: Elem<T>,
|
||||
z: Elem<T>,
|
||||
t: Elem<T>,
|
||||
}
|
||||
|
||||
impl ExtPoint {
|
||||
// Returns the result of multiplying the base point by the scalar in constant time.
|
||||
pub(super) fn from_scalarmult_base(scalar: &Scalar, cpu: cpu::Features) -> Self {
|
||||
let mut r = Self {
|
||||
x: Elem::zero(),
|
||||
y: Elem::zero(),
|
||||
z: Elem::zero(),
|
||||
t: Elem::zero(),
|
||||
};
|
||||
prefixed_extern! {
|
||||
fn x25519_ge_scalarmult_base(h: &mut ExtPoint, a: &Scalar, has_fe25519_adx: c_int);
|
||||
}
|
||||
unsafe {
|
||||
x25519_ge_scalarmult_base(&mut r, scalar, has_fe25519_adx(cpu).into());
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
pub fn from_encoded_point_vartime(encoded: &EncodedPoint) -> Result<Self, error::Unspecified> {
|
||||
let mut point = Self {
|
||||
x: Elem::zero(),
|
||||
y: Elem::zero(),
|
||||
z: Elem::zero(),
|
||||
t: Elem::zero(),
|
||||
};
|
||||
|
||||
Result::from(unsafe { x25519_ge_frombytes_vartime(&mut point, encoded) }).map(|()| point)
|
||||
}
|
||||
|
||||
pub(super) fn into_encoded_point(self, cpu_features: cpu::Features) -> EncodedPoint {
|
||||
encode_point(self.x, self.y, self.z, cpu_features)
|
||||
}
|
||||
|
||||
pub(super) fn invert_vartime(&mut self) {
|
||||
self.x.negate();
|
||||
self.t.negate();
|
||||
}
|
||||
}
|
||||
|
||||
// Keep this in sync with `ge_p2` in curve25519/internal.h.
|
||||
#[repr(C)]
|
||||
pub struct Point {
|
||||
x: Elem<T>,
|
||||
y: Elem<T>,
|
||||
z: Elem<T>,
|
||||
}
|
||||
|
||||
impl Point {
|
||||
pub fn new_at_infinity() -> Self {
|
||||
Self {
|
||||
x: Elem::zero(),
|
||||
y: Elem::zero(),
|
||||
z: Elem::zero(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn into_encoded_point(self, cpu_features: cpu::Features) -> EncodedPoint {
|
||||
encode_point(self.x, self.y, self.z, cpu_features)
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_point(x: Elem<T>, y: Elem<T>, z: Elem<T>, _cpu_features: cpu::Features) -> EncodedPoint {
|
||||
let mut bytes = [0; ELEM_LEN];
|
||||
|
||||
let sign_bit: u8 = unsafe {
|
||||
let mut recip = Elem::zero();
|
||||
x25519_fe_invert(&mut recip, &z);
|
||||
|
||||
let mut x_over_z = Elem::zero();
|
||||
x25519_fe_mul_ttt(&mut x_over_z, &x, &recip);
|
||||
|
||||
let mut y_over_z = Elem::zero();
|
||||
x25519_fe_mul_ttt(&mut y_over_z, &y, &recip);
|
||||
x25519_fe_tobytes(&mut bytes, &y_over_z);
|
||||
|
||||
x25519_fe_isnegative(&x_over_z)
|
||||
};
|
||||
|
||||
// The preceding computations must execute in constant time, but this
|
||||
// doesn't need to.
|
||||
bytes[ELEM_LEN - 1] ^= sign_bit << 7;
|
||||
|
||||
bytes
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(super) fn has_fe25519_adx(cpu: cpu::Features) -> bool {
|
||||
cfg_if::cfg_if! {
|
||||
if #[cfg(all(target_arch = "x86_64", not(target_os = "windows")))] {
|
||||
use cpu::{intel::{Adx, Bmi1, Bmi2}, GetFeature as _};
|
||||
matches!(cpu.get_feature(), Some((Adx { .. }, Bmi1 { .. }, Bmi2 { .. })))
|
||||
} else {
|
||||
let _ = cpu;
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
prefixed_extern! {
|
||||
fn x25519_fe_invert(out: &mut Elem<T>, z: &Elem<T>);
|
||||
fn x25519_fe_isnegative(elem: &Elem<T>) -> u8;
|
||||
fn x25519_fe_mul_ttt(h: &mut Elem<T>, f: &Elem<T>, g: &Elem<T>);
|
||||
fn x25519_fe_neg(f: &mut Elem<T>);
|
||||
fn x25519_fe_tobytes(bytes: &mut EncodedPoint, elem: &Elem<T>);
|
||||
fn x25519_ge_frombytes_vartime(h: &mut ExtPoint, s: &EncodedPoint) -> bssl::Result;
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
// Copyright 2015-2019 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
use crate::{
|
||||
arithmetic::limbs_from_hex,
|
||||
digest, error, limb,
|
||||
polyfill::slice::{self, AsChunks},
|
||||
};
|
||||
use core::array;
|
||||
|
||||
#[repr(transparent)]
|
||||
pub struct Scalar([u8; SCALAR_LEN]);
|
||||
|
||||
pub const SCALAR_LEN: usize = 32;
|
||||
|
||||
impl Scalar {
|
||||
// Constructs a `Scalar` from `bytes`, failing if `bytes` encodes a scalar
|
||||
// that is not in the range [0, n).
|
||||
pub fn from_bytes_checked(bytes: [u8; SCALAR_LEN]) -> Result<Self, error::Unspecified> {
|
||||
const ORDER: [limb::Limb; SCALAR_LEN / limb::LIMB_BYTES] =
|
||||
limbs_from_hex("1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed");
|
||||
let order = ORDER.map(limb::Limb::from);
|
||||
|
||||
let (limbs_as_bytes, _empty): (AsChunks<u8, { limb::LIMB_BYTES }>, _) =
|
||||
slice::as_chunks(&bytes);
|
||||
debug_assert!(_empty.is_empty());
|
||||
let limbs: [limb::Limb; SCALAR_LEN / limb::LIMB_BYTES] =
|
||||
array::from_fn(|i| limb::Limb::from_le_bytes(limbs_as_bytes[i]));
|
||||
limb::verify_limbs_less_than_limbs_leak_bit(&limbs, &order)?;
|
||||
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
|
||||
// Constructs a `Scalar` from `digest` reduced modulo n.
|
||||
pub fn from_sha512_digest_reduced(digest: digest::Digest) -> Self {
|
||||
prefixed_extern! {
|
||||
fn x25519_sc_reduce(s: &mut UnreducedScalar);
|
||||
}
|
||||
let mut unreduced = [0u8; digest::SHA512_OUTPUT_LEN];
|
||||
unreduced.copy_from_slice(digest.as_ref());
|
||||
unsafe { x25519_sc_reduce(&mut unreduced) };
|
||||
Self((&unreduced[..SCALAR_LEN]).try_into().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(transparent)]
|
||||
pub struct MaskedScalar([u8; SCALAR_LEN]);
|
||||
|
||||
impl MaskedScalar {
|
||||
pub fn from_bytes_masked(bytes: [u8; SCALAR_LEN]) -> Self {
|
||||
prefixed_extern! {
|
||||
fn x25519_sc_mask(a: &mut [u8; SCALAR_LEN]);
|
||||
}
|
||||
let mut r = Self(bytes);
|
||||
unsafe { x25519_sc_mask(&mut r.0) };
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
impl From<MaskedScalar> for Scalar {
|
||||
fn from(MaskedScalar(scalar): MaskedScalar) -> Self {
|
||||
Self(scalar)
|
||||
}
|
||||
}
|
||||
|
||||
type UnreducedScalar = [u8; UNREDUCED_SCALAR_LEN];
|
||||
const UNREDUCED_SCALAR_LEN: usize = SCALAR_LEN * 2;
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
// Copyright 2015-2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! X25519 Key agreement.
|
||||
|
||||
use super::{ops, scalar::SCALAR_LEN};
|
||||
use crate::{agreement, bb, cpu, ec, error, rand};
|
||||
use core::ffi::c_int;
|
||||
|
||||
static CURVE25519: ec::Curve = ec::Curve {
|
||||
public_key_len: PUBLIC_KEY_LEN,
|
||||
elem_scalar_seed_len: ELEM_AND_SCALAR_LEN,
|
||||
id: ec::CurveID::Curve25519,
|
||||
check_private_key_bytes: x25519_check_private_key_bytes,
|
||||
generate_private_key: x25519_generate_private_key,
|
||||
public_from_private: x25519_public_from_private,
|
||||
};
|
||||
|
||||
/// X25519 (ECDH using Curve25519) as described in [RFC 7748].
|
||||
///
|
||||
/// Everything is as described in RFC 7748. Key agreement will fail if the
|
||||
/// result of the X25519 operation is zero; see the notes on the
|
||||
/// "all-zero value" in [RFC 7748 section 6.1].
|
||||
///
|
||||
/// [RFC 7748]: https://tools.ietf.org/html/rfc7748
|
||||
/// [RFC 7748 section 6.1]: https://tools.ietf.org/html/rfc7748#section-6.1
|
||||
pub static X25519: agreement::Algorithm = agreement::Algorithm {
|
||||
curve: &CURVE25519,
|
||||
ecdh: x25519_ecdh,
|
||||
};
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
fn x25519_check_private_key_bytes(
|
||||
bytes: &[u8],
|
||||
_: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
debug_assert_eq!(bytes.len(), PRIVATE_KEY_LEN);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn x25519_generate_private_key(
|
||||
rng: &dyn rand::SecureRandom,
|
||||
out: &mut [u8],
|
||||
_: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
rng.fill(out)
|
||||
}
|
||||
|
||||
fn x25519_public_from_private(
|
||||
public_out: &mut [u8],
|
||||
private_key: &ec::Seed,
|
||||
cpu_features: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let public_out = public_out.try_into()?;
|
||||
|
||||
let private_key: &[u8; SCALAR_LEN] = private_key.bytes_less_safe().try_into()?;
|
||||
let private_key = ops::MaskedScalar::from_bytes_masked(*private_key);
|
||||
|
||||
#[cfg(all(
|
||||
all(target_arch = "arm", target_endian = "little"),
|
||||
any(target_os = "android", target_os = "linux")
|
||||
))]
|
||||
if let Some(cpu) = <cpu::Features as cpu::GetFeature<_>>::get_feature(&cpu_features) {
|
||||
static MONTGOMERY_BASE_POINT: [u8; 32] = [
|
||||
9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0,
|
||||
];
|
||||
x25519_neon(public_out, &private_key, &MONTGOMERY_BASE_POINT, cpu);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
prefixed_extern! {
|
||||
fn x25519_public_from_private_generic_masked(
|
||||
public_key_out: &mut PublicKey,
|
||||
private_key: &PrivateKey,
|
||||
use_adx: c_int,
|
||||
);
|
||||
}
|
||||
unsafe {
|
||||
x25519_public_from_private_generic_masked(
|
||||
public_out,
|
||||
&private_key,
|
||||
ops::has_fe25519_adx(cpu_features).into(),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn x25519_ecdh(
|
||||
out: &mut [u8],
|
||||
my_private_key: &ec::Seed,
|
||||
peer_public_key: untrusted::Input,
|
||||
cpu_features: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let my_private_key: &[u8; SCALAR_LEN] = my_private_key.bytes_less_safe().try_into()?;
|
||||
let my_private_key = ops::MaskedScalar::from_bytes_masked(*my_private_key);
|
||||
let peer_public_key: &[u8; PUBLIC_KEY_LEN] = peer_public_key.as_slice_less_safe().try_into()?;
|
||||
|
||||
fn scalar_mult(
|
||||
out: &mut ops::EncodedPoint,
|
||||
scalar: &ops::MaskedScalar,
|
||||
point: &ops::EncodedPoint,
|
||||
#[allow(unused_variables)] cpu_features: cpu::Features,
|
||||
) {
|
||||
#[cfg(all(
|
||||
all(target_arch = "arm", target_endian = "little"),
|
||||
any(target_os = "android", target_os = "linux")
|
||||
))]
|
||||
if let Some(cpu) = <cpu::Features as cpu::GetFeature<_>>::get_feature(&cpu_features) {
|
||||
return x25519_neon(out, scalar, point, cpu);
|
||||
}
|
||||
|
||||
#[cfg(all(target_arch = "x86_64", not(target_os = "windows")))]
|
||||
{
|
||||
if ops::has_fe25519_adx(cpu_features) {
|
||||
prefixed_extern! {
|
||||
fn x25519_scalar_mult_adx(
|
||||
out: &mut ops::EncodedPoint,
|
||||
scalar: &ops::MaskedScalar,
|
||||
point: &ops::EncodedPoint,
|
||||
);
|
||||
}
|
||||
return unsafe { x25519_scalar_mult_adx(out, scalar, point) };
|
||||
}
|
||||
}
|
||||
|
||||
prefixed_extern! {
|
||||
fn x25519_scalar_mult_generic_masked(
|
||||
out: &mut ops::EncodedPoint,
|
||||
scalar: &ops::MaskedScalar,
|
||||
point: &ops::EncodedPoint,
|
||||
);
|
||||
}
|
||||
unsafe {
|
||||
x25519_scalar_mult_generic_masked(out, scalar, point);
|
||||
}
|
||||
}
|
||||
|
||||
scalar_mult(
|
||||
out.try_into()?,
|
||||
&my_private_key,
|
||||
peer_public_key,
|
||||
cpu_features,
|
||||
);
|
||||
|
||||
let zeros: SharedSecret = [0; SHARED_SECRET_LEN];
|
||||
if bb::verify_slices_are_equal(out, &zeros).is_ok() {
|
||||
// All-zero output results when the input is a point of small order.
|
||||
return Err(error::Unspecified);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// BoringSSL uses `!defined(OPENSSL_APPLE)`.
|
||||
#[cfg(all(
|
||||
all(target_arch = "arm", target_endian = "little"),
|
||||
any(target_os = "android", target_os = "linux")
|
||||
))]
|
||||
fn x25519_neon(
|
||||
out: &mut ops::EncodedPoint,
|
||||
scalar: &ops::MaskedScalar,
|
||||
point: &ops::EncodedPoint,
|
||||
_cpu: cpu::arm::Neon,
|
||||
) {
|
||||
prefixed_extern! {
|
||||
fn x25519_NEON(
|
||||
out: &mut ops::EncodedPoint,
|
||||
scalar: &ops::MaskedScalar,
|
||||
point: &ops::EncodedPoint,
|
||||
);
|
||||
}
|
||||
unsafe { x25519_NEON(out, scalar, point) }
|
||||
}
|
||||
|
||||
const ELEM_AND_SCALAR_LEN: usize = ops::ELEM_LEN;
|
||||
|
||||
type PrivateKey = ops::MaskedScalar;
|
||||
const PRIVATE_KEY_LEN: usize = ELEM_AND_SCALAR_LEN;
|
||||
|
||||
// An X25519 public key as an encoded Curve25519 point.
|
||||
type PublicKey = [u8; PUBLIC_KEY_LEN];
|
||||
const PUBLIC_KEY_LEN: usize = ELEM_AND_SCALAR_LEN;
|
||||
|
||||
// An X25519 shared secret as an encoded Curve25519 point.
|
||||
type SharedSecret = [u8; SHARED_SECRET_LEN];
|
||||
const SHARED_SECRET_LEN: usize = ELEM_AND_SCALAR_LEN;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::ec;
|
||||
use untrusted::Input;
|
||||
|
||||
#[test]
|
||||
fn test_x25519_public_from_private() {
|
||||
struct TestVector {
|
||||
private: [u8; 32],
|
||||
public: [u8; 32],
|
||||
}
|
||||
static TEST_CASES: &[TestVector] = &[
|
||||
TestVector {
|
||||
private: [
|
||||
0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1, 0x72, 0x51,
|
||||
0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0, 0x99, 0x2a, 0xb1, 0x77,
|
||||
0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a,
|
||||
],
|
||||
public: [
|
||||
0x85, 0x20, 0xf0, 0x09, 0x89, 0x30, 0xa7, 0x54, 0x74, 0x8b, 0x7d, 0xdc, 0xb4,
|
||||
0x3e, 0xf7, 0x5a, 0x0d, 0xbf, 0x3a, 0x0d, 0x26, 0x38, 0x1a, 0xf4, 0xeb, 0xa4,
|
||||
0xa9, 0x8e, 0xaa, 0x9b, 0x4e, 0x6a,
|
||||
],
|
||||
},
|
||||
TestVector {
|
||||
private: [
|
||||
0x5d, 0xab, 0x08, 0x7e, 0x62, 0x4a, 0x8a, 0x4b, 0x79, 0xe1, 0x7f, 0x8b, 0x83,
|
||||
0x80, 0x0e, 0xe6, 0x6f, 0x3b, 0xb1, 0x29, 0x26, 0x18, 0xb6, 0xfd, 0x1c, 0x2f,
|
||||
0x8b, 0x27, 0xff, 0x88, 0xe0, 0xeb,
|
||||
],
|
||||
public: [
|
||||
0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4, 0xd3, 0x5b, 0x61, 0xc2, 0xec,
|
||||
0xe4, 0x35, 0x37, 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78, 0x67, 0x4d, 0xad, 0xfc,
|
||||
0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f,
|
||||
],
|
||||
},
|
||||
];
|
||||
let cpu_features = cpu::features();
|
||||
for test_case in TEST_CASES {
|
||||
let seed =
|
||||
ec::Seed::from_bytes(&CURVE25519, Input::from(&test_case.private), cpu_features)
|
||||
.unwrap();
|
||||
let mut output = [0u8; 32];
|
||||
x25519_public_from_private(&mut output, &seed, cpu_features).unwrap();
|
||||
assert_eq!(output, test_case.public);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+97
@@ -0,0 +1,97 @@
|
||||
use super::{Curve, ELEM_MAX_BYTES, SEED_MAX_BYTES};
|
||||
use crate::{cpu, error, rand};
|
||||
|
||||
pub struct KeyPair {
|
||||
seed: Seed,
|
||||
public_key: PublicKey,
|
||||
}
|
||||
|
||||
impl KeyPair {
|
||||
pub(super) fn derive(
|
||||
seed: Seed,
|
||||
cpu_features: cpu::Features,
|
||||
) -> Result<Self, error::Unspecified> {
|
||||
let public_key = seed.compute_public_key(cpu_features)?;
|
||||
Ok(Self { seed, public_key })
|
||||
}
|
||||
|
||||
pub fn public_key(&self) -> &PublicKey {
|
||||
&self.public_key
|
||||
}
|
||||
pub fn split(self) -> (Seed, PublicKey) {
|
||||
(self.seed, self.public_key)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Seed {
|
||||
bytes: [u8; SEED_MAX_BYTES],
|
||||
curve: &'static Curve,
|
||||
}
|
||||
|
||||
impl Seed {
|
||||
pub(crate) fn generate(
|
||||
curve: &'static Curve,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
cpu: cpu::Features,
|
||||
) -> Result<Self, error::Unspecified> {
|
||||
let mut r = Self {
|
||||
bytes: [0u8; SEED_MAX_BYTES],
|
||||
curve,
|
||||
};
|
||||
(curve.generate_private_key)(rng, &mut r.bytes[..curve.elem_scalar_seed_len], cpu)?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub(crate) fn from_bytes(
|
||||
curve: &'static Curve,
|
||||
bytes: untrusted::Input,
|
||||
cpu: cpu::Features,
|
||||
) -> Result<Self, error::Unspecified> {
|
||||
let bytes = bytes.as_slice_less_safe();
|
||||
if curve.elem_scalar_seed_len != bytes.len() {
|
||||
return Err(error::Unspecified);
|
||||
}
|
||||
(curve.check_private_key_bytes)(bytes, cpu)?;
|
||||
let mut r = Self {
|
||||
bytes: [0; SEED_MAX_BYTES],
|
||||
curve,
|
||||
};
|
||||
r.bytes[..curve.elem_scalar_seed_len].copy_from_slice(bytes);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub fn bytes_less_safe(&self) -> &[u8] {
|
||||
&self.bytes[..self.curve.elem_scalar_seed_len]
|
||||
}
|
||||
|
||||
pub(crate) fn compute_public_key(
|
||||
&self,
|
||||
cpu_features: cpu::Features,
|
||||
) -> Result<PublicKey, error::Unspecified> {
|
||||
let mut public_key = PublicKey {
|
||||
bytes: [0u8; PUBLIC_KEY_MAX_LEN],
|
||||
len: self.curve.public_key_len,
|
||||
};
|
||||
(self.curve.public_from_private)(
|
||||
&mut public_key.bytes[..public_key.len],
|
||||
self,
|
||||
cpu_features,
|
||||
)?;
|
||||
Ok(public_key)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct PublicKey {
|
||||
bytes: [u8; PUBLIC_KEY_MAX_LEN],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for PublicKey {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
&self.bytes[..self.len]
|
||||
}
|
||||
}
|
||||
|
||||
/// The maximum length, in bytes, of an encoded public key.
|
||||
pub const PUBLIC_KEY_MAX_LEN: usize = 1 + (2 * ELEM_MAX_BYTES);
|
||||
Vendored
+239
@@ -0,0 +1,239 @@
|
||||
// Copyright 2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! Elliptic curve operations on P-256 & P-384.
|
||||
|
||||
use self::ops::*;
|
||||
use crate::{arithmetic::montgomery::*, cpu, ec, error, io::der, pkcs8};
|
||||
|
||||
// NIST SP 800-56A Step 3: "If q is an odd prime p, verify that
|
||||
// yQ**2 = xQ**3 + axQ + b in GF(p), where the arithmetic is performed modulo
|
||||
// p."
|
||||
//
|
||||
// That is, verify that (x, y) is on the curve, which is true iif:
|
||||
//
|
||||
// y**2 == x**3 + a*x + b (mod q)
|
||||
//
|
||||
// Or, equivalently, but more efficiently:
|
||||
//
|
||||
// y**2 == (x**2 + a)*x + b (mod q)
|
||||
//
|
||||
fn verify_affine_point_is_on_the_curve(
|
||||
q: &Modulus<Q>,
|
||||
(x, y): (&Elem<R>, &Elem<R>),
|
||||
) -> Result<(), error::Unspecified> {
|
||||
verify_affine_point_is_on_the_curve_scaled(q, (x, y), &Elem::from(q.a()), &Elem::from(q.b()))
|
||||
}
|
||||
|
||||
// Use `verify_affine_point_is_on_the_curve` instead of this function whenever
|
||||
// the affine coordinates are available or will become available. This function
|
||||
// should only be used then the affine coordinates are never calculated. See
|
||||
// the notes for `verify_affine_point_is_on_the_curve_scaled`.
|
||||
//
|
||||
// The value `z**2` is returned on success because it is useful for ECDSA
|
||||
// verification.
|
||||
//
|
||||
// This function also verifies that the point is not at infinity.
|
||||
fn verify_jacobian_point_is_on_the_curve(
|
||||
q: &Modulus<Q>,
|
||||
p: &Point,
|
||||
) -> Result<Elem<R>, error::Unspecified> {
|
||||
let z = q.point_z(p);
|
||||
|
||||
// Verify that the point is not at infinity.
|
||||
q.elem_verify_is_not_zero(&z)?;
|
||||
|
||||
let x = q.point_x(p);
|
||||
let y = q.point_y(p);
|
||||
|
||||
// We are given Jacobian coordinates (x, y, z). So, we have:
|
||||
//
|
||||
// (x/z**2, y/z**3) == (x', y'),
|
||||
//
|
||||
// where (x', y') are the affine coordinates. The curve equation is:
|
||||
//
|
||||
// y'**2 == x'**3 + a*x' + b == (x'**2 + a)*x' + b
|
||||
//
|
||||
// Substituting our Jacobian coordinates, we get:
|
||||
//
|
||||
// / y \**2 / / x \**2 \ / x \
|
||||
// | ---- | == | | ---- | + a | * | ---- | + b
|
||||
// \ z**3 / \ \ z**2 / / \ z**2 /
|
||||
//
|
||||
// Simplify:
|
||||
//
|
||||
// y**2 / x**2 \ x
|
||||
// ---- == | ---- + a | * ---- + b
|
||||
// z**6 \ z**4 / z**2
|
||||
//
|
||||
// Multiply both sides by z**6:
|
||||
//
|
||||
// z**6 / x**2 \ z**6
|
||||
// ---- * y**2 == | ---- + a | * ---- * x + (z**6) * b
|
||||
// z**6 \ z**4 / z**2
|
||||
//
|
||||
// Simplify:
|
||||
//
|
||||
// / x**2 \
|
||||
// y**2 == | ---- + a | * z**4 * x + (z**6) * b
|
||||
// \ z**4 /
|
||||
//
|
||||
// Distribute z**4:
|
||||
//
|
||||
// / z**4 \
|
||||
// y**2 == | ---- * x**2 + z**4 * a | * x + (z**6) * b
|
||||
// \ z**4 /
|
||||
//
|
||||
// Simplify:
|
||||
//
|
||||
// y**2 == (x**2 + z**4 * a) * x + (z**6) * b
|
||||
//
|
||||
let z2 = q.elem_squared(&z);
|
||||
let z4 = q.elem_squared(&z2);
|
||||
let z4_a = q.elem_product(&z4, &Elem::from(q.a()));
|
||||
let z6 = q.elem_product(&z4, &z2);
|
||||
let z6_b = q.elem_product(&z6, &Elem::from(q.b()));
|
||||
verify_affine_point_is_on_the_curve_scaled(q, (&x, &y), &z4_a, &z6_b)?;
|
||||
Ok(z2)
|
||||
}
|
||||
|
||||
// Handles the common logic of point-is-on-the-curve checks for both affine and
|
||||
// Jacobian cases.
|
||||
//
|
||||
// When doing the check that the point is on the curve after a computation,
|
||||
// to avoid fault attacks or mitigate potential bugs, it is better for security
|
||||
// to use `verify_affine_point_is_on_the_curve` on the affine coordinates,
|
||||
// because it provides some protection against faults that occur in the
|
||||
// computation of the inverse of `z`. See the paper and presentation "Fault
|
||||
// Attacks on Projective-to-Affine Coordinates Conversion" by Diana Maimuţ,
|
||||
// Cédric Murdica, David Naccache, Mehdi Tibouchi. That presentation concluded
|
||||
// simply "Check the validity of the result after conversion to affine
|
||||
// coordinates." (It seems like a good idea to verify that
|
||||
// z_inv * z == 1 mod q too).
|
||||
//
|
||||
// In the case of affine coordinates (x, y), `a_scaled` and `b_scaled` are
|
||||
// `a` and `b`, respectively. In the case of Jacobian coordinates (x, y, z),
|
||||
// the computation and comparison is the same, except `a_scaled` and `b_scaled`
|
||||
// are (z**4 * a) and (z**6 * b), respectively. Thus, performance is another
|
||||
// reason to prefer doing the check on the affine coordinates, as Jacobian
|
||||
// computation requires 3 extra multiplications and 2 extra squarings.
|
||||
//
|
||||
// An example of a fault attack that isn't mitigated by a point-on-the-curve
|
||||
// check after multiplication is given in "Sign Change Fault Attacks On
|
||||
// Elliptic Curve Cryptosystems" by Johannes Blömer, Martin Otto, and
|
||||
// Jean-Pierre Seifert.
|
||||
fn verify_affine_point_is_on_the_curve_scaled(
|
||||
q: &Modulus<Q>,
|
||||
(x, y): (&Elem<R>, &Elem<R>),
|
||||
a_scaled: &Elem<R>,
|
||||
b_scaled: &Elem<R>,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let lhs = q.elem_squared(y);
|
||||
|
||||
let mut rhs = q.elem_squared(x);
|
||||
q.add_assign(&mut rhs, a_scaled);
|
||||
q.elem_mul(&mut rhs, x);
|
||||
q.add_assign(&mut rhs, b_scaled);
|
||||
|
||||
if !q.elems_are_equal(&lhs, &rhs).leak() {
|
||||
return Err(error::Unspecified);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn key_pair_from_pkcs8(
|
||||
curve: &'static ec::Curve,
|
||||
template: &pkcs8::Template,
|
||||
input: untrusted::Input,
|
||||
cpu_features: cpu::Features,
|
||||
) -> Result<ec::KeyPair, error::KeyRejected> {
|
||||
let (ec_private_key, _) = pkcs8::unwrap_key(template, pkcs8::Version::V1Only, input)?;
|
||||
let (private_key, public_key) =
|
||||
ec_private_key.read_all(error::KeyRejected::invalid_encoding(), |input| {
|
||||
// https://tools.ietf.org/html/rfc5915#section-3
|
||||
der::nested(
|
||||
input,
|
||||
der::Tag::Sequence,
|
||||
error::KeyRejected::invalid_encoding(),
|
||||
|input| key_pair_from_pkcs8_(template, input),
|
||||
)
|
||||
})?;
|
||||
key_pair_from_bytes(curve, private_key, public_key, cpu_features)
|
||||
}
|
||||
|
||||
fn key_pair_from_pkcs8_<'a>(
|
||||
template: &pkcs8::Template,
|
||||
input: &mut untrusted::Reader<'a>,
|
||||
) -> Result<(untrusted::Input<'a>, untrusted::Input<'a>), error::KeyRejected> {
|
||||
let version = der::small_nonnegative_integer(input)
|
||||
.map_err(|error::Unspecified| error::KeyRejected::invalid_encoding())?;
|
||||
if version != 1 {
|
||||
return Err(error::KeyRejected::version_not_supported());
|
||||
}
|
||||
|
||||
let private_key = der::expect_tag_and_get_value(input, der::Tag::OctetString)
|
||||
.map_err(|error::Unspecified| error::KeyRejected::invalid_encoding())?;
|
||||
|
||||
// [0] parameters (optional).
|
||||
if input.peek(u8::from(der::Tag::ContextSpecificConstructed0)) {
|
||||
let actual_alg_id =
|
||||
der::expect_tag_and_get_value(input, der::Tag::ContextSpecificConstructed0)
|
||||
.map_err(|error::Unspecified| error::KeyRejected::invalid_encoding())?;
|
||||
if actual_alg_id.as_slice_less_safe() != template.curve_oid().as_slice_less_safe() {
|
||||
return Err(error::KeyRejected::wrong_algorithm());
|
||||
}
|
||||
}
|
||||
|
||||
// [1] publicKey. The RFC says it is optional, but we require it
|
||||
// to be present.
|
||||
let public_key = der::nested(
|
||||
input,
|
||||
der::Tag::ContextSpecificConstructed1,
|
||||
error::Unspecified,
|
||||
der::bit_string_with_no_unused_bits,
|
||||
)
|
||||
.map_err(|error::Unspecified| error::KeyRejected::invalid_encoding())?;
|
||||
|
||||
Ok((private_key, public_key))
|
||||
}
|
||||
|
||||
pub(crate) fn key_pair_from_bytes(
|
||||
curve: &'static ec::Curve,
|
||||
private_key_bytes: untrusted::Input,
|
||||
public_key_bytes: untrusted::Input,
|
||||
cpu_features: cpu::Features,
|
||||
) -> Result<ec::KeyPair, error::KeyRejected> {
|
||||
let seed = ec::Seed::from_bytes(curve, private_key_bytes, cpu_features)
|
||||
.map_err(|error::Unspecified| error::KeyRejected::invalid_component())?;
|
||||
|
||||
let r = ec::KeyPair::derive(seed, cpu_features)
|
||||
.map_err(|error::Unspecified| error::KeyRejected::unexpected_error())?;
|
||||
if public_key_bytes.as_slice_less_safe() != r.public_key().as_ref() {
|
||||
return Err(error::KeyRejected::inconsistent_components());
|
||||
}
|
||||
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
pub mod curve;
|
||||
|
||||
pub mod ecdh;
|
||||
|
||||
pub mod ecdsa;
|
||||
|
||||
mod ops;
|
||||
|
||||
mod private_key;
|
||||
mod public_key;
|
||||
Vendored
+93
@@ -0,0 +1,93 @@
|
||||
// Copyright 2015-2017 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
use crate::{cpu, ec, error, rand};
|
||||
|
||||
/// A key agreement algorithm.
|
||||
macro_rules! suite_b_curve {
|
||||
( $NAME:ident, $bits:expr, $private_key_ops:expr, $id:expr,
|
||||
$check_private_key_bytes:ident, $generate_private_key:ident,
|
||||
$public_from_private:ident) => {
|
||||
/// Public keys are encoding in uncompressed form using the
|
||||
/// Octet-String-to-Elliptic-Curve-Point algorithm in
|
||||
/// [SEC 1: Elliptic Curve Cryptography, Version 2.0]. Public keys are
|
||||
/// validated during key agreement according to
|
||||
/// [NIST Special Publication 800-56A, revision 2] and Appendix B.3 of
|
||||
/// the NSA's [Suite B Implementer's Guide to NIST SP 800-56A].
|
||||
///
|
||||
/// [SEC 1: Elliptic Curve Cryptography, Version 2.0]:
|
||||
/// http://www.secg.org/sec1-v2.pdf
|
||||
/// [NIST Special Publication 800-56A, revision 2]:
|
||||
/// http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
|
||||
/// [Suite B Implementer's Guide to NIST SP 800-56A]:
|
||||
/// https://github.com/briansmith/ring/blob/main/doc/ecdh.pdf
|
||||
pub static $NAME: ec::Curve = ec::Curve {
|
||||
public_key_len: 1 + (2 * (($bits + 7) / 8)),
|
||||
elem_scalar_seed_len: ($bits + 7) / 8,
|
||||
id: $id,
|
||||
check_private_key_bytes: $check_private_key_bytes,
|
||||
generate_private_key: $generate_private_key,
|
||||
public_from_private: $public_from_private,
|
||||
};
|
||||
|
||||
fn $check_private_key_bytes(
|
||||
bytes: &[u8],
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
debug_assert_eq!(bytes.len(), $bits / 8);
|
||||
ec::suite_b::private_key::check_scalar_big_endian_bytes($private_key_ops, bytes, cpu)
|
||||
}
|
||||
|
||||
fn $generate_private_key(
|
||||
rng: &dyn rand::SecureRandom,
|
||||
out: &mut [u8],
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
ec::suite_b::private_key::generate_private_scalar_bytes($private_key_ops, rng, out, cpu)
|
||||
}
|
||||
|
||||
fn $public_from_private(
|
||||
public_out: &mut [u8],
|
||||
private_key: &ec::Seed,
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
ec::suite_b::private_key::public_from_private(
|
||||
$private_key_ops,
|
||||
public_out,
|
||||
private_key,
|
||||
cpu,
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
suite_b_curve!(
|
||||
P256,
|
||||
256,
|
||||
&ec::suite_b::ops::p256::PRIVATE_KEY_OPS,
|
||||
ec::CurveID::P256,
|
||||
p256_check_private_key_bytes,
|
||||
p256_generate_private_key,
|
||||
p256_public_from_private
|
||||
);
|
||||
|
||||
suite_b_curve!(
|
||||
P384,
|
||||
384,
|
||||
&ec::suite_b::ops::p384::PRIVATE_KEY_OPS,
|
||||
ec::CurveID::P384,
|
||||
p384_check_private_key_bytes,
|
||||
p384_generate_private_key,
|
||||
p384_public_from_private
|
||||
);
|
||||
Vendored
+243
@@ -0,0 +1,243 @@
|
||||
// Copyright 2015-2017 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! ECDH key agreement using the P-256 and P-384 curves.
|
||||
|
||||
use super::{ops::*, private_key::*, public_key::*};
|
||||
use crate::{agreement, cpu, ec, error};
|
||||
|
||||
/// A key agreement algorithm.
|
||||
macro_rules! ecdh {
|
||||
( $NAME:ident, $curve:expr, $name_str:expr, $private_key_ops:expr,
|
||||
$public_key_ops:expr, $ecdh:ident ) => {
|
||||
#[doc = "ECDH using the NSA Suite B"]
|
||||
#[doc=$name_str]
|
||||
#[doc = "curve."]
|
||||
///
|
||||
/// Public keys are encoding in uncompressed form using the
|
||||
/// Octet-String-to-Elliptic-Curve-Point algorithm in
|
||||
/// [SEC 1: Elliptic Curve Cryptography, Version 2.0]. Public keys are
|
||||
/// validated during key agreement according to
|
||||
/// [NIST Special Publication 800-56A, revision 2] and Appendix B.3 of
|
||||
/// the NSA's [Suite B Implementer's Guide to NIST SP 800-56A].
|
||||
///
|
||||
/// [SEC 1: Elliptic Curve Cryptography, Version 2.0]:
|
||||
/// http://www.secg.org/sec1-v2.pdf
|
||||
/// [NIST Special Publication 800-56A, revision 2]:
|
||||
/// http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
|
||||
/// [Suite B Implementer's Guide to NIST SP 800-56A]:
|
||||
/// https://github.com/briansmith/ring/blob/main/doc/ecdh.pdf
|
||||
pub static $NAME: agreement::Algorithm = agreement::Algorithm {
|
||||
curve: $curve,
|
||||
ecdh: $ecdh,
|
||||
};
|
||||
|
||||
fn $ecdh(
|
||||
out: &mut [u8],
|
||||
my_private_key: &ec::Seed,
|
||||
peer_public_key: untrusted::Input,
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
ecdh(
|
||||
$private_key_ops,
|
||||
$public_key_ops,
|
||||
out,
|
||||
my_private_key,
|
||||
peer_public_key,
|
||||
cpu,
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
ecdh!(
|
||||
ECDH_P256,
|
||||
&ec::suite_b::curve::P256,
|
||||
"P-256 (secp256r1)",
|
||||
&p256::PRIVATE_KEY_OPS,
|
||||
&p256::PUBLIC_KEY_OPS,
|
||||
p256_ecdh
|
||||
);
|
||||
|
||||
ecdh!(
|
||||
ECDH_P384,
|
||||
&ec::suite_b::curve::P384,
|
||||
"P-384 (secp384r1)",
|
||||
&p384::PRIVATE_KEY_OPS,
|
||||
&p384::PUBLIC_KEY_OPS,
|
||||
p384_ecdh
|
||||
);
|
||||
|
||||
fn ecdh(
|
||||
private_key_ops: &PrivateKeyOps,
|
||||
public_key_ops: &PublicKeyOps,
|
||||
out: &mut [u8],
|
||||
my_private_key: &ec::Seed,
|
||||
peer_public_key: untrusted::Input,
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
// The NIST SP 800-56Ar2 steps are from section 5.7.1.2 Elliptic Curve
|
||||
// Cryptography Cofactor Diffie-Hellman (ECC CDH) Primitive.
|
||||
//
|
||||
// The "NSA Guide" steps are from section 3.1 of the NSA guide, "Ephemeral
|
||||
// Unified Model."
|
||||
|
||||
let q = &public_key_ops.common.elem_modulus(cpu);
|
||||
|
||||
// NSA Guide Step 1 is handled separately.
|
||||
|
||||
// NIST SP 800-56Ar2 5.6.2.2.2.
|
||||
// NSA Guide Step 2.
|
||||
//
|
||||
// `parse_uncompressed_point` verifies that the point is not at infinity
|
||||
// and that it is on the curve, using the Partial Public-Key Validation
|
||||
// Routine.
|
||||
let peer_public_key = parse_uncompressed_point(public_key_ops, q, peer_public_key)?;
|
||||
|
||||
// NIST SP 800-56Ar2 Step 1.
|
||||
// NSA Guide Step 3 (except point at infinity check).
|
||||
//
|
||||
// Note that the cofactor (h) is one since we only support prime-order
|
||||
// curves, so we can safely ignore the cofactor.
|
||||
//
|
||||
// It is impossible for the result to be the point at infinity because our
|
||||
// private key is in the range [1, n) and the curve has prime order and
|
||||
// `parse_uncompressed_point` verified that the peer public key is on the
|
||||
// curve and not at infinity. However, since the standards require the
|
||||
// check, we do it using `assert!`.
|
||||
//
|
||||
// NIST SP 800-56Ar2 defines "Destroy" thusly: "In this Recommendation, to
|
||||
// destroy is an action applied to a key or a piece of secret data. After
|
||||
// a key or a piece of secret data is destroyed, no information about its
|
||||
// value can be recovered." We interpret "destroy" somewhat liberally: we
|
||||
// assume that since we throw away the values to be destroyed, no
|
||||
// information about their values can be recovered. This doesn't meet the
|
||||
// NSA guide's explicit requirement to "zeroize" them though.
|
||||
// TODO: this only needs common scalar ops
|
||||
let n = &private_key_ops.common.scalar_modulus(cpu);
|
||||
let my_private_key = private_key_as_scalar(n, my_private_key);
|
||||
let product = private_key_ops.point_mul(&my_private_key, &peer_public_key, cpu);
|
||||
|
||||
// NIST SP 800-56Ar2 Steps 2, 3, 4, and 5.
|
||||
// NSA Guide Steps 3 (point at infinity check) and 4.
|
||||
//
|
||||
// Again, we have a pretty liberal interpretation of the NIST's spec's
|
||||
// "Destroy" that doesn't meet the NSA requirement to "zeroize."
|
||||
// `big_endian_affine_from_jacobian` verifies that the result is not at
|
||||
// infinity and also does an extra check to verify that the point is on
|
||||
// the curve.
|
||||
big_endian_affine_from_jacobian(private_key_ops, q, out, None, &product)
|
||||
|
||||
// NSA Guide Step 5 & 6 are deferred to the caller. Again, we have a
|
||||
// pretty liberal interpretation of the NIST's spec's "Destroy" that
|
||||
// doesn't meet the NSA requirement to "zeroize."
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::ops;
|
||||
use crate::testutil as test;
|
||||
use crate::{agreement, ec, limb};
|
||||
|
||||
static SUPPORTED_SUITE_B_ALGS: [(&str, &agreement::Algorithm, &ec::Curve, &ops::CommonOps); 2] = [
|
||||
(
|
||||
"P-256",
|
||||
&agreement::ECDH_P256,
|
||||
&super::super::curve::P256,
|
||||
&ops::p256::COMMON_OPS,
|
||||
),
|
||||
(
|
||||
"P-384",
|
||||
&agreement::ECDH_P384,
|
||||
&super::super::curve::P384,
|
||||
&ops::p384::COMMON_OPS,
|
||||
),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn test_agreement_suite_b_ecdh_generate() {
|
||||
// Generates a string of bytes 0x00...00, which will always result in
|
||||
// a scalar value of zero.
|
||||
let random_00 = test::rand::FixedByteRandom { byte: 0x00 };
|
||||
|
||||
// Generates a string of bytes 0xFF...FF, which will be larger than the
|
||||
// group order of any curve that is supported.
|
||||
let random_ff = test::rand::FixedByteRandom { byte: 0xff };
|
||||
|
||||
for &(_, alg, curve, ops) in SUPPORTED_SUITE_B_ALGS.iter() {
|
||||
// Test that the private key value zero is rejected and that
|
||||
// `generate` gives up after a while of only getting zeros.
|
||||
assert!(agreement::EphemeralPrivateKey::generate(alg, &random_00).is_err());
|
||||
|
||||
// Test that the private key value larger than the group order is
|
||||
// rejected and that `generate` gives up after a while of only
|
||||
// getting values larger than the group order.
|
||||
assert!(agreement::EphemeralPrivateKey::generate(alg, &random_ff).is_err());
|
||||
|
||||
// Test that a private key value exactly equal to the group order
|
||||
// is rejected and that `generate` gives up after a while of only
|
||||
// getting that value from the PRNG.
|
||||
let mut n_bytes = [0u8; ec::SCALAR_MAX_BYTES];
|
||||
let num_bytes = curve.elem_scalar_seed_len;
|
||||
limb::big_endian_from_limbs(ops.n_limbs(), &mut n_bytes[..num_bytes]);
|
||||
{
|
||||
let n_bytes = &mut n_bytes[..num_bytes];
|
||||
let rng = test::rand::FixedSliceRandom { bytes: n_bytes };
|
||||
assert!(agreement::EphemeralPrivateKey::generate(alg, &rng).is_err());
|
||||
}
|
||||
|
||||
// Test that a private key value exactly equal to the group order
|
||||
// minus 1 is accepted.
|
||||
let mut n_minus_1_bytes = n_bytes;
|
||||
{
|
||||
let n_minus_1_bytes = &mut n_minus_1_bytes[..num_bytes];
|
||||
n_minus_1_bytes[num_bytes - 1] -= 1;
|
||||
let rng = test::rand::FixedSliceRandom {
|
||||
bytes: n_minus_1_bytes,
|
||||
};
|
||||
let key = agreement::EphemeralPrivateKey::generate(alg, &rng).unwrap();
|
||||
assert_eq!(n_minus_1_bytes, key.bytes_for_test());
|
||||
}
|
||||
|
||||
// Test that n + 1 also fails.
|
||||
let mut n_plus_1_bytes = n_bytes;
|
||||
{
|
||||
let n_plus_1_bytes = &mut n_plus_1_bytes[..num_bytes];
|
||||
n_plus_1_bytes[num_bytes - 1] += 1;
|
||||
let rng = test::rand::FixedSliceRandom {
|
||||
bytes: n_plus_1_bytes,
|
||||
};
|
||||
assert!(agreement::EphemeralPrivateKey::generate(alg, &rng).is_err());
|
||||
}
|
||||
|
||||
// Test recovery from initial RNG failure. The first value will be
|
||||
// n, then n + 1, then zero, the next value will be n - 1, which
|
||||
// will be accepted.
|
||||
{
|
||||
let bytes = [
|
||||
&n_bytes[..num_bytes],
|
||||
&n_plus_1_bytes[..num_bytes],
|
||||
&[0u8; ec::SCALAR_MAX_BYTES][..num_bytes],
|
||||
&n_minus_1_bytes[..num_bytes],
|
||||
];
|
||||
let rng = test::rand::FixedSliceSequenceRandom {
|
||||
bytes: &bytes,
|
||||
current: core::cell::UnsafeCell::new(0),
|
||||
};
|
||||
let key = agreement::EphemeralPrivateKey::generate(alg, &rng).unwrap();
|
||||
assert_eq!(&n_minus_1_bytes[..num_bytes], key.bytes_for_test());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
mod digest_scalar;
|
||||
pub mod signing;
|
||||
pub mod verification;
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
// Copyright 2015-2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! ECDSA Signatures using the P-256 and P-384 curves.
|
||||
|
||||
use crate::{digest, ec::suite_b::ops::*};
|
||||
|
||||
/// Calculate the digest of `msg` using the digest algorithm `digest_alg`. Then
|
||||
/// convert the digest to a scalar in the range [0, n) as described in
|
||||
/// NIST's FIPS 186-4 Section 4.2. Note that this is one of the few cases where
|
||||
/// a `Scalar` is allowed to have the value zero.
|
||||
///
|
||||
/// NIST's FIPS 186-4 4.2 says "When the length of the output of the hash
|
||||
/// function is greater than N (i.e., the bit length of q), then the leftmost N
|
||||
/// bits of the hash function output block shall be used in any calculation
|
||||
/// using the hash function output during the generation or verification of a
|
||||
/// digital signature."
|
||||
///
|
||||
/// "Leftmost N bits" means "N most significant bits" because we interpret the
|
||||
/// digest as a bit-endian encoded integer.
|
||||
///
|
||||
/// The NSA guide instead vaguely suggests that we should convert the digest
|
||||
/// value to an integer and then reduce it mod `n`. However, real-world
|
||||
/// implementations (e.g. `digest_to_bn` in OpenSSL and `hashToInt` in Go) do
|
||||
/// what FIPS 186-4 says to do, not what the NSA guide suggests.
|
||||
///
|
||||
/// Why shifting the value right by at most one bit is sufficient: P-256's `n`
|
||||
/// has its 256th bit set; i.e. 2**255 < n < 2**256. Once we've truncated the
|
||||
/// digest to 256 bits and converted it to an integer, it will have a value
|
||||
/// less than 2**256. If the value is larger than `n` then shifting it one bit
|
||||
/// right will give a value less than 2**255, which is less than `n`. The
|
||||
/// analogous argument applies for P-384. However, it does *not* apply in
|
||||
/// general; for example, it doesn't apply to P-521.
|
||||
pub(super) fn digest_scalar(n: &Modulus<N>, msg: digest::Digest) -> Scalar {
|
||||
digest_scalar_(n, msg.as_ref())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn digest_bytes_scalar(n: &Modulus<N>, digest: &[u8]) -> Scalar {
|
||||
digest_scalar_(n, digest)
|
||||
}
|
||||
|
||||
// This is a separate function solely so that we can test specific digest
|
||||
// values like all-zero values and values larger than `n`.
|
||||
fn digest_scalar_(n: &Modulus<N>, digest: &[u8]) -> Scalar {
|
||||
let len = n.bytes_len();
|
||||
let digest = if digest.len() > len {
|
||||
&digest[..len]
|
||||
} else {
|
||||
digest
|
||||
};
|
||||
|
||||
scalar_parse_big_endian_partially_reduced_variable_consttime(n, untrusted::Input::from(digest))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::digest_bytes_scalar;
|
||||
use crate::testutil as test;
|
||||
use crate::{cpu, digest, ec::suite_b::ops::*, limb};
|
||||
|
||||
#[test]
|
||||
fn test() {
|
||||
let cpu = cpu::features();
|
||||
test::run(
|
||||
test_vector_file!("ecdsa_digest_scalar_tests.txt"),
|
||||
|section, test_case| {
|
||||
assert_eq!(section, "");
|
||||
|
||||
let curve_name = test_case.consume_string("Curve");
|
||||
let digest_name = test_case.consume_string("Digest");
|
||||
let input = test_case.consume_bytes("Input");
|
||||
let output = test_case.consume_bytes("Output");
|
||||
|
||||
let (ops, digest_alg) = match (curve_name.as_str(), digest_name.as_str()) {
|
||||
("P-256", "SHA256") => (&p256::PUBLIC_SCALAR_OPS, &digest::SHA256),
|
||||
("P-256", "SHA384") => (&p256::PUBLIC_SCALAR_OPS, &digest::SHA384),
|
||||
("P-384", "SHA256") => (&p384::PUBLIC_SCALAR_OPS, &digest::SHA256),
|
||||
("P-384", "SHA384") => (&p384::PUBLIC_SCALAR_OPS, &digest::SHA384),
|
||||
_ => {
|
||||
panic!("Unsupported curve+digest: {}+{}", curve_name, digest_name);
|
||||
}
|
||||
};
|
||||
let n = &ops.scalar_ops.scalar_modulus(cpu);
|
||||
|
||||
assert_eq!(input.len(), digest_alg.output_len());
|
||||
assert_eq!(output.len(), ops.scalar_ops.scalar_bytes_len());
|
||||
assert_eq!(output.len(), n.bytes_len());
|
||||
|
||||
let expected = scalar_parse_big_endian_variable(
|
||||
n,
|
||||
limb::AllowZero::Yes,
|
||||
untrusted::Input::from(&output),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let actual = digest_bytes_scalar(n, &input);
|
||||
assert_eq!(
|
||||
ops.scalar_ops.leak_limbs(&actual),
|
||||
ops.scalar_ops.leak_limbs(&expected)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
+615
@@ -0,0 +1,615 @@
|
||||
// Copyright 2015-2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! ECDSA Signatures using the P-256 and P-384 curves.
|
||||
|
||||
use super::digest_scalar::digest_scalar;
|
||||
use crate::{
|
||||
arithmetic::montgomery::*,
|
||||
cpu, digest,
|
||||
ec::{
|
||||
self,
|
||||
suite_b::{ops::*, private_key},
|
||||
},
|
||||
error,
|
||||
io::der,
|
||||
limb, pkcs8, rand, sealed, signature,
|
||||
};
|
||||
/// An ECDSA signing algorithm.
|
||||
pub struct EcdsaSigningAlgorithm {
|
||||
curve: &'static ec::Curve,
|
||||
private_scalar_ops: &'static PrivateScalarOps,
|
||||
private_key_ops: &'static PrivateKeyOps,
|
||||
digest_alg: &'static digest::Algorithm,
|
||||
pkcs8_template: &'static pkcs8::Template,
|
||||
format_rs: fn(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize,
|
||||
id: AlgorithmID,
|
||||
}
|
||||
|
||||
#[derive(Debug, Eq, PartialEq)]
|
||||
enum AlgorithmID {
|
||||
ECDSA_P256_SHA256_FIXED_SIGNING,
|
||||
ECDSA_P384_SHA384_FIXED_SIGNING,
|
||||
ECDSA_P256_SHA256_ASN1_SIGNING,
|
||||
ECDSA_P384_SHA384_ASN1_SIGNING,
|
||||
}
|
||||
|
||||
derive_debug_via_id!(EcdsaSigningAlgorithm);
|
||||
|
||||
impl PartialEq for EcdsaSigningAlgorithm {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.id == other.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for EcdsaSigningAlgorithm {}
|
||||
|
||||
impl sealed::Sealed for EcdsaSigningAlgorithm {}
|
||||
|
||||
/// An ECDSA key pair, used for signing.
|
||||
pub struct EcdsaKeyPair {
|
||||
d: Scalar<R>,
|
||||
nonce_key: NonceRandomKey,
|
||||
alg: &'static EcdsaSigningAlgorithm,
|
||||
public_key: PublicKey,
|
||||
}
|
||||
|
||||
derive_debug_via_field!(EcdsaKeyPair, stringify!(EcdsaKeyPair), public_key);
|
||||
|
||||
impl EcdsaKeyPair {
|
||||
/// Generates a new key pair and returns the key pair serialized as a
|
||||
/// PKCS#8 document.
|
||||
///
|
||||
/// The PKCS#8 document will be a v1 `OneAsymmetricKey` with the public key
|
||||
/// included in the `ECPrivateKey` structure, as described in
|
||||
/// [RFC 5958 Section 2] and [RFC 5915]. The `ECPrivateKey` structure will
|
||||
/// not have a `parameters` field so the generated key is compatible with
|
||||
/// PKCS#11.
|
||||
///
|
||||
/// [RFC 5915]: https://tools.ietf.org/html/rfc5915
|
||||
/// [RFC 5958 Section 2]: https://tools.ietf.org/html/rfc5958#section-2
|
||||
pub fn generate_pkcs8(
|
||||
alg: &'static EcdsaSigningAlgorithm,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
) -> Result<pkcs8::Document, error::Unspecified> {
|
||||
let cpu = cpu::features();
|
||||
let private_key = ec::Seed::generate(alg.curve, rng, cpu)?;
|
||||
let public_key = private_key.compute_public_key(cpu)?;
|
||||
Ok(pkcs8::wrap_key(
|
||||
alg.pkcs8_template,
|
||||
private_key.bytes_less_safe(),
|
||||
public_key.as_ref(),
|
||||
))
|
||||
}
|
||||
|
||||
/// Constructs an ECDSA key pair by parsing an unencrypted PKCS#8 v1
|
||||
/// id-ecPublicKey `ECPrivateKey` key.
|
||||
///
|
||||
/// The input must be in PKCS#8 v1 format. It must contain the public key in
|
||||
/// the `ECPrivateKey` structure; `from_pkcs8()` will verify that the public
|
||||
/// key and the private key are consistent with each other. The algorithm
|
||||
/// identifier must identify the curve by name; it must not use an
|
||||
/// "explicit" encoding of the curve. The `parameters` field of the
|
||||
/// `ECPrivateKey`, if present, must be the same named curve that is in the
|
||||
/// algorithm identifier in the PKCS#8 header.
|
||||
pub fn from_pkcs8(
|
||||
alg: &'static EcdsaSigningAlgorithm,
|
||||
pkcs8: &[u8],
|
||||
rng: &dyn rand::SecureRandom,
|
||||
) -> Result<Self, error::KeyRejected> {
|
||||
let key_pair = ec::suite_b::key_pair_from_pkcs8(
|
||||
alg.curve,
|
||||
alg.pkcs8_template,
|
||||
untrusted::Input::from(pkcs8),
|
||||
cpu::features(),
|
||||
)?;
|
||||
Self::new(alg, key_pair, rng)
|
||||
}
|
||||
|
||||
/// Constructs an ECDSA key pair from the private key and public key bytes
|
||||
///
|
||||
/// The private key must encoded as a big-endian fixed-length integer. For
|
||||
/// example, a P-256 private key must be 32 bytes prefixed with leading
|
||||
/// zeros as needed.
|
||||
///
|
||||
/// The public key is encoding in uncompressed form using the
|
||||
/// Octet-String-to-Elliptic-Curve-Point algorithm in
|
||||
/// [SEC 1: Elliptic Curve Cryptography, Version 2.0].
|
||||
///
|
||||
/// This is intended for use by code that deserializes key pairs. It is
|
||||
/// recommended to use `EcdsaKeyPair::from_pkcs8()` (with a PKCS#8-encoded
|
||||
/// key) instead.
|
||||
///
|
||||
/// [SEC 1: Elliptic Curve Cryptography, Version 2.0]:
|
||||
/// http://www.secg.org/sec1-v2.pdf
|
||||
pub fn from_private_key_and_public_key(
|
||||
alg: &'static EcdsaSigningAlgorithm,
|
||||
private_key: &[u8],
|
||||
public_key: &[u8],
|
||||
rng: &dyn rand::SecureRandom,
|
||||
) -> Result<Self, error::KeyRejected> {
|
||||
let key_pair = ec::suite_b::key_pair_from_bytes(
|
||||
alg.curve,
|
||||
untrusted::Input::from(private_key),
|
||||
untrusted::Input::from(public_key),
|
||||
cpu::features(),
|
||||
)?;
|
||||
Self::new(alg, key_pair, rng)
|
||||
}
|
||||
|
||||
fn new(
|
||||
alg: &'static EcdsaSigningAlgorithm,
|
||||
key_pair: ec::KeyPair,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
) -> Result<Self, error::KeyRejected> {
|
||||
let cpu = cpu::features();
|
||||
|
||||
let (seed, public_key) = key_pair.split();
|
||||
let n = &alg.private_scalar_ops.scalar_ops.scalar_modulus(cpu);
|
||||
let d = private_key::private_key_as_scalar(n, &seed);
|
||||
let d = alg.private_scalar_ops.to_mont(&d, cpu);
|
||||
|
||||
let nonce_key = NonceRandomKey::new(alg, &seed, rng)?;
|
||||
Ok(Self {
|
||||
d,
|
||||
nonce_key,
|
||||
alg,
|
||||
public_key: PublicKey(public_key),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the signature of the `message` using a random nonce generated by `rng`.
|
||||
pub fn sign(
|
||||
&self,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
message: &[u8],
|
||||
) -> Result<signature::Signature, error::Unspecified> {
|
||||
let cpu = cpu::features();
|
||||
|
||||
// Step 4 (out of order).
|
||||
let h = digest::digest(self.alg.digest_alg, message);
|
||||
|
||||
// Incorporate `h` into the nonce to hedge against faulty RNGs. (This
|
||||
// is not an approved random number generator that is mandated in
|
||||
// the spec.)
|
||||
let nonce_rng = NonceRandom {
|
||||
key: &self.nonce_key,
|
||||
message_digest: &h,
|
||||
rng,
|
||||
};
|
||||
|
||||
self.sign_digest(h, &nonce_rng, cpu)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn sign_with_fixed_nonce_during_test(
|
||||
&self,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
message: &[u8],
|
||||
) -> Result<signature::Signature, error::Unspecified> {
|
||||
// Step 4 (out of order).
|
||||
let h = digest::digest(self.alg.digest_alg, message);
|
||||
|
||||
self.sign_digest(h, rng, cpu::features())
|
||||
}
|
||||
|
||||
/// Returns the signature of message digest `h` using a "random" nonce
|
||||
/// generated by `rng`.
|
||||
fn sign_digest(
|
||||
&self,
|
||||
h: digest::Digest,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
cpu: cpu::Features,
|
||||
) -> Result<signature::Signature, error::Unspecified> {
|
||||
// NSA Suite B Implementer's Guide to ECDSA Section 3.4.1: ECDSA
|
||||
// Signature Generation.
|
||||
|
||||
// NSA Guide Prerequisites:
|
||||
//
|
||||
// Prior to generating an ECDSA signature, the signatory shall
|
||||
// obtain:
|
||||
//
|
||||
// 1. an authentic copy of the domain parameters,
|
||||
// 2. a digital signature key pair (d,Q), either generated by a
|
||||
// method from Appendix A.1, or obtained from a trusted third
|
||||
// party,
|
||||
// 3. assurance of the validity of the public key Q (see Appendix
|
||||
// A.3), and
|
||||
// 4. assurance that he/she/it actually possesses the associated
|
||||
// private key d (see [SP800-89] Section 6).
|
||||
//
|
||||
// The domain parameters are hard-coded into the source code.
|
||||
// `EcdsaKeyPair::generate_pkcs8()` can be used to meet the second
|
||||
// requirement; otherwise, it is up to the user to ensure the key pair
|
||||
// was obtained from a trusted private key. The constructors for
|
||||
// `EcdsaKeyPair` ensure that #3 and #4 are met subject to the caveats
|
||||
// in SP800-89 Section 6.
|
||||
|
||||
let ops = self.alg.private_scalar_ops;
|
||||
let scalar_ops = ops.scalar_ops;
|
||||
let cops = scalar_ops.common;
|
||||
let private_key_ops = self.alg.private_key_ops;
|
||||
let q = &cops.elem_modulus(cpu);
|
||||
let n = &scalar_ops.scalar_modulus(cpu);
|
||||
|
||||
for _ in 0..100 {
|
||||
// XXX: iteration conut?
|
||||
// Step 1.
|
||||
let k = private_key::random_scalar(self.alg.private_key_ops, n, rng)?;
|
||||
let k_inv = ops.scalar_inv_to_mont(&k, cpu);
|
||||
|
||||
// Step 2.
|
||||
let r = private_key_ops.point_mul_base(&k, cpu);
|
||||
|
||||
// Step 3.
|
||||
let r = {
|
||||
let (x, _) = private_key::affine_from_jacobian(private_key_ops, q, &r)?;
|
||||
let x = q.elem_unencoded(&x);
|
||||
n.elem_reduced_to_scalar(&x)
|
||||
};
|
||||
if n.is_zero(&r) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Step 4 is done by the caller.
|
||||
|
||||
// Step 5.
|
||||
let e = digest_scalar(n, h);
|
||||
|
||||
// Step 6.
|
||||
let s = {
|
||||
let mut e_plus_dr = scalar_ops.scalar_product(&self.d, &r, cpu);
|
||||
n.add_assign(&mut e_plus_dr, &e);
|
||||
scalar_ops.scalar_product(&k_inv, &e_plus_dr, cpu)
|
||||
};
|
||||
if n.is_zero(&s) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Step 7 with encoding.
|
||||
return Ok(signature::Signature::new(|sig_bytes| {
|
||||
(self.alg.format_rs)(scalar_ops, &r, &s, sig_bytes)
|
||||
}));
|
||||
}
|
||||
|
||||
Err(error::Unspecified)
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates an ECDSA nonce in a way that attempts to protect against a faulty
|
||||
/// `SecureRandom`.
|
||||
struct NonceRandom<'a> {
|
||||
key: &'a NonceRandomKey,
|
||||
message_digest: &'a digest::Digest,
|
||||
rng: &'a dyn rand::SecureRandom,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for NonceRandom<'_> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("NonceRandom").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl rand::sealed::SecureRandom for NonceRandom<'_> {
|
||||
fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
|
||||
// Use the same digest algorithm that will be used to digest the
|
||||
// message. The digest algorithm's output is exactly the right size;
|
||||
// this is checked below.
|
||||
//
|
||||
// XXX(perf): The single iteration will require two digest block
|
||||
// operations because the amount of data digested is larger than one
|
||||
// block.
|
||||
let digest_alg = self.key.0.algorithm();
|
||||
let mut ctx = digest::Context::new(digest_alg);
|
||||
|
||||
// Digest the randomized digest of the private key.
|
||||
let key = self.key.0.as_ref();
|
||||
ctx.update(key);
|
||||
|
||||
// The random value is digested between the key and the message so that
|
||||
// the key and the message are not directly digested in the same digest
|
||||
// block.
|
||||
assert!(key.len() <= digest_alg.block_len() / 2);
|
||||
{
|
||||
let mut rand = [0u8; digest::MAX_BLOCK_LEN];
|
||||
let rand = &mut rand[..digest_alg.block_len() - key.len()];
|
||||
assert!(rand.len() >= dest.len());
|
||||
self.rng.fill(rand)?;
|
||||
ctx.update(rand);
|
||||
}
|
||||
|
||||
ctx.update(self.message_digest.as_ref());
|
||||
|
||||
let nonce = ctx.finish();
|
||||
|
||||
// `copy_from_slice()` panics if the lengths differ, so we don't have
|
||||
// to separately assert that the lengths are the same.
|
||||
dest.copy_from_slice(nonce.as_ref());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl sealed::Sealed for NonceRandom<'_> {}
|
||||
|
||||
struct NonceRandomKey(digest::Digest);
|
||||
|
||||
impl NonceRandomKey {
|
||||
fn new(
|
||||
alg: &EcdsaSigningAlgorithm,
|
||||
seed: &ec::Seed,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
) -> Result<Self, error::KeyRejected> {
|
||||
let mut rand = [0; digest::MAX_OUTPUT_LEN];
|
||||
let rand = &mut rand[0..alg.curve.elem_scalar_seed_len];
|
||||
|
||||
// XXX: `KeyRejected` isn't the right way to model failure of the RNG,
|
||||
// but to fix that we'd need to break the API by changing the result type.
|
||||
// TODO: Fix the API in the next breaking release.
|
||||
rng.fill(rand)
|
||||
.map_err(|error::Unspecified| error::KeyRejected::rng_failed())?;
|
||||
|
||||
let mut ctx = digest::Context::new(alg.digest_alg);
|
||||
ctx.update(rand);
|
||||
ctx.update(seed.bytes_less_safe());
|
||||
Ok(Self(ctx.finish()))
|
||||
}
|
||||
}
|
||||
|
||||
impl signature::KeyPair for EcdsaKeyPair {
|
||||
type PublicKey = PublicKey;
|
||||
|
||||
fn public_key(&self) -> &Self::PublicKey {
|
||||
&self.public_key
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PublicKey(ec::PublicKey);
|
||||
|
||||
derive_debug_self_as_ref_hex_bytes!(PublicKey);
|
||||
|
||||
impl AsRef<[u8]> for PublicKey {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
fn format_rs_fixed(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize {
|
||||
let scalar_len = ops.scalar_bytes_len();
|
||||
|
||||
let (r_out, rest) = out.split_at_mut(scalar_len);
|
||||
limb::big_endian_from_limbs(ops.leak_limbs(r), r_out);
|
||||
|
||||
let (s_out, _) = rest.split_at_mut(scalar_len);
|
||||
limb::big_endian_from_limbs(ops.leak_limbs(s), s_out);
|
||||
|
||||
2 * scalar_len
|
||||
}
|
||||
|
||||
fn format_rs_asn1(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize {
|
||||
// This assumes `a` is not zero since neither `r` or `s` is allowed to be
|
||||
// zero.
|
||||
fn format_integer_tlv(ops: &ScalarOps, a: &Scalar, out: &mut [u8]) -> usize {
|
||||
let mut fixed = [0u8; ec::SCALAR_MAX_BYTES + 1];
|
||||
let fixed = &mut fixed[..(ops.scalar_bytes_len() + 1)];
|
||||
limb::big_endian_from_limbs(ops.leak_limbs(a), &mut fixed[1..]);
|
||||
|
||||
// Since `a_fixed_out` is an extra byte long, it is guaranteed to start
|
||||
// with a zero.
|
||||
debug_assert_eq!(fixed[0], 0);
|
||||
|
||||
// There must be at least one non-zero byte since `a` isn't zero.
|
||||
let first_index = fixed.iter().position(|b| *b != 0).unwrap();
|
||||
|
||||
// If the first byte has its high bit set, it needs to be prefixed with 0x00.
|
||||
let first_index = if fixed[first_index] & 0x80 != 0 {
|
||||
first_index - 1
|
||||
} else {
|
||||
first_index
|
||||
};
|
||||
let value = &fixed[first_index..];
|
||||
|
||||
out[0] = der::Tag::Integer.into();
|
||||
|
||||
// Lengths less than 128 are encoded in one byte.
|
||||
assert!(value.len() < 128);
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
{
|
||||
out[1] = value.len() as u8;
|
||||
}
|
||||
|
||||
out[2..][..value.len()].copy_from_slice(value);
|
||||
|
||||
2 + value.len()
|
||||
}
|
||||
|
||||
out[0] = der::Tag::Sequence.into();
|
||||
let r_tlv_len = format_integer_tlv(ops, r, &mut out[2..]);
|
||||
let s_tlv_len = format_integer_tlv(ops, s, &mut out[2..][r_tlv_len..]);
|
||||
|
||||
// Lengths less than 128 are encoded in one byte.
|
||||
let value_len = r_tlv_len + s_tlv_len;
|
||||
assert!(value_len < 128);
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
{
|
||||
out[1] = value_len as u8;
|
||||
}
|
||||
|
||||
2 + value_len
|
||||
}
|
||||
|
||||
/// Signing of fixed-length (PKCS#11 style) ECDSA signatures using the
|
||||
/// P-256 curve and SHA-256.
|
||||
///
|
||||
/// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P256_SHA256_FIXED_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
|
||||
curve: &ec::suite_b::curve::P256,
|
||||
private_scalar_ops: &p256::PRIVATE_SCALAR_OPS,
|
||||
private_key_ops: &p256::PRIVATE_KEY_OPS,
|
||||
digest_alg: &digest::SHA256,
|
||||
pkcs8_template: &EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE,
|
||||
format_rs: format_rs_fixed,
|
||||
id: AlgorithmID::ECDSA_P256_SHA256_FIXED_SIGNING,
|
||||
};
|
||||
|
||||
/// Signing of fixed-length (PKCS#11 style) ECDSA signatures using the
|
||||
/// P-384 curve and SHA-384.
|
||||
///
|
||||
/// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P384_SHA384_FIXED_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
|
||||
curve: &ec::suite_b::curve::P384,
|
||||
private_scalar_ops: &p384::PRIVATE_SCALAR_OPS,
|
||||
private_key_ops: &p384::PRIVATE_KEY_OPS,
|
||||
digest_alg: &digest::SHA384,
|
||||
pkcs8_template: &EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE,
|
||||
format_rs: format_rs_fixed,
|
||||
id: AlgorithmID::ECDSA_P384_SHA384_FIXED_SIGNING,
|
||||
};
|
||||
|
||||
/// Signing of ASN.1 DER-encoded ECDSA signatures using the P-256 curve and
|
||||
/// SHA-256.
|
||||
///
|
||||
/// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P256_SHA256_ASN1_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
|
||||
curve: &ec::suite_b::curve::P256,
|
||||
private_scalar_ops: &p256::PRIVATE_SCALAR_OPS,
|
||||
private_key_ops: &p256::PRIVATE_KEY_OPS,
|
||||
digest_alg: &digest::SHA256,
|
||||
pkcs8_template: &EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE,
|
||||
format_rs: format_rs_asn1,
|
||||
id: AlgorithmID::ECDSA_P256_SHA256_ASN1_SIGNING,
|
||||
};
|
||||
|
||||
/// Signing of ASN.1 DER-encoded ECDSA signatures using the P-384 curve and
|
||||
/// SHA-384.
|
||||
///
|
||||
/// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P384_SHA384_ASN1_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
|
||||
curve: &ec::suite_b::curve::P384,
|
||||
private_scalar_ops: &p384::PRIVATE_SCALAR_OPS,
|
||||
private_key_ops: &p384::PRIVATE_KEY_OPS,
|
||||
digest_alg: &digest::SHA384,
|
||||
pkcs8_template: &EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE,
|
||||
format_rs: format_rs_asn1,
|
||||
id: AlgorithmID::ECDSA_P384_SHA384_ASN1_SIGNING,
|
||||
};
|
||||
|
||||
static EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE: pkcs8::Template = pkcs8::Template {
|
||||
bytes: include_bytes!("ecPublicKey_p256_pkcs8_v1_template.der"),
|
||||
alg_id_range: core::ops::Range { start: 8, end: 27 },
|
||||
curve_id_index: 9,
|
||||
private_key_index: 0x24,
|
||||
};
|
||||
|
||||
static EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE: pkcs8::Template = pkcs8::Template {
|
||||
bytes: include_bytes!("ecPublicKey_p384_pkcs8_v1_template.der"),
|
||||
alg_id_range: core::ops::Range { start: 8, end: 24 },
|
||||
curve_id_index: 9,
|
||||
private_key_index: 0x23,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::testutil as test;
|
||||
use crate::{rand, signature};
|
||||
|
||||
#[test]
|
||||
fn signature_ecdsa_sign_fixed_test() {
|
||||
let rng = rand::SystemRandom::new();
|
||||
|
||||
test::run(
|
||||
test_vector_file!("ecdsa_sign_fixed_tests.txt"),
|
||||
|section, test_case| {
|
||||
assert_eq!(section, "");
|
||||
|
||||
let curve_name = test_case.consume_string("Curve");
|
||||
let digest_name = test_case.consume_string("Digest");
|
||||
let msg = test_case.consume_bytes("Msg");
|
||||
let d = test_case.consume_bytes("d");
|
||||
let q = test_case.consume_bytes("Q");
|
||||
let k = test_case.consume_bytes("k");
|
||||
|
||||
let expected_result = test_case.consume_bytes("Sig");
|
||||
|
||||
let alg = match (curve_name.as_str(), digest_name.as_str()) {
|
||||
("P-256", "SHA256") => &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
|
||||
("P-384", "SHA384") => &signature::ECDSA_P384_SHA384_FIXED_SIGNING,
|
||||
_ => {
|
||||
panic!("Unsupported curve+digest: {}+{}", curve_name, digest_name);
|
||||
}
|
||||
};
|
||||
|
||||
let private_key =
|
||||
signature::EcdsaKeyPair::from_private_key_and_public_key(alg, &d, &q, &rng)
|
||||
.unwrap();
|
||||
let rng = test::rand::FixedSliceRandom { bytes: &k };
|
||||
|
||||
let actual_result = private_key
|
||||
.sign_with_fixed_nonce_during_test(&rng, &msg)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(actual_result.as_ref(), &expected_result[..]);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signature_ecdsa_sign_asn1_test() {
|
||||
let rng = rand::SystemRandom::new();
|
||||
|
||||
test::run(
|
||||
test_vector_file!("ecdsa_sign_asn1_tests.txt"),
|
||||
|section, test_case| {
|
||||
assert_eq!(section, "");
|
||||
|
||||
let curve_name = test_case.consume_string("Curve");
|
||||
let digest_name = test_case.consume_string("Digest");
|
||||
let msg = test_case.consume_bytes("Msg");
|
||||
let d = test_case.consume_bytes("d");
|
||||
let q = test_case.consume_bytes("Q");
|
||||
let k = test_case.consume_bytes("k");
|
||||
|
||||
let expected_result = test_case.consume_bytes("Sig");
|
||||
|
||||
let alg = match (curve_name.as_str(), digest_name.as_str()) {
|
||||
("P-256", "SHA256") => &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
|
||||
("P-384", "SHA384") => &signature::ECDSA_P384_SHA384_ASN1_SIGNING,
|
||||
_ => {
|
||||
panic!("Unsupported curve+digest: {}+{}", curve_name, digest_name);
|
||||
}
|
||||
};
|
||||
|
||||
let private_key =
|
||||
signature::EcdsaKeyPair::from_private_key_and_public_key(alg, &d, &q, &rng)
|
||||
.unwrap();
|
||||
let rng = test::rand::FixedSliceRandom { bytes: &k };
|
||||
|
||||
let actual_result = private_key
|
||||
.sign_with_fixed_nonce_during_test(&rng, &msg)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(actual_result.as_ref(), &expected_result[..]);
|
||||
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
// Copyright 2015-2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! ECDSA Signatures using the P-256 and P-384 curves.
|
||||
|
||||
use super::digest_scalar::digest_scalar;
|
||||
use crate::{
|
||||
arithmetic::montgomery::*,
|
||||
cpu, digest,
|
||||
ec::suite_b::{ops::*, public_key::*, verify_jacobian_point_is_on_the_curve},
|
||||
error,
|
||||
io::der,
|
||||
limb, sealed, signature,
|
||||
};
|
||||
|
||||
/// An ECDSA verification algorithm.
|
||||
pub struct EcdsaVerificationAlgorithm {
|
||||
ops: &'static PublicScalarOps,
|
||||
digest_alg: &'static digest::Algorithm,
|
||||
split_rs:
|
||||
for<'a> fn(
|
||||
ops: &'static ScalarOps,
|
||||
input: &mut untrusted::Reader<'a>,
|
||||
)
|
||||
-> Result<(untrusted::Input<'a>, untrusted::Input<'a>), error::Unspecified>,
|
||||
id: AlgorithmID,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum AlgorithmID {
|
||||
ECDSA_P256_SHA256_ASN1,
|
||||
ECDSA_P256_SHA256_FIXED,
|
||||
ECDSA_P256_SHA384_ASN1,
|
||||
ECDSA_P384_SHA256_ASN1,
|
||||
ECDSA_P384_SHA384_ASN1,
|
||||
ECDSA_P384_SHA384_FIXED,
|
||||
}
|
||||
|
||||
derive_debug_via_id!(EcdsaVerificationAlgorithm);
|
||||
|
||||
impl signature::VerificationAlgorithm for EcdsaVerificationAlgorithm {
|
||||
fn verify(
|
||||
&self,
|
||||
public_key: untrusted::Input,
|
||||
msg: untrusted::Input,
|
||||
signature: untrusted::Input,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let cpu = cpu::features();
|
||||
let e = {
|
||||
// NSA Guide Step 2: "Use the selected hash function to compute H =
|
||||
// Hash(M)."
|
||||
let h = digest::digest(self.digest_alg, msg.as_slice_less_safe());
|
||||
|
||||
// NSA Guide Step 3: "Convert the bit string H to an integer e as
|
||||
// described in Appendix B.2."
|
||||
let n = &self.ops.scalar_ops.scalar_modulus(cpu);
|
||||
digest_scalar(n, h)
|
||||
};
|
||||
|
||||
self.verify_digest(public_key, e, signature)
|
||||
}
|
||||
}
|
||||
|
||||
impl EcdsaVerificationAlgorithm {
|
||||
/// This is intentionally not public.
|
||||
fn verify_digest(
|
||||
&self,
|
||||
public_key: untrusted::Input,
|
||||
e: Scalar,
|
||||
signature: untrusted::Input,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let cpu = cpu::features();
|
||||
|
||||
// NSA Suite B Implementer's Guide to ECDSA Section 3.4.2.
|
||||
|
||||
let public_key_ops = self.ops.public_key_ops;
|
||||
let scalar_ops = self.ops.scalar_ops;
|
||||
let q = &public_key_ops.common.elem_modulus(cpu);
|
||||
let n = &scalar_ops.scalar_modulus(cpu);
|
||||
|
||||
// NSA Guide Prerequisites:
|
||||
//
|
||||
// Prior to accepting a verified digital signature as valid the
|
||||
// verifier shall have:
|
||||
//
|
||||
// 1. assurance of the signatory’s claimed identity,
|
||||
// 2. an authentic copy of the domain parameters, (q, FR, a, b, SEED,
|
||||
// G, n, h),
|
||||
// 3. assurance of the validity of the public key, and
|
||||
// 4. assurance that the claimed signatory actually possessed the
|
||||
// private key that was used to generate the digital signature at
|
||||
// the time that the signature was generated.
|
||||
//
|
||||
// Prerequisites #1 and #4 are outside the scope of what this function
|
||||
// can do. Prerequisite #2 is handled implicitly as the domain
|
||||
// parameters are hard-coded into the source. Prerequisite #3 is
|
||||
// handled by `parse_uncompressed_point`.
|
||||
let peer_pub_key = parse_uncompressed_point(public_key_ops, q, public_key)?;
|
||||
|
||||
let (r, s) = signature.read_all(error::Unspecified, |input| {
|
||||
(self.split_rs)(scalar_ops, input)
|
||||
})?;
|
||||
|
||||
// NSA Guide Step 1: "If r and s are not both integers in the interval
|
||||
// [1, n − 1], output INVALID."
|
||||
let r = scalar_parse_big_endian_variable(n, limb::AllowZero::No, r)?;
|
||||
let s = scalar_parse_big_endian_variable(n, limb::AllowZero::No, s)?;
|
||||
|
||||
// NSA Guide Step 4: "Compute w = s**−1 mod n, using the routine in
|
||||
// Appendix B.1."
|
||||
let w = self.ops.scalar_inv_to_mont_vartime(&s, cpu);
|
||||
|
||||
// NSA Guide Step 5: "Compute u1 = (e * w) mod n, and compute
|
||||
// u2 = (r * w) mod n."
|
||||
let u1 = scalar_ops.scalar_product(&e, &w, cpu);
|
||||
let u2 = scalar_ops.scalar_product(&r, &w, cpu);
|
||||
|
||||
// NSA Guide Step 6: "Compute the elliptic curve point
|
||||
// R = (xR, yR) = u1*G + u2*Q, using EC scalar multiplication and EC
|
||||
// addition. If R is equal to the point at infinity, output INVALID."
|
||||
let product = (self.ops.twin_mul)(&u1, &u2, &peer_pub_key, cpu);
|
||||
|
||||
// Verify that the point we computed is on the curve; see
|
||||
// `verify_affine_point_is_on_the_curve_scaled` for details on why. It
|
||||
// would be more secure to do the check on the affine coordinates if we
|
||||
// were going to convert to affine form (again, see
|
||||
// `verify_affine_point_is_on_the_curve_scaled` for details on why).
|
||||
// But, we're going to avoid converting to affine for performance
|
||||
// reasons, so we do the verification using the Jacobian coordinates.
|
||||
let z2 = verify_jacobian_point_is_on_the_curve(q, &product)?;
|
||||
|
||||
// NSA Guide Step 7: "Compute v = xR mod n."
|
||||
// NSA Guide Step 8: "Compare v and r0. If v = r0, output VALID;
|
||||
// otherwise, output INVALID."
|
||||
//
|
||||
// Instead, we use Greg Maxwell's trick to avoid the inversion mod `q`
|
||||
// that would be necessary to compute the affine X coordinate.
|
||||
let x = q.point_x(&product);
|
||||
fn sig_r_equals_x(q: &Modulus<Q>, r: &Elem<Unencoded>, x: &Elem<R>, z2: &Elem<R>) -> bool {
|
||||
let r_jacobian = q.elem_product(z2, r);
|
||||
let x = q.elem_unencoded(x);
|
||||
q.elems_are_equal(&r_jacobian, &x).leak()
|
||||
}
|
||||
let mut r = self.ops.scalar_as_elem(&r);
|
||||
if sig_r_equals_x(q, &r, &x, &z2) {
|
||||
return Ok(());
|
||||
}
|
||||
if q.elem_less_than_vartime(&r, &self.ops.q_minus_n) {
|
||||
let n = Elem::from(self.ops.n());
|
||||
q.add_assign(&mut r, &n);
|
||||
if sig_r_equals_x(q, &r, &x, &z2) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(error::Unspecified)
|
||||
}
|
||||
}
|
||||
|
||||
impl sealed::Sealed for EcdsaVerificationAlgorithm {}
|
||||
|
||||
fn split_rs_fixed<'a>(
|
||||
ops: &'static ScalarOps,
|
||||
input: &mut untrusted::Reader<'a>,
|
||||
) -> Result<(untrusted::Input<'a>, untrusted::Input<'a>), error::Unspecified> {
|
||||
let scalar_len = ops.scalar_bytes_len();
|
||||
let r = input.read_bytes(scalar_len)?;
|
||||
let s = input.read_bytes(scalar_len)?;
|
||||
Ok((r, s))
|
||||
}
|
||||
|
||||
fn split_rs_asn1<'a>(
|
||||
_ops: &'static ScalarOps,
|
||||
input: &mut untrusted::Reader<'a>,
|
||||
) -> Result<(untrusted::Input<'a>, untrusted::Input<'a>), error::Unspecified> {
|
||||
der::nested(input, der::Tag::Sequence, error::Unspecified, |input| {
|
||||
let r = der::positive_integer(input)?.big_endian_without_leading_zero_as_input();
|
||||
let s = der::positive_integer(input)?.big_endian_without_leading_zero_as_input();
|
||||
Ok((r, s))
|
||||
})
|
||||
}
|
||||
|
||||
/// Verification of fixed-length (PKCS#11 style) ECDSA signatures using the
|
||||
/// P-256 curve and SHA-256.
|
||||
///
|
||||
/// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P256_SHA256_FIXED: EcdsaVerificationAlgorithm = EcdsaVerificationAlgorithm {
|
||||
ops: &p256::PUBLIC_SCALAR_OPS,
|
||||
digest_alg: &digest::SHA256,
|
||||
split_rs: split_rs_fixed,
|
||||
id: AlgorithmID::ECDSA_P256_SHA256_FIXED,
|
||||
};
|
||||
|
||||
/// Verification of fixed-length (PKCS#11 style) ECDSA signatures using the
|
||||
/// P-384 curve and SHA-384.
|
||||
///
|
||||
/// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P384_SHA384_FIXED: EcdsaVerificationAlgorithm = EcdsaVerificationAlgorithm {
|
||||
ops: &p384::PUBLIC_SCALAR_OPS,
|
||||
digest_alg: &digest::SHA384,
|
||||
split_rs: split_rs_fixed,
|
||||
id: AlgorithmID::ECDSA_P384_SHA384_FIXED,
|
||||
};
|
||||
|
||||
/// Verification of ASN.1 DER-encoded ECDSA signatures using the P-256 curve
|
||||
/// and SHA-256.
|
||||
///
|
||||
/// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P256_SHA256_ASN1: EcdsaVerificationAlgorithm = EcdsaVerificationAlgorithm {
|
||||
ops: &p256::PUBLIC_SCALAR_OPS,
|
||||
digest_alg: &digest::SHA256,
|
||||
split_rs: split_rs_asn1,
|
||||
id: AlgorithmID::ECDSA_P256_SHA256_ASN1,
|
||||
};
|
||||
|
||||
/// *Not recommended*. Verification of ASN.1 DER-encoded ECDSA signatures using
|
||||
/// the P-256 curve and SHA-384.
|
||||
///
|
||||
/// In most situations, P-256 should be used only with SHA-256 and P-384
|
||||
/// should be used only with SHA-384. However, in some cases, particularly TLS
|
||||
/// on the web, it is necessary to support P-256 with SHA-384 for compatibility
|
||||
/// with widely-deployed implementations that do not follow these guidelines.
|
||||
///
|
||||
/// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P256_SHA384_ASN1: EcdsaVerificationAlgorithm = EcdsaVerificationAlgorithm {
|
||||
ops: &p256::PUBLIC_SCALAR_OPS,
|
||||
digest_alg: &digest::SHA384,
|
||||
split_rs: split_rs_asn1,
|
||||
id: AlgorithmID::ECDSA_P256_SHA384_ASN1,
|
||||
};
|
||||
|
||||
/// *Not recommended*. Verification of ASN.1 DER-encoded ECDSA signatures using
|
||||
/// the P-384 curve and SHA-256.
|
||||
///
|
||||
/// In most situations, P-256 should be used only with SHA-256 and P-384
|
||||
/// should be used only with SHA-384. However, in some cases, particularly TLS
|
||||
/// on the web, it is necessary to support P-256 with SHA-384 for compatibility
|
||||
/// with widely-deployed implementations that do not follow these guidelines.
|
||||
///
|
||||
/// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P384_SHA256_ASN1: EcdsaVerificationAlgorithm = EcdsaVerificationAlgorithm {
|
||||
ops: &p384::PUBLIC_SCALAR_OPS,
|
||||
digest_alg: &digest::SHA256,
|
||||
split_rs: split_rs_asn1,
|
||||
id: AlgorithmID::ECDSA_P384_SHA256_ASN1,
|
||||
};
|
||||
|
||||
/// Verification of ASN.1 DER-encoded ECDSA signatures using the P-384 curve
|
||||
/// and SHA-384.
|
||||
///
|
||||
/// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
|
||||
/// documentation for more details.
|
||||
pub static ECDSA_P384_SHA384_ASN1: EcdsaVerificationAlgorithm = EcdsaVerificationAlgorithm {
|
||||
ops: &p384::PUBLIC_SCALAR_OPS,
|
||||
digest_alg: &digest::SHA384,
|
||||
split_rs: split_rs_asn1,
|
||||
id: AlgorithmID::ECDSA_P384_SHA384_ASN1,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
extern crate alloc;
|
||||
use super::*;
|
||||
use crate::testutil as test;
|
||||
use alloc::{vec, vec::Vec};
|
||||
|
||||
#[test]
|
||||
fn test_digest_based_test_vectors() {
|
||||
let cpu = cpu::features();
|
||||
test::run(
|
||||
test_vector_file!("../../../../crypto/fipsmodule/ecdsa/ecdsa_verify_tests.txt"),
|
||||
|section, test_case| {
|
||||
assert_eq!(section, "");
|
||||
|
||||
let curve_name = test_case.consume_string("Curve");
|
||||
|
||||
let public_key = {
|
||||
let mut public_key = vec![0x04];
|
||||
public_key.extend(&test_case.consume_bytes("X"));
|
||||
public_key.extend(&test_case.consume_bytes("Y"));
|
||||
public_key
|
||||
};
|
||||
|
||||
let digest = test_case.consume_bytes("Digest");
|
||||
|
||||
let sig = {
|
||||
let mut sig = Vec::new();
|
||||
sig.extend(&test_case.consume_bytes("R"));
|
||||
sig.extend(&test_case.consume_bytes("S"));
|
||||
sig
|
||||
};
|
||||
|
||||
let invalid = test_case.consume_optional_string("Invalid");
|
||||
|
||||
let alg = match curve_name.as_str() {
|
||||
"P-256" => &ECDSA_P256_SHA256_FIXED,
|
||||
"P-384" => &ECDSA_P384_SHA384_FIXED,
|
||||
_ => {
|
||||
panic!("Unsupported curve: {}", curve_name);
|
||||
}
|
||||
};
|
||||
let n = &alg.ops.scalar_ops.scalar_modulus(cpu);
|
||||
|
||||
let digest = super::super::digest_scalar::digest_bytes_scalar(n, &digest[..]);
|
||||
let actual_result = alg.verify_digest(
|
||||
untrusted::Input::from(&public_key[..]),
|
||||
digest,
|
||||
untrusted::Input::from(&sig[..]),
|
||||
);
|
||||
assert_eq!(actual_result.is_ok(), invalid.is_none());
|
||||
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Vendored
+1406
File diff suppressed because it is too large
Load Diff
+167
@@ -0,0 +1,167 @@
|
||||
// Copyright 2017 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
use crate::ec::suite_b::ops::{
|
||||
p256::NUM_LIMBS as P256_NUM_LIMBS, p384::NUM_LIMBS as P384_NUM_LIMBS,
|
||||
};
|
||||
use crate::{
|
||||
arithmetic::{
|
||||
limbs_from_hex,
|
||||
montgomery::{Encoding, ProductEncoding, Unencoded},
|
||||
},
|
||||
limb::{LeakyLimb, Limb},
|
||||
};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum NumLimbs {
|
||||
P256,
|
||||
P384,
|
||||
}
|
||||
|
||||
impl NumLimbs {
|
||||
pub(super) const MAX: usize = Self::P384.into();
|
||||
|
||||
pub(super) const fn into(self) -> usize {
|
||||
match self {
|
||||
NumLimbs::P256 => P256_NUM_LIMBS,
|
||||
NumLimbs::P384 => P384_NUM_LIMBS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Elements of ℤ/mℤ for some modulus *m*. Elements are always fully reduced
|
||||
/// with respect to *m*; i.e. the 0 <= x < m for every value x.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Elem<M, E: Encoding> {
|
||||
// XXX: pub
|
||||
pub(super) limbs: [Limb; NumLimbs::MAX],
|
||||
|
||||
/// The modulus *m* for the ring ℤ/mℤ for which this element is a value.
|
||||
pub(super) m: PhantomData<M>,
|
||||
|
||||
/// The number of Montgomery factors that need to be canceled out from
|
||||
/// `value` to get the actual value.
|
||||
pub(super) encoding: PhantomData<E>,
|
||||
}
|
||||
|
||||
pub struct PublicElem<M, E: Encoding> {
|
||||
pub(super) limbs: [LeakyLimb; NumLimbs::MAX],
|
||||
pub(super) m: PhantomData<M>,
|
||||
pub(super) encoding: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<M, E: Encoding> From<&PublicElem<M, E>> for Elem<M, E> {
|
||||
fn from(value: &PublicElem<M, E>) -> Self {
|
||||
Self {
|
||||
limbs: core::array::from_fn(|i| Limb::from(value.limbs[i])),
|
||||
m: value.m,
|
||||
encoding: value.encoding,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<M, E: Encoding> Elem<M, E> {
|
||||
// There's no need to convert `value` to the Montgomery domain since
|
||||
// 0 * R**2 (mod m) == 0, so neither the modulus nor the encoding are needed
|
||||
// as inputs for constructing a zero-valued element.
|
||||
pub fn zero() -> Self {
|
||||
Self {
|
||||
limbs: [0; NumLimbs::MAX],
|
||||
m: PhantomData,
|
||||
encoding: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<M> Elem<M, Unencoded> {
|
||||
pub fn one() -> Self {
|
||||
let mut r = Self::zero();
|
||||
r.limbs[0] = 1;
|
||||
r
|
||||
}
|
||||
}
|
||||
|
||||
impl<M, E: Encoding> PublicElem<M, E> {
|
||||
pub const fn from_hex(hex: &str) -> Self {
|
||||
Self {
|
||||
limbs: limbs_from_hex(hex),
|
||||
m: PhantomData,
|
||||
encoding: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn mul_mont<M, EA: Encoding, EB: Encoding>(
|
||||
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
|
||||
a: &Elem<M, EA>,
|
||||
b: &Elem<M, EB>,
|
||||
) -> Elem<M, <(EA, EB) as ProductEncoding>::Output>
|
||||
where
|
||||
(EA, EB): ProductEncoding,
|
||||
{
|
||||
binary_op(f, a, b)
|
||||
}
|
||||
|
||||
// let r = f(a, b); return r;
|
||||
#[inline]
|
||||
pub fn binary_op<M, EA: Encoding, EB: Encoding, ER: Encoding>(
|
||||
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
|
||||
a: &Elem<M, EA>,
|
||||
b: &Elem<M, EB>,
|
||||
) -> Elem<M, ER> {
|
||||
let mut r = Elem::zero();
|
||||
unsafe { f(r.limbs.as_mut_ptr(), a.limbs.as_ptr(), b.limbs.as_ptr()) }
|
||||
r
|
||||
}
|
||||
|
||||
// a := f(a, b);
|
||||
#[inline]
|
||||
pub fn binary_op_assign<M, EA: Encoding, EB: Encoding>(
|
||||
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
|
||||
a: &mut Elem<M, EA>,
|
||||
b: &Elem<M, EB>,
|
||||
) {
|
||||
unsafe { f(a.limbs.as_mut_ptr(), a.limbs.as_ptr(), b.limbs.as_ptr()) }
|
||||
}
|
||||
|
||||
// let r = f(a); return r;
|
||||
#[inline]
|
||||
pub fn unary_op<M, E: Encoding>(
|
||||
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb),
|
||||
a: &Elem<M, E>,
|
||||
) -> Elem<M, E> {
|
||||
let mut r = Elem::zero();
|
||||
unsafe { f(r.limbs.as_mut_ptr(), a.limbs.as_ptr()) }
|
||||
r
|
||||
}
|
||||
|
||||
// a := f(a);
|
||||
#[inline]
|
||||
pub fn unary_op_assign<M, E: Encoding>(
|
||||
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb),
|
||||
a: &mut Elem<M, E>,
|
||||
) {
|
||||
unsafe { f(a.limbs.as_mut_ptr(), a.limbs.as_ptr()) }
|
||||
}
|
||||
|
||||
// a := f(a, a);
|
||||
#[inline]
|
||||
pub fn unary_op_from_binary_op_assign<M, E: Encoding>(
|
||||
f: unsafe extern "C" fn(r: *mut Limb, a: *const Limb, b: *const Limb),
|
||||
a: &mut Elem<M, E>,
|
||||
) {
|
||||
unsafe { f(a.limbs.as_mut_ptr(), a.limbs.as_ptr(), a.limbs.as_ptr()) }
|
||||
}
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
// Copyright 2016-2023 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
use super::{
|
||||
elem::{binary_op, binary_op_assign},
|
||||
elem_sqr_mul, elem_sqr_mul_acc, PublicModulus, *,
|
||||
};
|
||||
|
||||
pub(super) const NUM_LIMBS: usize = 256 / LIMB_BITS;
|
||||
|
||||
pub static COMMON_OPS: CommonOps = CommonOps {
|
||||
num_limbs: elem::NumLimbs::P256,
|
||||
|
||||
q: PublicModulus {
|
||||
p: limbs_from_hex("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),
|
||||
rr: PublicElem::from_hex("4fffffffdfffffffffffffffefffffffbffffffff0000000000000003"),
|
||||
},
|
||||
n: PublicElem::from_hex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
|
||||
|
||||
a: PublicElem::from_hex("fffffffc00000004000000000000000000000003fffffffffffffffffffffffc"),
|
||||
b: PublicElem::from_hex("dc30061d04874834e5a220abf7212ed6acf005cd78843090d89cdf6229c4bddf"),
|
||||
|
||||
elem_mul_mont: p256_mul_mont,
|
||||
elem_sqr_mont: p256_sqr_mont,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) static GENERATOR: (PublicElem<R>, PublicElem<R>) = (
|
||||
PublicElem::from_hex("18905f76a53755c679fb732b7762251075ba95fc5fedb60179e730d418a9143c"),
|
||||
PublicElem::from_hex("8571ff1825885d85d2e88688dd21f3258b4ab8e4ba19e45cddf25357ce95560a"),
|
||||
);
|
||||
|
||||
pub static PRIVATE_KEY_OPS: PrivateKeyOps = PrivateKeyOps {
|
||||
common: &COMMON_OPS,
|
||||
elem_inv_squared: p256_elem_inv_squared,
|
||||
point_mul_base_impl: p256_point_mul_base_impl,
|
||||
point_mul_impl: p256_point_mul,
|
||||
point_add_jacobian_impl: p256_point_add,
|
||||
};
|
||||
|
||||
fn p256_elem_inv_squared(q: &Modulus<Q>, a: &Elem<R>) -> Elem<R> {
|
||||
// Calculate a**-2 (mod q) == a**(q - 3) (mod q)
|
||||
//
|
||||
// The exponent (q - 3) is:
|
||||
//
|
||||
// 0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc
|
||||
|
||||
#[inline]
|
||||
fn sqr_mul(q: &Modulus<Q>, a: &Elem<R>, squarings: LeakyWord, b: &Elem<R>) -> Elem<R> {
|
||||
elem_sqr_mul(&COMMON_OPS, a, squarings, b, q.cpu())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn sqr_mul_acc(q: &Modulus<Q>, a: &mut Elem<R>, squarings: LeakyWord, b: &Elem<R>) {
|
||||
elem_sqr_mul_acc(&COMMON_OPS, a, squarings, b, q.cpu())
|
||||
}
|
||||
|
||||
let b_1 = &a;
|
||||
let b_11 = sqr_mul(q, b_1, 1, b_1);
|
||||
let b_111 = sqr_mul(q, &b_11, 1, b_1);
|
||||
let f_11 = sqr_mul(q, &b_111, 3, &b_111);
|
||||
let fff = sqr_mul(q, &f_11, 6, &f_11);
|
||||
let fff_111 = sqr_mul(q, &fff, 3, &b_111);
|
||||
let fffffff_11 = sqr_mul(q, &fff_111, 15, &fff_111);
|
||||
let ffffffff = sqr_mul(q, &fffffff_11, 2, &b_11);
|
||||
|
||||
// ffffffff00000001
|
||||
let mut acc = sqr_mul(q, &ffffffff, 31 + 1, b_1);
|
||||
|
||||
// ffffffff00000001000000000000000000000000ffffffff
|
||||
sqr_mul_acc(q, &mut acc, 96 + 32, &ffffffff);
|
||||
|
||||
// ffffffff00000001000000000000000000000000ffffffffffffffff
|
||||
sqr_mul_acc(q, &mut acc, 32, &ffffffff);
|
||||
|
||||
// ffffffff00000001000000000000000000000000fffffffffffffffffffffff_11
|
||||
sqr_mul_acc(q, &mut acc, 30, &fffffff_11);
|
||||
|
||||
// ffffffff00000001000000000000000000000000fffffffffffffffffffffffc
|
||||
q.elem_square(&mut acc);
|
||||
q.elem_square(&mut acc);
|
||||
|
||||
acc
|
||||
}
|
||||
|
||||
fn p256_point_mul_base_impl(g_scalar: &Scalar, _cpu: cpu::Features) -> Point {
|
||||
prefixed_extern! {
|
||||
fn p256_point_mul_base(
|
||||
r: *mut Limb, // [3][COMMON_OPS.num_limbs]
|
||||
g_scalar: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
}
|
||||
|
||||
let mut r = Point::new_at_infinity();
|
||||
unsafe {
|
||||
p256_point_mul_base(r.xyz.as_mut_ptr(), g_scalar.limbs.as_ptr());
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
pub static PUBLIC_KEY_OPS: PublicKeyOps = PublicKeyOps {
|
||||
common: &COMMON_OPS,
|
||||
};
|
||||
|
||||
pub static SCALAR_OPS: ScalarOps = ScalarOps {
|
||||
common: &COMMON_OPS,
|
||||
scalar_mul_mont: p256_scalar_mul_mont,
|
||||
};
|
||||
|
||||
pub static PUBLIC_SCALAR_OPS: PublicScalarOps = PublicScalarOps {
|
||||
scalar_ops: &SCALAR_OPS,
|
||||
public_key_ops: &PUBLIC_KEY_OPS,
|
||||
|
||||
#[cfg(any(
|
||||
all(target_arch = "aarch64", target_endian = "little"),
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
twin_mul: twin_mul_nistz256,
|
||||
|
||||
#[cfg(not(any(
|
||||
all(target_arch = "aarch64", target_endian = "little"),
|
||||
target_arch = "x86_64"
|
||||
)))]
|
||||
twin_mul: |g_scalar, p_scalar, p_xy, cpu| {
|
||||
twin_mul_inefficient(&PRIVATE_KEY_OPS, g_scalar, p_scalar, p_xy, cpu)
|
||||
},
|
||||
|
||||
q_minus_n: PublicElem::from_hex("4319055358e8617b0c46353d039cdaae"),
|
||||
|
||||
// TODO: Use an optimized variable-time implementation.
|
||||
scalar_inv_to_mont_vartime: |s, cpu| PRIVATE_SCALAR_OPS.scalar_inv_to_mont(s, cpu),
|
||||
};
|
||||
|
||||
#[cfg(any(
|
||||
all(target_arch = "aarch64", target_endian = "little"),
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
fn twin_mul_nistz256(
|
||||
g_scalar: &Scalar,
|
||||
p_scalar: &Scalar,
|
||||
p_xy: &(Elem<R>, Elem<R>),
|
||||
cpu: cpu::Features,
|
||||
) -> Point {
|
||||
let scaled_g = point_mul_base_vartime(g_scalar, cpu);
|
||||
let scaled_p = PRIVATE_KEY_OPS.point_mul(p_scalar, p_xy, cpu::features());
|
||||
PRIVATE_KEY_OPS.point_sum(&scaled_g, &scaled_p, cpu)
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(target_arch = "aarch64", target_endian = "little"),
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
fn point_mul_base_vartime(g_scalar: &Scalar, _cpu: cpu::Features) -> Point {
|
||||
prefixed_extern! {
|
||||
fn p256_point_mul_base_vartime(r: *mut Limb, // [3][COMMON_OPS.num_limbs]
|
||||
g_scalar: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
}
|
||||
let mut scaled_g = Point::new_at_infinity();
|
||||
unsafe {
|
||||
p256_point_mul_base_vartime(scaled_g.xyz.as_mut_ptr(), g_scalar.limbs.as_ptr());
|
||||
}
|
||||
scaled_g
|
||||
}
|
||||
|
||||
pub static PRIVATE_SCALAR_OPS: PrivateScalarOps = PrivateScalarOps {
|
||||
scalar_ops: &SCALAR_OPS,
|
||||
|
||||
oneRR_mod_n: PublicScalar::from_hex(
|
||||
"66e12d94f3d956202845b2392b6bec594699799c49bd6fa683244c95be79eea2",
|
||||
),
|
||||
scalar_inv_to_mont: p256_scalar_inv_to_mont,
|
||||
};
|
||||
|
||||
#[allow(clippy::just_underscores_and_digits)]
|
||||
fn p256_scalar_inv_to_mont(a: Scalar<R>, _cpu: cpu::Features) -> Scalar<R> {
|
||||
// Calculate the modular inverse of scalar |a| using Fermat's Little
|
||||
// Theorem:
|
||||
//
|
||||
// a**-1 (mod n) == a**(n - 2) (mod n)
|
||||
//
|
||||
// The exponent (n - 2) is:
|
||||
//
|
||||
// 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc63254f
|
||||
|
||||
#[inline]
|
||||
fn mul(a: &Scalar<R>, b: &Scalar<R>) -> Scalar<R> {
|
||||
binary_op(p256_scalar_mul_mont, a, b)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn sqr(a: &Scalar<R>) -> Scalar<R> {
|
||||
let mut tmp = Scalar::zero();
|
||||
unsafe { p256_scalar_sqr_rep_mont(tmp.limbs.as_mut_ptr(), a.limbs.as_ptr(), 1) }
|
||||
tmp
|
||||
}
|
||||
|
||||
// Returns (`a` squared `squarings` times) * `b`.
|
||||
fn sqr_mul(a: &Scalar<R>, squarings: LeakyWord, b: &Scalar<R>) -> Scalar<R> {
|
||||
debug_assert!(squarings >= 1);
|
||||
let mut tmp = Scalar::zero();
|
||||
unsafe { p256_scalar_sqr_rep_mont(tmp.limbs.as_mut_ptr(), a.limbs.as_ptr(), squarings) }
|
||||
mul(&tmp, b)
|
||||
}
|
||||
|
||||
// Sets `acc` = (`acc` squared `squarings` times) * `b`.
|
||||
fn sqr_mul_acc(acc: &mut Scalar<R>, squarings: LeakyWord, b: &Scalar<R>) {
|
||||
debug_assert!(squarings >= 1);
|
||||
unsafe { p256_scalar_sqr_rep_mont(acc.limbs.as_mut_ptr(), acc.limbs.as_ptr(), squarings) }
|
||||
binary_op_assign(p256_scalar_mul_mont, acc, b);
|
||||
}
|
||||
|
||||
let _1 = &a;
|
||||
|
||||
let _10 = sqr(_1); // 2
|
||||
let _100 = sqr(&_10); // 4
|
||||
let _101 = mul(&_100, _1); // 5
|
||||
let _111 = mul(&_101, &_10); // 7
|
||||
|
||||
let _1000 = sqr(&_100); // 8
|
||||
let _10000 = sqr(&_1000); // 16
|
||||
let _100000 = sqr(&_10000); // 32
|
||||
|
||||
let _100111 = mul(&_111, &_100000); // 39 = 7 + 32
|
||||
let _101011 = mul(&_100, &_100111); // 43 = 4 + 39
|
||||
let _101111 = mul(&_100, &_101011); // 47 = 4 + 39
|
||||
let _1001111 = mul(&_100000, &_101111); // 79 = 32 + 47
|
||||
let _86 = sqr(&_101011); // 86 = 43 * 2
|
||||
let _1011011 = mul(&_101, &_86); // 91 = 5 + 86
|
||||
let _92 = mul(_1, &_1011011); // 92 = 1 + 91
|
||||
let _1100011 = mul(&_111, &_92); // 99 = 7 + 92
|
||||
let _10111111 = mul(&_92, &_1100011); // 191 = 92 + 99
|
||||
let _11011111 = mul(&_100000, &_10111111); // 223 = 32 + 191
|
||||
|
||||
let ff = mul(&_100000, &_11011111); // 255 = 32 + 223
|
||||
let ffff = sqr_mul(&ff, 0 + 8, &ff);
|
||||
let ffffffff = sqr_mul(&ffff, 0 + 16, &ffff);
|
||||
|
||||
// ffffffff00000000ffffffff
|
||||
let mut acc = sqr_mul(&ffffffff, 32 + 32, &ffffffff);
|
||||
|
||||
// ffffffff00000000ffffffffffffffff
|
||||
sqr_mul_acc(&mut acc, 0 + 32, &ffffffff);
|
||||
|
||||
// The rest of the exponent, in binary, is:
|
||||
//
|
||||
// 1011110011100110111110101010110110100111000101111001111010000100
|
||||
// 1111001110111001110010101100001011111100011000110010010101001111
|
||||
|
||||
sqr_mul_acc(&mut acc, 6, &_101111);
|
||||
sqr_mul_acc(&mut acc, 2 + 3, &_111);
|
||||
sqr_mul_acc(&mut acc, 2 + 8, &_11011111);
|
||||
sqr_mul_acc(&mut acc, 1 + 3, &_101);
|
||||
sqr_mul_acc(&mut acc, 1 + 7, &_1011011);
|
||||
sqr_mul_acc(&mut acc, 1 + 6, &_100111);
|
||||
sqr_mul_acc(&mut acc, 3 + 6, &_101111);
|
||||
sqr_mul_acc(&mut acc, 2 + 3, &_111);
|
||||
sqr_mul_acc(&mut acc, 3, &_101);
|
||||
sqr_mul_acc(&mut acc, 4 + 7, &_1001111);
|
||||
sqr_mul_acc(&mut acc, 2 + 3, &_111);
|
||||
sqr_mul_acc(&mut acc, 1 + 3, &_111);
|
||||
sqr_mul_acc(&mut acc, 2 + 3, &_111);
|
||||
sqr_mul_acc(&mut acc, 2 + 6, &_101011);
|
||||
sqr_mul_acc(&mut acc, 4 + 8, &_10111111);
|
||||
sqr_mul_acc(&mut acc, 3 + 7, &_1100011);
|
||||
sqr_mul_acc(&mut acc, 2 + 1, _1);
|
||||
sqr_mul_acc(&mut acc, 2 + 3, &_101);
|
||||
sqr_mul_acc(&mut acc, 1 + 7, &_1001111);
|
||||
|
||||
acc
|
||||
}
|
||||
|
||||
prefixed_extern! {
|
||||
pub(super) fn p256_mul_mont(
|
||||
r: *mut Limb, // [COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
b: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
pub(super) fn p256_sqr_mont(
|
||||
r: *mut Limb, // [COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
|
||||
fn p256_point_add(
|
||||
r: *mut Limb, // [3][COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [3][COMMON_OPS.num_limbs]
|
||||
b: *const Limb, // [3][COMMON_OPS.num_limbs]
|
||||
);
|
||||
fn p256_point_mul(
|
||||
r: *mut Limb, // [3][COMMON_OPS.num_limbs]
|
||||
p_scalar: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
p_x: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
p_y: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
|
||||
fn p256_scalar_mul_mont(
|
||||
r: *mut Limb, // [COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
b: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
fn p256_scalar_sqr_rep_mont(
|
||||
r: *mut Limb, // [COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
rep: LeakyWord,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[cfg(any(
|
||||
all(target_arch = "aarch64", target_endian = "little"),
|
||||
target_arch = "x86_64"
|
||||
))]
|
||||
#[test]
|
||||
fn p256_point_mul_base_vartime_test() {
|
||||
use super::{super::tests::point_mul_base_tests, *};
|
||||
point_mul_base_tests(
|
||||
&PRIVATE_KEY_OPS,
|
||||
point_mul_base_vartime,
|
||||
test_vector_file!("p256_point_mul_base_tests.txt"),
|
||||
);
|
||||
}
|
||||
}
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
// Copyright 2016-2023 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
use super::{
|
||||
elem::{binary_op, binary_op_assign},
|
||||
elem_sqr_mul, elem_sqr_mul_acc, PublicModulus, *,
|
||||
};
|
||||
|
||||
pub(super) const NUM_LIMBS: usize = 384 / LIMB_BITS;
|
||||
|
||||
pub static COMMON_OPS: CommonOps = CommonOps {
|
||||
num_limbs: elem::NumLimbs::P384,
|
||||
|
||||
q: PublicModulus {
|
||||
p: limbs_from_hex("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),
|
||||
rr: PublicElem::from_hex("10000000200000000fffffffe000000000000000200000000fffffffe00000001"),
|
||||
},
|
||||
n: PublicElem::from_hex("ffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),
|
||||
|
||||
a: PublicElem::from_hex("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbfffffffc0000000000000003fffffffc"),
|
||||
b: PublicElem::from_hex("cd08114b604fbff9b62b21f41f022094e3374bee94938ae277f2209b1920022ef729add87a4c32ec081188719d412dcc"),
|
||||
|
||||
elem_mul_mont: p384_elem_mul_mont,
|
||||
elem_sqr_mont: p384_elem_sqr_mont,
|
||||
};
|
||||
|
||||
pub(super) static GENERATOR: (PublicElem<R>, PublicElem<R>) = (
|
||||
PublicElem::from_hex("4d3aadc2299e1513812ff723614ede2b6454868459a30eff879c3afc541b4d6e20e378e2a0d6ce383dd0756649c0b528"),
|
||||
PublicElem::from_hex("2b78abc25a15c5e9dd8002263969a840c6c3521968f4ffd98bade7562e83b050a1bfa8bf7bb4a9ac23043dad4b03a4fe"),
|
||||
);
|
||||
|
||||
pub static PRIVATE_KEY_OPS: PrivateKeyOps = PrivateKeyOps {
|
||||
common: &COMMON_OPS,
|
||||
elem_inv_squared: p384_elem_inv_squared,
|
||||
point_mul_base_impl: p384_point_mul_base_impl,
|
||||
point_mul_impl: p384_point_mul,
|
||||
point_add_jacobian_impl: p384_point_add,
|
||||
};
|
||||
|
||||
fn p384_elem_inv_squared(q: &Modulus<Q>, a: &Elem<R>) -> Elem<R> {
|
||||
// Calculate a**-2 (mod q) == a**(q - 3) (mod q)
|
||||
//
|
||||
// The exponent (q - 3) is:
|
||||
//
|
||||
// 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe\
|
||||
// ffffffff0000000000000000fffffffc
|
||||
|
||||
#[inline]
|
||||
fn sqr_mul(q: &Modulus<Q>, a: &Elem<R>, squarings: LeakyWord, b: &Elem<R>) -> Elem<R> {
|
||||
elem_sqr_mul(&COMMON_OPS, a, squarings, b, q.cpu())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn sqr_mul_acc(q: &Modulus<Q>, a: &mut Elem<R>, squarings: LeakyWord, b: &Elem<R>) {
|
||||
elem_sqr_mul_acc(&COMMON_OPS, a, squarings, b, q.cpu())
|
||||
}
|
||||
|
||||
let b_1 = &a;
|
||||
let b_11 = sqr_mul(q, b_1, 1, b_1);
|
||||
let b_111 = sqr_mul(q, &b_11, 1, b_1);
|
||||
let f_11 = sqr_mul(q, &b_111, 3, &b_111);
|
||||
let fff = sqr_mul(q, &f_11, 6, &f_11);
|
||||
let fff_111 = sqr_mul(q, &fff, 3, &b_111);
|
||||
let fffffff_11 = sqr_mul(q, &fff_111, 15, &fff_111);
|
||||
|
||||
let fffffffffffffff = sqr_mul(q, &fffffff_11, 30, &fffffff_11);
|
||||
|
||||
let ffffffffffffffffffffffffffffff = sqr_mul(q, &fffffffffffffff, 60, &fffffffffffffff);
|
||||
|
||||
// ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
|
||||
let mut acc = sqr_mul(
|
||||
q,
|
||||
&ffffffffffffffffffffffffffffff,
|
||||
120,
|
||||
&ffffffffffffffffffffffffffffff,
|
||||
);
|
||||
|
||||
// fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff_111
|
||||
sqr_mul_acc(q, &mut acc, 15, &fff_111);
|
||||
|
||||
// fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff
|
||||
sqr_mul_acc(q, &mut acc, 1 + 30, &fffffff_11);
|
||||
sqr_mul_acc(q, &mut acc, 2, &b_11);
|
||||
|
||||
// fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff
|
||||
// 0000000000000000fffffff_11
|
||||
sqr_mul_acc(q, &mut acc, 64 + 30, &fffffff_11);
|
||||
|
||||
// fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff
|
||||
// 0000000000000000fffffffc
|
||||
q.elem_square(&mut acc);
|
||||
q.elem_square(&mut acc);
|
||||
|
||||
acc
|
||||
}
|
||||
|
||||
fn p384_point_mul_base_impl(a: &Scalar, cpu: cpu::Features) -> Point {
|
||||
// XXX: Not efficient. TODO: Precompute multiples of the generator.
|
||||
let generator = (Elem::from(&GENERATOR.0), Elem::from(&GENERATOR.1));
|
||||
PRIVATE_KEY_OPS.point_mul(a, &generator, cpu)
|
||||
}
|
||||
|
||||
pub static PUBLIC_KEY_OPS: PublicKeyOps = PublicKeyOps {
|
||||
common: &COMMON_OPS,
|
||||
};
|
||||
|
||||
pub static SCALAR_OPS: ScalarOps = ScalarOps {
|
||||
common: &COMMON_OPS,
|
||||
scalar_mul_mont: p384_scalar_mul_mont,
|
||||
};
|
||||
|
||||
pub static PUBLIC_SCALAR_OPS: PublicScalarOps = PublicScalarOps {
|
||||
scalar_ops: &SCALAR_OPS,
|
||||
public_key_ops: &PUBLIC_KEY_OPS,
|
||||
twin_mul: |g_scalar, p_scalar, p_xy, cpu| {
|
||||
twin_mul_inefficient(&PRIVATE_KEY_OPS, g_scalar, p_scalar, p_xy, cpu)
|
||||
},
|
||||
|
||||
q_minus_n: PublicElem::from_hex("389cb27e0bc8d21fa7e5f24cb74f58851313e696333ad68c"),
|
||||
|
||||
// TODO: Use an optimized variable-time implementation.
|
||||
scalar_inv_to_mont_vartime: |s, cpu| PRIVATE_SCALAR_OPS.scalar_inv_to_mont(s, cpu),
|
||||
};
|
||||
|
||||
pub static PRIVATE_SCALAR_OPS: PrivateScalarOps = PrivateScalarOps {
|
||||
scalar_ops: &SCALAR_OPS,
|
||||
|
||||
oneRR_mod_n: PublicScalar::from_hex("c84ee012b39bf213fb05b7a28266895d40d49174aab1cc5bc3e483afcb82947ff3d81e5df1aa4192d319b2419b409a9"),
|
||||
scalar_inv_to_mont: p384_scalar_inv_to_mont,
|
||||
};
|
||||
|
||||
fn p384_scalar_inv_to_mont(a: Scalar<R>, _cpu: cpu::Features) -> Scalar<R> {
|
||||
// Calculate the modular inverse of scalar |a| using Fermat's Little
|
||||
// Theorem:
|
||||
//
|
||||
// a**-1 (mod n) == a**(n - 2) (mod n)
|
||||
//
|
||||
// The exponent (n - 2) is:
|
||||
//
|
||||
// 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf\
|
||||
// 581a0db248b0a77aecec196accc52971
|
||||
|
||||
fn mul(a: &Scalar<R>, b: &Scalar<R>) -> Scalar<R> {
|
||||
binary_op(p384_scalar_mul_mont, a, b)
|
||||
}
|
||||
|
||||
fn sqr(a: &Scalar<R>) -> Scalar<R> {
|
||||
binary_op(p384_scalar_mul_mont, a, a)
|
||||
}
|
||||
|
||||
fn sqr_mut(a: &mut Scalar<R>) {
|
||||
unary_op_from_binary_op_assign(p384_scalar_mul_mont, a);
|
||||
}
|
||||
|
||||
// Returns (`a` squared `squarings` times) * `b`.
|
||||
fn sqr_mul(a: &Scalar<R>, squarings: LeakyWord, b: &Scalar<R>) -> Scalar<R> {
|
||||
debug_assert!(squarings >= 1);
|
||||
let mut tmp = sqr(a);
|
||||
for _ in 1..squarings {
|
||||
sqr_mut(&mut tmp);
|
||||
}
|
||||
mul(&tmp, b)
|
||||
}
|
||||
|
||||
// Sets `acc` = (`acc` squared `squarings` times) * `b`.
|
||||
fn sqr_mul_acc(acc: &mut Scalar<R>, squarings: LeakyWord, b: &Scalar<R>) {
|
||||
debug_assert!(squarings >= 1);
|
||||
for _ in 0..squarings {
|
||||
sqr_mut(acc);
|
||||
}
|
||||
binary_op_assign(p384_scalar_mul_mont, acc, b)
|
||||
}
|
||||
|
||||
// Indexes into `d`.
|
||||
const B_1: usize = 0;
|
||||
const B_11: usize = 1;
|
||||
const B_101: usize = 2;
|
||||
const B_111: usize = 3;
|
||||
const B_1001: usize = 4;
|
||||
const B_1011: usize = 5;
|
||||
const B_1101: usize = 6;
|
||||
const B_1111: usize = 7;
|
||||
const DIGIT_COUNT: usize = 8;
|
||||
|
||||
let mut d = [Scalar::zero(); DIGIT_COUNT];
|
||||
d[B_1] = a;
|
||||
let b_10 = sqr(&d[B_1]);
|
||||
for i in B_11..DIGIT_COUNT {
|
||||
d[i] = mul(&d[i - 1], &b_10);
|
||||
}
|
||||
|
||||
let ff = sqr_mul(&d[B_1111], 0 + 4, &d[B_1111]);
|
||||
let ffff = sqr_mul(&ff, 0 + 8, &ff);
|
||||
let ffffffff = sqr_mul(&ffff, 0 + 16, &ffff);
|
||||
|
||||
let ffffffffffffffff = sqr_mul(&ffffffff, 0 + 32, &ffffffff);
|
||||
|
||||
let ffffffffffffffffffffffff = sqr_mul(&ffffffffffffffff, 0 + 32, &ffffffff);
|
||||
|
||||
// ffffffffffffffffffffffffffffffffffffffffffffffff
|
||||
let mut acc = sqr_mul(&ffffffffffffffffffffffff, 0 + 96, &ffffffffffffffffffffffff);
|
||||
|
||||
// The rest of the exponent, in binary, is:
|
||||
//
|
||||
// 1100011101100011010011011000000111110100001101110010110111011111
|
||||
// 0101100000011010000011011011001001001000101100001010011101111010
|
||||
// 1110110011101100000110010110101011001100110001010010100101110001
|
||||
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
static REMAINING_WINDOWS: [(u8, u8); 39] = [
|
||||
(2, B_11 as u8),
|
||||
(3 + 3, B_111 as u8),
|
||||
(1 + 2, B_11 as u8),
|
||||
(3 + 2, B_11 as u8),
|
||||
(1 + 4, B_1001 as u8),
|
||||
(4, B_1011 as u8),
|
||||
(6 + 4, B_1111 as u8),
|
||||
(3, B_101 as u8),
|
||||
(4 + 1, B_1 as u8),
|
||||
(4, B_1011 as u8),
|
||||
(4, B_1001 as u8),
|
||||
(1 + 4, B_1101 as u8),
|
||||
(4, B_1101 as u8),
|
||||
(4, B_1111 as u8),
|
||||
(1 + 4, B_1011 as u8),
|
||||
(6 + 4, B_1101 as u8),
|
||||
(5 + 4, B_1101 as u8),
|
||||
(4, B_1011 as u8),
|
||||
(2 + 4, B_1001 as u8),
|
||||
(2 + 1, B_1 as u8),
|
||||
(3 + 4, B_1011 as u8),
|
||||
(4 + 3, B_101 as u8),
|
||||
(2 + 3, B_111 as u8),
|
||||
(1 + 4, B_1111 as u8),
|
||||
(1 + 4, B_1011 as u8),
|
||||
(4, B_1011 as u8),
|
||||
(2 + 3, B_111 as u8),
|
||||
(1 + 2, B_11 as u8),
|
||||
(5 + 2, B_11 as u8),
|
||||
(2 + 4, B_1011 as u8),
|
||||
(1 + 3, B_101 as u8),
|
||||
(1 + 2, B_11 as u8),
|
||||
(2 + 2, B_11 as u8),
|
||||
(2 + 2, B_11 as u8),
|
||||
(3 + 3, B_101 as u8),
|
||||
(2 + 3, B_101 as u8),
|
||||
(2 + 3, B_101 as u8),
|
||||
(2, B_11 as u8),
|
||||
(3 + 1, B_1 as u8),
|
||||
];
|
||||
|
||||
for &(squarings, digit) in &REMAINING_WINDOWS[..] {
|
||||
sqr_mul_acc(&mut acc, LeakyWord::from(squarings), &d[usize::from(digit)]);
|
||||
}
|
||||
|
||||
acc
|
||||
}
|
||||
|
||||
unsafe extern "C" fn p384_elem_sqr_mont(
|
||||
r: *mut Limb, // [COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
) {
|
||||
// XXX: Inefficient. TODO: Make a dedicated squaring routine.
|
||||
unsafe {
|
||||
p384_elem_mul_mont(r, a, a);
|
||||
}
|
||||
}
|
||||
|
||||
prefixed_extern! {
|
||||
fn p384_elem_mul_mont(
|
||||
r: *mut Limb, // [COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
b: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
|
||||
fn p384_point_add(
|
||||
r: *mut Limb, // [3][COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [3][COMMON_OPS.num_limbs]
|
||||
b: *const Limb, // [3][COMMON_OPS.num_limbs]
|
||||
);
|
||||
fn p384_point_mul(
|
||||
r: *mut Limb, // [3][COMMON_OPS.num_limbs]
|
||||
p_scalar: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
p_x: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
p_y: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
|
||||
fn p384_scalar_mul_mont(
|
||||
r: *mut Limb, // [COMMON_OPS.num_limbs]
|
||||
a: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
b: *const Limb, // [COMMON_OPS.num_limbs]
|
||||
);
|
||||
}
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
// Copyright 2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! Functionality shared by operations on private keys (ECC keygen and
|
||||
//! ECDSA signing).
|
||||
|
||||
use super::{ops::*, verify_affine_point_is_on_the_curve};
|
||||
use crate::{arithmetic::montgomery::R, cpu, ec, error, limb, rand};
|
||||
|
||||
/// Generates a random scalar in the range [1, n).
|
||||
pub(super) fn random_scalar(
|
||||
ops: &PrivateKeyOps,
|
||||
n: &Modulus<N>,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
) -> Result<Scalar, error::Unspecified> {
|
||||
let mut bytes = [0; ec::SCALAR_MAX_BYTES];
|
||||
let bytes = &mut bytes[..ops.common.len()];
|
||||
generate_private_scalar_bytes(ops, rng, bytes, n.cpu())?;
|
||||
scalar_from_big_endian_bytes(n, bytes)
|
||||
}
|
||||
|
||||
pub(super) fn generate_private_scalar_bytes(
|
||||
ops: &PrivateKeyOps,
|
||||
rng: &dyn rand::SecureRandom,
|
||||
out: &mut [u8],
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
// [NSA Suite B Implementer's Guide to ECDSA] Appendix A.1.2, and
|
||||
// [NSA Suite B Implementer's Guide to NIST SP 800-56A] Appendix B.2,
|
||||
// "Key Pair Generation by Testing Candidates".
|
||||
//
|
||||
// [NSA Suite B Implementer's Guide to ECDSA]: doc/ecdsa.pdf
|
||||
// [NSA Suite B Implementer's Guide to NIST SP 800-56A]: doc/ecdh.pdf
|
||||
|
||||
// TODO: The NSA guide also suggests, in appendix B.1, another mechanism
|
||||
// that would avoid the need to use `rng.fill()` more than once. It works
|
||||
// by generating an extra 64 bits of random bytes and then reducing the
|
||||
// output (mod n). Supposedly, this removes enough of the bias towards
|
||||
// small values from the modular reduction, but it isn't obvious that it is
|
||||
// sufficient. TODO: Figure out what we can do to mitigate the bias issue
|
||||
// and switch to the other mechanism.
|
||||
|
||||
let candidate = out;
|
||||
|
||||
// XXX: The value 100 was chosen to match OpenSSL due to uncertainty of
|
||||
// what specific value would be better, but it seems bad to try 100 times.
|
||||
for _ in 0..100 {
|
||||
// NSA Guide Steps 1, 2, and 3.
|
||||
//
|
||||
// Since we calculate the length ourselves, it is pointless to check
|
||||
// it, since we can only check it by doing the same calculation.
|
||||
|
||||
// NSA Guide Step 4.
|
||||
//
|
||||
// The requirement that the random number generator has the
|
||||
// requested security strength is delegated to `rng`.
|
||||
rng.fill(candidate)?;
|
||||
|
||||
// NSA Guide Steps 5, 6, and 7.
|
||||
if check_scalar_big_endian_bytes(ops, candidate, cpu).is_err() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// NSA Guide Step 8 is done in `public_from_private()`.
|
||||
|
||||
// NSA Guide Step 9.
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(error::Unspecified)
|
||||
}
|
||||
|
||||
// The underlying X25519 and Ed25519 code uses an [u8; 32] to store the private
|
||||
// key. To make the ECDH and ECDSA code similar to that, we also store the
|
||||
// private key that way, which means we have to convert it to a Scalar whenever
|
||||
// we need to use it.
|
||||
#[inline]
|
||||
pub(super) fn private_key_as_scalar(n: &Modulus<N>, private_key: &ec::Seed) -> Scalar {
|
||||
// This cannot fail because we know the private key is valid.
|
||||
scalar_from_big_endian_bytes(n, private_key.bytes_less_safe()).unwrap()
|
||||
}
|
||||
|
||||
pub(super) fn check_scalar_big_endian_bytes(
|
||||
ops: &PrivateKeyOps,
|
||||
bytes: &[u8],
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
debug_assert_eq!(bytes.len(), ops.common.len());
|
||||
let n = &ops.common.scalar_modulus(cpu);
|
||||
scalar_from_big_endian_bytes(n, bytes).map(|_| ())
|
||||
}
|
||||
|
||||
// Parses a fixed-length (zero-padded) big-endian-encoded scalar in the range
|
||||
// [1, n). This is intended to be constant-time with respect to the actual
|
||||
// value *only if* the value is actually in range. In other words, this won't
|
||||
// leak anything about a valid value, but it might leak small amounts of
|
||||
// information about an invalid value (which constraint it failed).
|
||||
pub(super) fn scalar_from_big_endian_bytes(
|
||||
n: &Modulus<N>,
|
||||
bytes: &[u8],
|
||||
) -> Result<Scalar, error::Unspecified> {
|
||||
// [NSA Suite B Implementer's Guide to ECDSA] Appendix A.1.2, and
|
||||
// [NSA Suite B Implementer's Guide to NIST SP 800-56A] Appendix B.2,
|
||||
// "Key Pair Generation by Testing Candidates".
|
||||
//
|
||||
// [NSA Suite B Implementer's Guide to ECDSA]: doc/ecdsa.pdf
|
||||
// [NSA Suite B Implementer's Guide to NIST SP 800-56A]: doc/ecdh.pdf
|
||||
//
|
||||
// Steps 5, 6, and 7.
|
||||
//
|
||||
// XXX: The NSA guide says that we should verify that the random scalar is
|
||||
// in the range [0, n - 1) and then add one to it so that it is in the range
|
||||
// [1, n). Instead, we verify that the scalar is in the range [1, n). This
|
||||
// way, we avoid needing to compute or store the value (n - 1), we avoid the
|
||||
// need to implement a function to add one to a scalar, and we avoid needing
|
||||
// to convert the scalar back into an array of bytes.
|
||||
scalar_parse_big_endian_fixed_consttime(n, untrusted::Input::from(bytes))
|
||||
}
|
||||
|
||||
pub(super) fn public_from_private(
|
||||
ops: &PrivateKeyOps,
|
||||
public_out: &mut [u8],
|
||||
my_private_key: &ec::Seed,
|
||||
cpu: cpu::Features,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let q = &ops.common.elem_modulus(cpu);
|
||||
let elem_and_scalar_bytes = ops.common.len();
|
||||
debug_assert_eq!(public_out.len(), 1 + (2 * elem_and_scalar_bytes));
|
||||
let n = &ops.common.scalar_modulus(cpu);
|
||||
let my_private_key = private_key_as_scalar(n, my_private_key);
|
||||
let my_public_key = ops.point_mul_base(&my_private_key, cpu);
|
||||
public_out[0] = 4; // Uncompressed encoding.
|
||||
let (x_out, y_out) = public_out[1..].split_at_mut(elem_and_scalar_bytes);
|
||||
|
||||
// `big_endian_affine_from_jacobian` verifies that the point is not at
|
||||
// infinity and is on the curve.
|
||||
big_endian_affine_from_jacobian(ops, q, x_out, Some(y_out), &my_public_key)
|
||||
}
|
||||
|
||||
pub(super) fn affine_from_jacobian(
|
||||
ops: &PrivateKeyOps,
|
||||
q: &Modulus<Q>,
|
||||
p: &Point,
|
||||
) -> Result<(Elem<R>, Elem<R>), error::Unspecified> {
|
||||
let z = q.point_z(p);
|
||||
|
||||
// Since we restrict our private key to the range [1, n), the curve has
|
||||
// prime order, and we verify that the peer's point is on the curve,
|
||||
// there's no way that the result can be at infinity. But, use `assert!`
|
||||
// instead of `debug_assert!` anyway
|
||||
assert!(q.elem_verify_is_not_zero(&z).is_ok());
|
||||
|
||||
let x = q.point_x(p);
|
||||
let y = q.point_y(p);
|
||||
|
||||
let zz_inv = ops.elem_inverse_squared(q, &z);
|
||||
|
||||
let x_aff = q.elem_product(&x, &zz_inv);
|
||||
|
||||
// `y_aff` is needed to validate the point is on the curve. It is also
|
||||
// needed in the non-ECDH case where we need to output it.
|
||||
let y_aff = {
|
||||
let zzzz_inv = q.elem_squared(&zz_inv);
|
||||
let zzz_inv = q.elem_product(&z, &zzzz_inv);
|
||||
q.elem_product(&y, &zzz_inv)
|
||||
};
|
||||
|
||||
// If we validated our inputs correctly and then computed (x, y, z), then
|
||||
// (x, y, z) will be on the curve. See
|
||||
// `verify_affine_point_is_on_the_curve_scaled` for the motivation.
|
||||
verify_affine_point_is_on_the_curve(q, (&x_aff, &y_aff))?;
|
||||
|
||||
Ok((x_aff, y_aff))
|
||||
}
|
||||
|
||||
pub(super) fn big_endian_affine_from_jacobian(
|
||||
ops: &PrivateKeyOps,
|
||||
q: &Modulus<Q>,
|
||||
x_out: &mut [u8],
|
||||
y_out: Option<&mut [u8]>,
|
||||
p: &Point,
|
||||
) -> Result<(), error::Unspecified> {
|
||||
let (x_aff, y_aff) = affine_from_jacobian(ops, q, p)?;
|
||||
let x = q.elem_unencoded(&x_aff);
|
||||
limb::big_endian_from_limbs(ops.leak_limbs(&x), x_out);
|
||||
if let Some(y_out) = y_out {
|
||||
let y = q.elem_unencoded(&y_aff);
|
||||
limb::big_endian_from_limbs(ops.leak_limbs(&y), y_out);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
// Copyright 2016 Brian Smith.
|
||||
//
|
||||
// Permission to use, copy, modify, and/or distribute this software for any
|
||||
// purpose with or without fee is hereby granted, provided that the above
|
||||
// copyright notice and this permission notice appear in all copies.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
||||
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
||||
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
||||
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
//! Functionality shared by operations on public keys (ECDSA verification and
|
||||
//! ECDH agreement).
|
||||
|
||||
use super::{ops::*, verify_affine_point_is_on_the_curve};
|
||||
use crate::{arithmetic::montgomery::*, error};
|
||||
|
||||
/// Parses a public key encoded in uncompressed form. The key is validated
|
||||
/// using the ECC Partial Public-Key Validation Routine from
|
||||
/// [NIST SP 800-56A, revision 2] Section 5.6.2.3.3, the NSA's
|
||||
/// "Suite B Implementer's Guide to NIST SP 800-56A," Appendix B.3, and the
|
||||
/// NSA's "Suite B Implementer's Guide to FIPS 186-3 (ECDSA)," Appendix A.3.
|
||||
///
|
||||
/// [NIST SP 800-56A, revision 2]:
|
||||
/// http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
|
||||
pub(super) fn parse_uncompressed_point(
|
||||
ops: &PublicKeyOps,
|
||||
q: &Modulus<Q>,
|
||||
input: untrusted::Input,
|
||||
) -> Result<(Elem<R>, Elem<R>), error::Unspecified> {
|
||||
// NIST SP 800-56A Step 1: "Verify that Q is not the point at infinity.
|
||||
// This can be done by inspection if the point is entered in the standard
|
||||
// affine representation." (We do it by inspection since we only accept
|
||||
// the affine representation.)
|
||||
let (x, y) = input.read_all(error::Unspecified, |input| {
|
||||
// The encoding must be 4, which is the encoding for "uncompressed".
|
||||
let encoding = input.read_byte()?;
|
||||
if encoding != 4 {
|
||||
return Err(error::Unspecified);
|
||||
}
|
||||
|
||||
// NIST SP 800-56A Step 2: "Verify that xQ and yQ are integers in the
|
||||
// interval [0, p-1] in the case that q is an odd prime p[.]"
|
||||
let x = ops.elem_parse(q, input)?;
|
||||
let y = ops.elem_parse(q, input)?;
|
||||
Ok((x, y))
|
||||
})?;
|
||||
|
||||
// NIST SP 800-56A Step 3: "If q is an odd prime p, verify that
|
||||
// yQ**2 = xQ**3 + axQ + b in GF(p), where the arithmetic is performed
|
||||
// modulo p."
|
||||
verify_affine_point_is_on_the_curve(q, (&x, &y))?;
|
||||
|
||||
// NIST SP 800-56A Note: "Since its order is not verified, there is no
|
||||
// check that the public key is in the correct EC subgroup."
|
||||
//
|
||||
// NSA Suite B Implementer's Guide Note: "ECC Full Public-Key Validation
|
||||
// includes an additional check to ensure that the point has the correct
|
||||
// order. This check is not necessary for curves having prime order (and
|
||||
// cofactor h = 1), such as P-256 and P-384."
|
||||
|
||||
Ok((x, y))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::cpu;
|
||||
use crate::testutil as test;
|
||||
|
||||
#[test]
|
||||
fn parse_uncompressed_point_test() {
|
||||
let cpu = cpu::features();
|
||||
test::run(
|
||||
test_vector_file!("suite_b_public_key_tests.txt"),
|
||||
|section, test_case| {
|
||||
assert_eq!(section, "");
|
||||
|
||||
let curve_name = test_case.consume_string("Curve");
|
||||
|
||||
let public_key = test_case.consume_bytes("Q");
|
||||
let public_key = untrusted::Input::from(&public_key);
|
||||
let is_valid = test_case.consume_string("Result") == "P";
|
||||
|
||||
let curve_ops = public_key_ops_from_curve_name(&curve_name);
|
||||
let q = &curve_ops.common.elem_modulus(cpu);
|
||||
|
||||
let result = parse_uncompressed_point(curve_ops, q, public_key);
|
||||
assert_eq!(is_valid, result.is_ok());
|
||||
|
||||
// TODO: Verify that we when we re-serialize the parsed (x, y), the
|
||||
// output is equal to the input.
|
||||
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn public_key_ops_from_curve_name(curve_name: &str) -> &'static PublicKeyOps {
|
||||
if curve_name == "P-256" {
|
||||
&p256::PUBLIC_KEY_OPS
|
||||
} else if curve_name == "P-384" {
|
||||
&p384::PUBLIC_KEY_OPS
|
||||
} else {
|
||||
panic!("Unsupported curve: {}", curve_name);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user