Skip to content

Commit

Permalink
fix clippy + fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
makavity committed May 10, 2024
1 parent 4c56ebd commit e2cc8a3
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 53 deletions.
2 changes: 1 addition & 1 deletion bign256/src/arithmetic/scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
mod scalar_impl;

use self::scalar_impl::*;
use crate::{BignP256, FieldBytes, FieldBytesEncoding, ORDER_HEX, SecretKey, U256};
use crate::{BignP256, FieldBytes, FieldBytesEncoding, SecretKey, ORDER_HEX, U256};
use core::{
iter::{Product, Sum},
ops::{AddAssign, MulAssign, Neg, Shr, ShrAssign, SubAssign},
Expand Down
31 changes: 12 additions & 19 deletions bign256/src/ecdh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@
// use rand_core::CryptoRngCore;
// use zeroize::{Zeroize, ZeroizeOnDrop};

use core::borrow::Borrow;
use crate::{AffinePoint, FieldBytes, NonZeroScalar, ProjectivePoint, PublicKey};
use belt_hash::BeltHash;
use core::borrow::Borrow;
use elliptic_curve::point::AffineCoordinates;
use elliptic_curve::zeroize::{Zeroize, ZeroizeOnDrop};
use hkdf::Hkdf;
use hmac::SimpleHmac;
use rand_core::CryptoRngCore;
use elliptic_curve::zeroize::{Zeroize, ZeroizeOnDrop};
use crate::{AffinePoint, FieldBytes, NonZeroScalar, ProjectivePoint, PublicKey};

/// Low-level Elliptic Curve Diffie-Hellman (ECDH) function.
///
Expand All @@ -65,9 +65,9 @@ use crate::{AffinePoint, FieldBytes, NonZeroScalar, ProjectivePoint, PublicKey};
pub fn diffie_hellman(
secret_key: impl Borrow<NonZeroScalar>,
public_key: impl Borrow<AffinePoint>,
) -> SharedSecret
{
) -> SharedSecret {
let public_point = ProjectivePoint::from(*public_key.borrow());
#[allow(clippy::arithmetic_side_effects)]
let secret_point = (public_point * secret_key.borrow().as_ref()).to_affine();
SharedSecret::new(secret_point)
}
Expand All @@ -93,13 +93,11 @@ pub fn diffie_hellman(
///
/// These exchanges should be performed in the context of a protocol which
/// takes further steps to authenticate the peers in a key exchange.
pub struct EphemeralSecret
{
pub struct EphemeralSecret {
scalar: NonZeroScalar,
}

impl EphemeralSecret
{
impl EphemeralSecret {
/// Generate a cryptographically random [`EphemeralSecret`].
pub fn random(rng: &mut impl CryptoRngCore) -> Self {
Self {
Expand All @@ -121,24 +119,21 @@ impl EphemeralSecret
}
}

impl From<&EphemeralSecret> for PublicKey
{
impl From<&EphemeralSecret> for PublicKey {
fn from(ephemeral_secret: &EphemeralSecret) -> Self {
ephemeral_secret.public_key()
}
}

impl Zeroize for EphemeralSecret
{
impl Zeroize for EphemeralSecret {
fn zeroize(&mut self) {
self.scalar.zeroize()
}
}

impl ZeroizeOnDrop for EphemeralSecret {}

impl Drop for EphemeralSecret
{
impl Drop for EphemeralSecret {
fn drop(&mut self) {
self.zeroize();
}
Expand All @@ -153,8 +148,7 @@ pub struct SharedSecret {
impl SharedSecret {
/// Create a new [`SharedSecret`] from an [`AffinePoint`] for this curve.
#[inline]
fn new(point: AffinePoint) -> Self
{
fn new(point: AffinePoint) -> Self {
Self {
secret_bytes: point.x(),
}
Expand All @@ -180,8 +174,7 @@ impl SharedSecret {
/// material.
///
/// [HKDF]: https://en.wikipedia.org/wiki/HKDF
pub fn extract(&self, salt: Option<&[u8]>) -> Hkdf<BeltHash, SimpleHmac<BeltHash>>
{
pub fn extract(&self, salt: Option<&[u8]>) -> Hkdf<BeltHash, SimpleHmac<BeltHash>> {
Hkdf::new(salt, &self.secret_bytes)
}

Expand Down
4 changes: 3 additions & 1 deletion bign256/src/ecdsa/verifying.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
//! ```
use super::{Signature, BELT_OID};
use crate::{AffinePoint, BignP256, EncodedPoint, FieldBytes, Hash, ProjectivePoint, PublicKey, Scalar};
use crate::{
AffinePoint, BignP256, EncodedPoint, FieldBytes, Hash, ProjectivePoint, PublicKey, Scalar,
};
use belt_hash::{
digest::{Digest, FixedOutput},
BeltHash,
Expand Down
10 changes: 3 additions & 7 deletions bign256/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,10 @@
extern crate alloc;

pub use elliptic_curve::{self, bigint::U256};
use elliptic_curve::{
bigint::ArrayEncoding, consts::U32, Error, FieldBytesEncoding,
};
use elliptic_curve::{bigint::ArrayEncoding, consts::U32, Error, FieldBytesEncoding};

#[cfg(feature = "arithmetic")]
pub use arithmetic::{AffinePoint, ProjectivePoint, scalar::Scalar};
pub use arithmetic::{scalar::Scalar, AffinePoint, ProjectivePoint};

/// Bign256 result type
pub type Result<T> = core::result::Result<T, Error>;
Expand Down Expand Up @@ -144,8 +142,7 @@ pub type ScalarPrimitive = elliptic_curve::ScalarPrimitive<BignP256>;
/// Elliptic curve BignP256 public key.
#[cfg(feature = "arithmetic")]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PublicKey
{
pub struct PublicKey {
point: elliptic_curve::AffinePoint<BignP256>,
}

Expand All @@ -156,7 +153,6 @@ pub struct SecretKey {
inner: ScalarPrimitive,
}


/// Bit representation of a BIGN P-256 scalar field element.
#[cfg(feature = "bits")]
pub type ScalarBits = elliptic_curve::ScalarBits<BignP256>;
16 changes: 8 additions & 8 deletions bign256/src/public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ use core::fmt::Display;
use core::str::FromStr;

use elliptic_curve::{
AffinePoint,
array::Array,
CurveArithmetic,
Error, Group, point::NonIdentity, sec1::{FromEncodedPoint, ToEncodedPoint},
point::NonIdentity,
sec1::{FromEncodedPoint, ToEncodedPoint},
AffinePoint, CurveArithmetic, Error, Group,
};
use pkcs8::{
AssociatedOid,
DecodePublicKey, EncodePublicKey, ObjectIdentifier, spki::{AlgorithmIdentifier, AssociatedAlgorithmIdentifier},
spki::{AlgorithmIdentifier, AssociatedAlgorithmIdentifier},
AssociatedOid, DecodePublicKey, EncodePublicKey, ObjectIdentifier,
};

use crate::{ALGORITHM_OID, BignP256, EncodedPoint, NonZeroScalar, ProjectivePoint, PublicKey};
use crate::{BignP256, EncodedPoint, NonZeroScalar, ProjectivePoint, PublicKey, ALGORITHM_OID};

impl PublicKey {
/// Convert an [`AffinePoint`] into a [`PublicKey`]
Expand Down Expand Up @@ -71,7 +71,7 @@ impl PublicKey {
})
}
}

/// Get [`PublicKey`] from encoded point
pub fn from_encoded_point(point: EncodedPoint) -> Result<Self, Error> {
let affine = AffinePoint::<BignP256>::from_encoded_point(&point);
Expand All @@ -92,7 +92,7 @@ impl PublicKey {
bytes[33..].reverse();
bytes[1..].to_vec().into_boxed_slice()
}

#[cfg(feature = "alloc")]
/// Get encoded point from [`PublicKey`]
pub fn to_encoded_point(&self) -> EncodedPoint {
Expand Down
13 changes: 8 additions & 5 deletions bign256/src/secret_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@
use core::str::FromStr;
use der::SecretDocument;

use elliptic_curve::{array::typenum::Unsigned, Error, zeroize::Zeroizing};
use pkcs8::{AssociatedOid, DecodePrivateKey, EncodePrivateKey, ObjectIdentifier, spki::{AlgorithmIdentifier, AssociatedAlgorithmIdentifier}};
use elliptic_curve::{array::typenum::Unsigned, zeroize::Zeroizing, Error};
use pkcs8::{
spki::{AlgorithmIdentifier, AssociatedAlgorithmIdentifier},
AssociatedOid, DecodePrivateKey, EncodePrivateKey, ObjectIdentifier,
};

#[cfg(feature = "arithmetic")]
use crate::{BignP256, elliptic_curve::rand_core::CryptoRngCore, NonZeroScalar, Result};
use crate::{ALGORITHM_OID, PublicKey, ScalarPrimitive, SecretKey};
#[cfg(feature = "arithmetic")]
use crate::FieldBytes;
#[cfg(feature = "arithmetic")]
use crate::{elliptic_curve::rand_core::CryptoRngCore, BignP256, NonZeroScalar, Result};
use crate::{PublicKey, ScalarPrimitive, SecretKey, ALGORITHM_OID};

impl SecretKey {
const MIN_SIZE: usize = 24;
Expand Down
17 changes: 10 additions & 7 deletions bign256/tests/ecdh.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![cfg(feature = "ecdh")]
#[test]
fn ecdh() {
use bign256::{EncodedPoint, PublicKey, ecdh::EphemeralSecret};
use bign256::{ecdh::EphemeralSecret, EncodedPoint, PublicKey};
use rand_core::OsRng; // requires 'getrandom' feature

// Alice
Expand All @@ -13,17 +13,20 @@ fn ecdh() {
let bob_pk_bytes = EncodedPoint::from(bob_secret.public_key());

// Alice decodes Bob's serialized public key and computes a shared secret from it
let bob_public = PublicKey::from_encoded_point(bob_pk_bytes)
.expect("bob's public key is invalid!"); // In real usage, don't panic, handle this!
let bob_public =
PublicKey::from_encoded_point(bob_pk_bytes).expect("bob's public key is invalid!"); // In real usage, don't panic, handle this!

let alice_shared = alice_secret.diffie_hellman(&bob_public);

// Bob decodes Alice's serialized public key and computes the same shared secret
let alice_public = PublicKey::from_encoded_point(alice_pk_bytes)
.expect("alice's public key is invalid!"); // In real usage, don't panic, handle this!
let alice_public =
PublicKey::from_encoded_point(alice_pk_bytes).expect("alice's public key is invalid!"); // In real usage, don't panic, handle this!

let bob_shared = bob_secret.diffie_hellman(&alice_public);

// Both participants arrive on the same shared secret
assert_eq!(alice_shared.raw_secret_bytes(), bob_shared.raw_secret_bytes());
}
assert_eq!(
alice_shared.raw_secret_bytes(),
bob_shared.raw_secret_bytes()
);
}
11 changes: 6 additions & 5 deletions bign256/tests/pkcs8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,16 @@ fn decode_pkcs8_public_key_from_pem() {
fn encode_pkcs8_private_key_to_der() {
let original_secret_key = SecretKey::from_pkcs8_der(&PKCS8_PRIVATE_KEY_DER[..]).unwrap();
let reencoded_secret_key = original_secret_key.to_pkcs8_der();
assert_eq!(reencoded_secret_key.unwrap().to_bytes().to_vec(), &PKCS8_PRIVATE_KEY_DER[..]);
assert_eq!(
reencoded_secret_key.unwrap().to_bytes().to_vec(),
&PKCS8_PRIVATE_KEY_DER[..]
);
}

#[test]
#[cfg(feature = "pem")]
fn encode_pkcs8_public_key_to_der() {
let original_public_key =
PublicKey::from_public_key_der(&PKCS8_PUBLIC_KEY_DER[..]).unwrap();
let original_public_key = PublicKey::from_public_key_der(&PKCS8_PUBLIC_KEY_DER[..]).unwrap();
let reencoded_public_key = original_public_key.to_public_key_der().unwrap();
assert_eq!(reencoded_public_key.as_ref(), &PKCS8_PUBLIC_KEY_DER[..]);
}
Expand All @@ -79,8 +81,7 @@ fn encode_pkcs8_private_key_to_pem() {
#[test]
#[cfg(feature = "pem")]
fn encode_pkcs8_public_key_to_pem() {
let original_public_key =
PublicKey::from_public_key_der(&PKCS8_PUBLIC_KEY_DER[..]).unwrap();
let original_public_key = PublicKey::from_public_key_der(&PKCS8_PUBLIC_KEY_DER[..]).unwrap();
let reencoded_public_key = original_public_key.to_string();
assert_eq!(reencoded_public_key.as_str(), PKCS8_PUBLIC_KEY_PEM);
}

0 comments on commit e2cc8a3

Please sign in to comment.