Skip to content

Commit

Permalink
v0.3.2
Browse files Browse the repository at this point in the history
update README.md
use sm9_core 0.4.0
  • Loading branch information
CadenzaYu committed Nov 4, 2024
1 parent 9714c52 commit fc66a9f
Show file tree
Hide file tree
Showing 6 changed files with 77 additions and 41 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "sm9"
version = "0.3.0"
version = "0.3.2"
edition = "2021"
authors = ["John Yu <cb8866@sina.com>"]
description = "SM9 (OSCCA GM/T 0044-2016), identity-based cryptography"
Expand All @@ -18,7 +18,7 @@ sec1 = { version = "0.7.3", features = ["alloc", "pem", "std"] }
sm3 = "0.4.2"
hmac = "0.12.1"
signature = "2.2.0"
sm9_core = "0.3.7"
sm9_core = "0.4.0"
hex-literal = "0.4"
kem = "0.2.0"
zeroize = { version = "1.8.1", features = ["zeroize_derive"] }
Expand Down
59 changes: 56 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ Add the `sm9` crate to your dependencies in `Cargo.toml`

```toml
[dependencies]
sm9 = "0.3.0"
sm9 = "0.3.2"
```

### Examples

#### Example1: Encrypt
(See `encryption.rs` for the full example.)

```rust
Expand Down Expand Up @@ -43,11 +44,13 @@ sm9 = "0.3.0"

```

#### Example2: Signature
(See `signature.rs` for the full example.)

```rust
use sm9::*;


//Sign
let m = b"Chinese IBS standard";
let user_id = b"Alice";
let sig = Sm9::sign(
Expand All @@ -58,12 +61,18 @@ sm9 = "0.3.0"
println!("{:02X?}", sig.h_as_ref());
println!("{:02X?}", sig.s_as_ref());

//Verify
let mut bytes = Vec::<u8>::new();
bytes.extend_from_slice(sig.h_as_ref());
bytes.extend_from_slice(sig.s_as_ref());
let sig_rev = Signature::from_slice(bytes.as_ref()).unwrap();
assert!(Sm9::verify(
"master_signature_public_key.pem",
user_id,
m,
&sig
&sig_rev
));

use std::fs;
let master_signature_public_key = fs::read_to_string("master_signature_public_key.pem")
.expect("read master_signature_public_key.pem error");
Expand All @@ -79,6 +88,50 @@ sm9 = "0.3.0"

```

#### Example3: Key Exchange
(See `exchange.rs` for the full example.)

```rust
use sm9::*;
let mpk = MasterPublicKey::read_pem_file("master_exchange_public_key.pem")
.expect("read master_public_key_file error");
let alice_id = b"Alice";
let alice_key = UserPrivateKey::read_pem_file("alice_exchange_private_key.pem")
.expect("read user_privte_key_file error");
let bob_id = b"Bob";
let bob_key = UserPrivateKey::read_pem_file("bob_exchange_private_key.pem")
.expect("read user_privte_key_file error");
// the initiator A
let mut initiator = KeyExchanger::new(alice_id, &alice_key, &mpk, true).unwrap();
// the responder B
let mut responder = KeyExchanger::new(bob_id, &bob_key, &mpk, false).unwrap();
// A Step 3: compute 𝑅𝐴
let ra = initiator.generate_ephemeral_secret(bob_id).unwrap();
// A Step 4: send 𝑅𝐴 to B

// B Step 3: compute 𝑅B
let rb = responder.generate_ephemeral_secret(alice_id).unwrap();
// B Step 4: send 𝑅B to A
// A compute shared_secret use received rb
let rb_received = EphemeralSecret::from_slice(rb.as_slice());
let ska = initiator.generate_shared_secret(&rb_received).unwrap();
// B compute shared_secret use received ra
let ra_received = EphemeralSecret::from_slice(ra.as_slice());
let skb = responder.generate_shared_secret(&ra_received).unwrap();
assert_eq!(ska, skb);
// B Step 6: (optional) compute SB, and send it to A
let sb = responder.generate_comfirmable_secret().unwrap();
// A (optional) confirmation from B to A
let sb_received = ComfirmableSecret::from_slice(sb.as_slice());
let confirmation_a = initiator.comfirm(&sb_received).unwrap();
// A Step 8: (optional) compute 𝑆𝐴, and send it to B,
let sa = initiator.generate_comfirmable_secret().unwrap();
// B (optional) confirmation from A to B
let sa_received = ComfirmableSecret::from_slice(sa.as_slice());
let confirmation_b = responder.comfirm(&sa_received).unwrap();
assert!(confirmation_a);
assert!(confirmation_b);
```
## License

