Skip to content

Commit

Permalink
foramt and fix test
Browse files Browse the repository at this point in the history
  • Loading branch information
heliannuuthus committed Aug 13, 2024
1 parent 640adca commit 0f943a3
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 27 deletions.
19 changes: 11 additions & 8 deletions sm2/src/pke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,23 @@
//!
//! // Encrypting
//! let secret_key = SecretKey::random(&mut OsRng); // serialize with `::to_bytes()`
//! let encrypting_key = EncryptingKey::new_with_mode(secret_key, Mode::C1C2C3);
//! let public_key = secret_key.public_key();
//! let encrypting_key = EncryptingKey::new_with_mode(public_key, Mode::C1C2C3);
//! let plaintext = b"plaintext";
//! let ciphertext = encrypting_key.encrypt(plaintext)?;
//!
//! use sm2::pke::DecryptingKey;
//! // Decrypting
//! let decrypting_key = DecryptingKey::new_with_mode(secret_key, Mode::C1C2C3);
//! let decrypting_key = DecryptingKey::new_with_mode(secret_key.to_nonzero_scalar(), Mode::C1C2C3);
//! assert_eq!(decrypting_key.decrypt(&ciphertext)?, plaintext);
//!
//! // Encrypting asn.1
//! let ciphertext = encrypting_key.encrypt_asna1(plaintext)?;
//!
//! // Decrypting asn.1
//! assert_eq!(decrypting_key.decrypt_asna1(&ciphertext)?, plaintext);
//!
//! Ok(())
//! # }
//! ```
//!
Expand Down Expand Up @@ -92,15 +95,15 @@ impl<'a> EncodeValue for Cipher<'a> {
fn value_len(&self) -> elliptic_curve::pkcs8::der::Result<Length> {
UintRef::new(&self.x.to_be_bytes())?.encoded_len()?
+ UintRef::new(&self.y.to_be_bytes())?.encoded_len()?
+ OctetStringRef::new(&self.digest)?.encoded_len()?
+ OctetStringRef::new(&self.cipher)?.encoded_len()?
+ OctetStringRef::new(self.digest)?.encoded_len()?
+ OctetStringRef::new(self.cipher)?.encoded_len()?
}

fn encode_value(&self, writer: &mut impl Writer) -> elliptic_curve::pkcs8::der::Result<()> {
UintRef::new(&self.x.to_be_bytes())?.encode(writer)?;
UintRef::new(&self.y.to_be_bytes())?.encode(writer)?;
OctetStringRef::new(&self.digest)?.encode(writer)?;
OctetStringRef::new(&self.cipher)?.encode(writer)?;
OctetStringRef::new(self.digest)?.encode(writer)?;
OctetStringRef::new(self.cipher)?.encode(writer)?;
Ok(())
}
}
Expand Down Expand Up @@ -137,8 +140,8 @@ fn kdf(hasher: &mut dyn DynDigest, kpb: AffinePoint, c2: &mut [u8]) -> Result<()
let encode_point = kpb.to_encoded_point(false);

while offset < klen {
hasher.update(encode_point.x().unwrap());
hasher.update(encode_point.y().unwrap());
hasher.update(encode_point.x().ok_or(elliptic_curve::Error)?);
hasher.update(encode_point.y().ok_or(elliptic_curve::Error)?);
hasher.update(&ct.to_be_bytes());

hasher
Expand Down
15 changes: 7 additions & 8 deletions sm2/src/pke/decrypting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,17 +107,16 @@ impl DecryptingKey {
where
D: 'static + Digest + DynDigest + Send + Sync,
{
let cipher =
Cipher::from_der(&ciphertext).map_err(|e| elliptic_curve::pkcs8::Error::from(e))?;
let cipher = Cipher::from_der(ciphertext).map_err(elliptic_curve::pkcs8::Error::from)?;
let prefix: &[u8] = &[0x04];
let x: [u8; 32] = cipher.x.to_be_bytes();
let y: [u8; 32] = cipher.y.to_be_bytes();
let mut cipher = match self.mode {
let cipher = match self.mode {
Mode::C1C2C3 => [prefix, &x, &y, cipher.cipher, cipher.digest].concat(),
Mode::C1C3C2 => [prefix, &x, &y, cipher.digest, cipher.cipher].concat(),
};

Ok(self.decrypt_digest::<D>(&mut cipher)?.to_vec())
Ok(self.decrypt_digest::<D>(&cipher)?.to_vec())
}
}

Expand Down Expand Up @@ -165,7 +164,7 @@ fn decrypt(

// B1: get 𝐶1 from 𝐶
let (c1, c) = cipher.split_at(c1_len as usize);
let encoded_c1 = EncodedPoint::from_bytes(c1).unwrap();
let encoded_c1 = EncodedPoint::from_bytes(c1).map_err(Error::from)?;

// verify that point c1 satisfies the elliptic curve
let mut c1_point = AffinePoint::from_encoded_point(&encoded_c1).unwrap();
Expand Down Expand Up @@ -195,9 +194,9 @@ fn decrypt(
// compute 𝑢 = 𝐻𝑎𝑠ℎ(𝑥2 ∥ 𝑀′∥ 𝑦2).
let mut u = vec![0u8; digest_size];
let encode_point = c1_point.to_encoded_point(false);
hasher.update(&encode_point.x().unwrap());
hasher.update(&mut c2);
hasher.update(&encode_point.y().unwrap());
hasher.update(encode_point.x().ok_or(Error)?);
hasher.update(&c2);
hasher.update(encode_point.y().ok_or(Error)?);
hasher.finalize_into_reset(&mut u).map_err(|_e| Error)?;
let checked = u
.iter()
Expand Down
10 changes: 5 additions & 5 deletions sm2/src/pke/encrypting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ impl EncryptingKey {
cipher,
}
.to_der()
.map_err(|e| elliptic_curve::pkcs8::Error::from(e))?)
.map_err(elliptic_curve::pkcs8::Error::from)?)
}
}