Licensed under either of
Expand Down
26 changes: 6 additions & 20 deletions src/exchanging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,7 @@ impl KeyExchanger {
let mut z = Vec::<u8>::new();
z.extend_from_slice(peer_id);
z.push(SM9_HID_ENC);
println!("𝐼𝐷𝐵∥ℎ𝑖𝑑 {:02X?}", z);
let h1 = Sm9::hash_1(z.as_slice()).unwrap();
println!("{:02X?}", h1);
let g1 = G1::one() * h1;
let pube = self.public_key.to_g1().ok_or(Error).unwrap();
let q = g1 + pube;
Expand All @@ -132,7 +130,6 @@ impl KeyExchanger {
self.r = r;
//Step 3: compute 𝑅𝐴=[𝑟𝐴]𝑄𝐵
let ra = (r * q).to_slice();
println!("ra: {:02X?}", ra);
self.ra = EphemeralSecret::from_slice(ra.as_ref());
Ok(self.ra.clone())
}
Expand All @@ -154,10 +151,7 @@ impl KeyExchanger {
z.extend(&self.peer_id);
z.extend_from_slice(self.ra.as_slice());
z.extend_from_slice(self.rb.as_slice());
z.extend_from_slice(g1.to_slice().as_ref());
z.extend_from_slice(g2.to_slice().as_ref());
z.extend_from_slice(g3.to_slice().as_ref());

z.extend_from_slice(&[g1.to_slice(), g2.to_slice(), g3.to_slice()].concat());
sk = Sm9::kdf(z.as_ref(), 16).expect("klen maybe error");
//𝑆1 = 𝐻𝑣(0x82 ∥ 𝑔1′∥ 𝐻𝑣(𝑔2′∥ 𝑔3′∥ 𝐼𝐷𝐴 ∥ 𝐼𝐷𝐵 ∥𝑅𝐴 ∥ 𝑅𝐵))
let mut u = Vec::<u8>::new();
Expand All @@ -177,17 +171,13 @@ impl KeyExchanger {
sm3.update([0x82u8]);
sm3.update(v.clone());
let ha = sm3.finalize();
println!("s1: {:02X?}", ha.as_slice());
self.s1 = ComfirmableSecret::from_slice(ha.as_slice());
//𝑆1 = 𝐻𝑣(0x83 ∥ 𝑔1′∥ 𝐻𝑣(𝑔2′∥ 𝑔3′∥ 𝐼𝐷𝐴 ∥ 𝐼𝐷𝐵 ∥𝑅𝐴 ∥ 𝑅𝐵))
//𝑆2 = 𝐻𝑣(0x83 ∥ 𝑔1′∥ 𝐻𝑣(𝑔2′∥ 𝑔3′∥ 𝐼𝐷𝐴 ∥ 𝐼𝐷𝐵 ∥𝑅𝐴 ∥ 𝑅𝐵))
let mut sm3 = Sm3::new();
sm3.update([0x83u8]);
sm3.update(v);
let ha = sm3.finalize();
println!("s2: {:02X?}", ha.as_slice());
self.s2 = ComfirmableSecret::from_slice(ha.as_slice());

println!("sk: {:02X?}", sk);
} else {
self.rb = EphemeralSecret::new(es.0);
let rb = G1::from_slice(self.rb.as_slice()).unwrap();
Expand All @@ -200,9 +190,7 @@ impl KeyExchanger {
z.extend(&self.user_id);
z.extend_from_slice(self.rb.as_slice());
z.extend_from_slice(self.ra.as_slice());
z.extend_from_slice(g1.to_slice().as_ref());
z.extend_from_slice(g2.to_slice().as_ref());
z.extend_from_slice(g3.to_slice().as_ref());
z.extend_from_slice(&[g1.to_slice(), g2.to_slice(), g3.to_slice()].concat());

sk = Sm9::kdf(z.as_ref(), 16).expect("klen maybe error");
//𝑆1 = 𝐻𝑣(0x82 ∥ 𝑔1′∥ 𝐻𝑣(𝑔2′∥ 𝑔3′∥ 𝐼𝐷𝐴 ∥ 𝐼𝐷𝐵 ∥𝑅𝐴 ∥ 𝑅𝐵))
Expand All @@ -223,23 +211,20 @@ impl KeyExchanger {
sm3.update([0x82u8]);
sm3.update(v.clone());
let ha = sm3.finalize();
println!("s1: {:02X?}", ha.as_slice());
self.s1 = ComfirmableSecret::from_slice(ha.as_slice());
//𝑆1 = 𝐻𝑣(0x83 ∥ 𝑔1′∥ 𝐻𝑣(𝑔2′∥ 𝑔3′∥ 𝐼𝐷𝐴 ∥ 𝐼𝐷𝐵 ∥𝑅𝐴 ∥ 𝑅𝐵))
//𝑆2 = 𝐻𝑣(0x83 ∥ 𝑔1′∥ 𝐻𝑣(𝑔2′∥ 𝑔3′∥ 𝐼𝐷𝐴 ∥ 𝐼𝐷𝐵 ∥𝑅𝐴 ∥ 𝑅𝐵))
let mut sm3 = Sm3::new();
sm3.update([0x83u8]);
sm3.update(v);
let ha = sm3.finalize();
println!("s2: {:02X?}", ha.as_slice());
self.s2 = ComfirmableSecret::from_slice(ha.as_slice());

println!("sk: {:02X?}", sk);
}
Ok(SharedSecret::from_slice(sk.as_ref()))
}
}
pub fn generate_comfirmable_secret(&self) -> Result<ComfirmableSecret, Error> {
if self.s1 == ComfirmableSecret::default() {
// call generate_shared_secret first
Err(Error)
} else if self.is_initiator {
Ok(self.s2.clone())
Expand All @@ -249,6 +234,7 @@ impl KeyExchanger {
}
pub fn comfirm(&self, cs: &ComfirmableSecret) -> Result<bool, Error> {
if self.s1 == ComfirmableSecret::default() {
// call generate_shared_secret first
Err(Error)
} else if self.is_initiator {
Ok(self.s1 == *cs)
Expand Down
20 changes: 6 additions & 14 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ pub struct Signature(
// (h, s)
pub(crate) [u8; Signature::BYTE_SIZE],
);
impl Default for Signature {
fn default() -> Self {
Self([0u8; Signature::BYTE_SIZE])
}
}
impl Signature {
/// Size of an encoded SM9 signature in bytes.
pub const BYTE_SIZE: usize = 32 + 65;
Expand All @@ -48,7 +53,7 @@ impl Signature {
if h.len() != 32 || s.len() != 65 {
None
} else {
let mut sig = Signature([0u8; Self::BYTE_SIZE]);
let mut sig = Signature::default();
sig.0[..32].copy_from_slice(h);
sig.0[32..].copy_from_slice(s);
Some(sig)
Expand Down Expand Up @@ -373,7 +378,6 @@ mod tests {
z.push(hid);
let a = Sm9::hash_1(z.as_slice()).unwrap();
let ex = hex!("9CB1F628 8CE0E510 43CE7234 4582FFC3 01E0A812 A7F5F200 4B85547A 24B82716");
println!("{:?}", a);
assert_eq!(a.to_slice(), ex);
}
#[test]
Expand All @@ -399,7 +403,6 @@ mod tests {
);
let k = hex!("4FF5CF86 D2AD40C8 F4BAC98D 76ABDBDE 0C0E2F0A 829D3F91 1EF5B2BC E0695480");
let d = Sm9::kdf(&r0, 32).unwrap();
println!("{:02X?}", d);
assert_eq!(k, d.as_slice())
}
#[test]
Expand All @@ -408,15 +411,13 @@ mod tests {
// Annex C: example of key encapsulation mechanism
fn test_bob_privte_key_from_pem() {
let a = UserPrivateKey::read_pem_file("bob_private_key.pem").unwrap();
println!("{:02X?}", a);
let de = a.to_g2().expect("UserPrivateKey error");
let b = hex!(
"94736ACD 2C8C8796 CC4785E9 38301A13 9A059D35 37B64141 40B2D31E ECF41683"
"115BAE85 F5D8BC6C 3DBD9E53 42979ACC CF3C2F4F 28420B1C B4F8C0B5 9A19B158"
"7AA5E475 70DA7600 CD760A0C F7BEAF71 C447F384 4753FE74 FA7BA92C A7D3B55F"
"27538A62 E7F7BFB5 1DCE0870 4796D94C 9D56734F 119EA447 32B50E31 CDEB75C1"
);
println!("{:02X?}", de);
assert_eq!(de.to_slice(), b);
}
#[test]
Expand All @@ -425,7 +426,6 @@ mod tests {
// Annex C: example of key encapsulation mechanism
fn test_master_public_key_from_pem() {
let a = MasterPublicKey::read_pem_file("master_public_key.pem").unwrap();
println!("{:02X?}", a);
let pube = a.to_g1().expect("MasterPublicKey error");
let b = hex!(
"787ED7B8 A51F3AB8 4E0A6600 3F32DA5C 720B17EC A7137D39 ABC66E3C 80A892FF"
Expand All @@ -440,7 +440,6 @@ mod tests {
fn test_master_private_key_from_pem() {
let a = MasterPrivateKey::read_pem_file("master_private_key.pem")
.expect("MasterPrivateKey read_pem_file error!");
println!("{:02X?}", a);
assert_eq!(
a.as_slice(),
&hex!("0001EDEE 3778F441 F8DEA3D9 FA0ACC4E 07EE36C9 3F9A0861 8AF4AD85 CEDE1C22")
Expand All @@ -453,7 +452,6 @@ mod tests {
fn test_master_signature_private_key() {
let a = MasterPrivateKey::read_pem_file("master_signature_private_key.pem")
.expect("MasterPrivateKey read_pem_file error!");
println!("{:02X?}", a);
assert_eq!(
a.as_slice(),
&hex!("000130E7 8459D785 45CB54C5 87E02CF4 80CE0B66 340F319F 348A1D5B 1F2DC5F4")
Expand All @@ -466,15 +464,13 @@ mod tests {
fn test_master_signature_public_key() {
let a = MasterSignaturePublicKey::read_pem_file("master_signature_public_key.pem")
.expect("MasterSignaturePublicKey read_pem_file error!");
println!("{:02X?}", a);
let pub_s = a.to_g2().expect("MasterSignaturePublicKey error");
let b = hex!(
"9F64080B 3084F733 E48AFF4B 41B56501 1CE0711C 5E392CFB 0AB1B679 1B94C408"
"29DBA116 152D1F78 6CE843ED 24A3B573 414D2177 386A92DD 8F14D656 96EA5E32"
"69850938 ABEA0112 B57329F4 47E3A0CB AD3E2FDB 1A77F335 E89E1408 D0EF1C25"
"41E00A53 DDA532DA 1A7CE027 B7A46F74 1006E85F 5CDFF073 0E75C05F B4E3216D"
);
println!("{:02X?}", pub_s);
assert_eq!(pub_s.to_slice(), b);
}
#[test]
Expand All @@ -484,13 +480,11 @@ mod tests {
fn test_alice_signature_private_key() {
let a = UserSignaturePrivateKey::read_pem_file("alice_signature_private_key.pem")
.expect("UserSignaturePrivateKey read_pem_file error!");
println!("{:02X?}", a);
let pub_s = a.to_g1().expect("UserSignaturePrivateKey error");
let b = hex!(
"A5702F05 CF131530 5E2D6EB6 4B0DEB92 3DB1A0BC F0CAFF90 523AC875 4AA69820"
"78559A84 4411F982 5C109F5E E3F52D72 0DD01785 392A727B B1556952 B2B013D3"
);
println!("{:02X?}", pub_s);
assert_eq!(pub_s.to_slice(), b);
}
#[test]
Expand All @@ -502,8 +496,6 @@ mod tests {
pk_recip[..3].copy_from_slice(usr_id);
let mut rng = OsRng;
let (ek, ss1) = encapper.try_encap(&mut rng, &pk_recip).unwrap();
println!("Sm9EncappedKey:{:02X?}", ek.as_ref());
println!("Sm9SharedSecret:{:02X?}", ss1.as_bytes());
let mut z = Vec::<u8>::new();
z.extend_from_slice(ek.as_ref());
z.extend_from_slice(ss1.as_bytes());
Expand Down
2 changes: 1 addition & 1 deletion tests/exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ fn test_key_exchange() {
// B compute shared_secret use received ra
let ra_received = EphemeralSecret::from_slice(ra.as_slice());
let skb = responder.generate_shared_secret(&ra_received).unwrap();
assert_eq!(ska, skb);
// B Step 6: (optional) compute SB, and send it to A
let sb = responder.generate_comfirmable_secret().unwrap();
// A (optional) confirmation from B to A
Expand All @@ -44,5 +45,4 @@ fn test_key_exchange() {
let confirmation_b = responder.comfirm(&sa_received).unwrap();
assert!(confirmation_a);
assert!(confirmation_b);
assert_eq!(ska, skb);
}
7 changes: 6 additions & 1 deletion tests/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,16 @@ fn test_signature_verify() {
println!("{:02X?}", sig.h_as_ref());
println!("{:02X?}", sig.s_as_ref());

//Verify
let mut bytes = Vec::<u8>::new();
bytes.extend_from_slice(sig.h_as_ref());
bytes.extend_from_slice(sig.s_as_ref());
let sig_rev = Signature::from_slice(bytes.as_ref()).unwrap();
assert!(Sm9::verify(
"master_signature_public_key.pem",
user_id,
m,
&sig
&sig_rev
));
}
#[test]
Expand Down

0 comments on commit fc66a9f

Please sign in to comment.