Expand Down Expand Up @@ -158,7 +158,7 @@ fn encrypt(
}

// A4: compute point [𝑘]𝑃𝐵 = (𝑥2, 𝑦2)
hpb = (s * &k).to_affine();
hpb = (s * k).to_affine();

// A5: compute 𝑡 = 𝐾𝐷𝐹(𝑥2||𝑦2, 𝑘𝑙𝑒𝑛)
// A6: compute 𝐶2 = 𝑀 ⊕ t
Expand All @@ -176,9 +176,9 @@ fn encrypt(

// A7: compute 𝐶3 = 𝐻𝑎𝑠ℎ(𝑥2||𝑀||𝑦2)
let mut c3 = vec![0; digest.output_size()];
digest.update(encode_point.x().unwrap());
digest.update(encode_point.x().ok_or(Error)?);
digest.update(msg);
digest.update(encode_point.y().unwrap());
digest.update(encode_point.y().ok_or(Error)?);
digest.finalize_into_reset(&mut c3).map_err(|_e| Error)?;

// A8: output the ciphertext 𝐶 = 𝐶1||𝐶2||𝐶3.
Expand All @@ -188,7 +188,7 @@ fn encrypt(
})
}

fn next_k(bit_length: u32) -> Uint<4> {
fn next_k(bit_length: u32) -> U256 {
loop {
let k = U256::random_bits(&mut rand_core::OsRng, bit_length);
if k.is_zero().unwrap_u8() == 0 && k <= Sm2::ORDER {
Expand Down
11 changes: 5 additions & 6 deletions sm2/tests/sm2pke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,13 @@ const ASN1_CIPHER: [u8; 116] = hex!("307202206ba17ad462a75beeb2caf8a1282687ab7e2

#[test]
fn decrypt_verify() {
let mut cipher = Vec::from(&CIPHER);
assert_eq!(
DecryptingKey::new(
NonZeroScalar::<Sm2>::try_from(PRIVATE_KEY.as_ref() as &[u8])
.unwrap()
.into()
)
.decrypt(&mut cipher)
.decrypt(&CIPHER)
.unwrap(),
MSG
);
Expand Down Expand Up @@ -73,16 +72,16 @@ proptest! {
#[test]
fn encrypt_and_decrpyt(dk in decrypting_key()) {
let ek = dk.encrypting_key();
let mut cipher_bytes = ek.encrypt(MSG).unwrap();
assert_eq!(dk.decrypt(&mut cipher_bytes).unwrap(), MSG);
let cipher_bytes = ek.encrypt(MSG).unwrap();
assert_eq!(dk.decrypt(&cipher_bytes).unwrap(), MSG);
}

#[test]
fn encrypt_and_decrpyt_mode(dk in decrypting_key_c1c2c3()) {
let ek = dk.encrypting_key();
let mut cipher_bytes = ek.encrypt(MSG).unwrap();
let cipher_bytes = ek.encrypt(MSG).unwrap();
assert_eq!(
dk.decrypt(&mut cipher_bytes)
dk.decrypt(&cipher_bytes)
.unwrap(),
MSG
);
Expand Down

0 comments on commit 0f943a3

Please sign in to comment.