Skip to content

Commit c164da2

Browse files
authored
Merge pull request #14 from Pencil-Yao/update_error
Update error
2 parents 666bb26 + 3b49d5b commit c164da2

File tree

9 files changed

+70
-105
lines changed

9 files changed

+70
-105
lines changed

Cargo.toml

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
[package]
22
name = "efficient-sm2"
3-
version = "0.1.5"
3+
version = "0.1.6"
44
authors = ["yieazy <yuitta@163.com>"]
55
description = "A Rust Library of China's Standards of Signature Algorithms (SM2)"
66
documentation = "https://mock.icu/efficient-sm2"
7-
edition = "2018"
7+
edition = "2021"
88
keywords = ["sm2", "cryptography", "performance"]
99
license = "Apache-2.0"
1010
repository = "https://github.com/Pencil-Yao/efficient-sm2"
@@ -13,12 +13,12 @@ repository = "https://github.com/Pencil-Yao/efficient-sm2"
1313

1414
[dependencies]
1515
rand = "0.8"
16-
libsm = "0.4"
16+
libsm = "0.5"
1717

1818
[dev-dependencies]
19-
hex = "0.3"
20-
num-bigint = "0.2"
21-
num-traits = "0.2.11"
19+
hex = "0.4"
20+
num-bigint = "0.4"
21+
num-traits = "0.2"
2222

2323
[features]
2424
internal_benches = []

src/ec/signing.rs

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::elem::{
1717
elem_reduced_to_scalar, elem_to_unencoded, scalar_add, scalar_inv_to_mont, scalar_mul,
1818
scalar_sub, scalar_to_unencoded, Elem, Scalar, R,
1919
};
20-
use crate::err::KeyRejected;
20+
use crate::err::KeyRejectedError;
2121
use crate::jacobian::exchange::affine_from_jacobian;
2222
use crate::key::private::create_private_key;
2323
use crate::key::public::PublicKey;
@@ -34,7 +34,7 @@ pub struct KeyPair {
3434
}
3535

3636
impl KeyPair {
37-
pub fn new(private_key: &[u8]) -> Result<Self, KeyRejected> {
37+
pub fn new(private_key: &[u8]) -> Result<Self, KeyRejectedError> {
3838
let mut key_limb = [0; LIMB_LENGTH];
3939
parse_big_endian(&mut key_limb, private_key)?;
4040
let d = Scalar {
@@ -49,12 +49,14 @@ impl KeyPair {
4949
self.pk
5050
}
5151

52-
pub fn sign(&self, message: &[u8]) -> Result<Signature, KeyRejected> {
52+
pub fn sign(&self, message: &[u8]) -> Result<Signature, KeyRejectedError> {
5353
let ctx = libsm::sm2::signature::SigCtx::new();
5454
let pk_point = ctx
5555
.load_pubkey(self.pk.bytes_less_safe())
56-
.map_err(|_| KeyRejected::sign_error())?;
57-
let digest = ctx.hash("1234567812345678", &pk_point, message);
56+
.map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
57+
let digest = ctx
58+
.hash("1234567812345678", &pk_point, message)
59+
.map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
5860

5961
self.sign_digest(&mut DefaultRand(rand::thread_rng()), &digest)
6062
}
@@ -63,12 +65,14 @@ impl KeyPair {
6365
&self,
6466
rng: &mut dyn SecureRandom,
6567
message: &[u8],
66-
) -> Result<Signature, KeyRejected> {
68+
) -> Result<Signature, KeyRejectedError> {
6769
let ctx = libsm::sm2::signature::SigCtx::new();
6870
let pk_point = ctx
6971
.load_pubkey(self.pk.bytes_less_safe())
70-
.map_err(|_| KeyRejected::sign_error())?;
71-
let digest = ctx.hash("1234567812345678", &pk_point, message);
72+
.map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
73+
let digest = ctx
74+
.hash("1234567812345678", &pk_point, message)
75+
.map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
7276

7377
self.sign_digest(rng, &digest)
7478
}
@@ -77,7 +81,7 @@ impl KeyPair {
7781
&self,
7882
rng: &mut dyn SecureRandom,
7983
digest: &[u8],
80-
) -> Result<Signature, KeyRejected> {
84+
) -> Result<Signature, KeyRejectedError> {
8185
for _ in 0..100 {
8286
#[allow(unused_variables)]
8387
let rk = create_private_key(rng)?;
@@ -153,7 +157,7 @@ impl KeyPair {
153157

154158
return Ok(Signature::from_scalars(r, s));
155159
}
156-
Err(KeyRejected::sign_digest_error())
160+
Err(KeyRejectedError::SignDigestFailed)
157161
}
158162
}
159163

@@ -171,24 +175,31 @@ mod tests {
171175

172176
let sig = key_pair.sign(test_word).unwrap();
173177

178+
println!(
179+
"pk: {}, r: {}, s: {}",
180+
hex::encode(key_pair.pk.bytes_less_safe()),
181+
hex::encode(&sig.r()),
182+
hex::encode(&sig.s())
183+
);
184+
174185
sig.verify(&key_pair.public_key(), test_word).unwrap()
175186
}
176187

177188
#[test]
178189
fn free_input_verify() {
179-
let msg = b"abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd";
190+
let msg = b"hello world";
180191

181192
let pk = PublicKey::new(
182-
&hex::decode("0259e738b6e8a699ad38011a85fc59f35a83ed6c287d944e8401c9b6e8793d0a")
193+
&hex::decode("B0E4E03D589C97375BBD6EA49483DD976FB88BBB0C07C72827CD8808B5794D5E")
183194
.unwrap(),
184-
&hex::decode("71c19ebd9a5750eb4ca1bb68f9b42057c5f25666385197f44544f97e2f4472c1")
195+
&hex::decode("2881721E8D9BF56E81FC1E0C325F4FFC052E67FC3A31510D66E7B8749B93B636")
185196
.unwrap(),
186197
);
187198

188199
let sig = Signature::new(
189-
&hex::decode("b027c1d33771a1f693f07dec8d952b7c72afeff08fe3c05358610edbe8a1953e")
200+
&hex::decode("45FACCE4BDE9B8A34D43E6060210928802878DDD86A6EAE2938313A165F9F100")
190201
.unwrap(),
191-
&hex::decode("99e911d3dc93381ba40c87e5c577ccbb855ea153ce25ef5022618c0af3c3bff3")
202+
&hex::decode("D9656DA4EC90FB2EFA399C0ECC6301882CA3301925281C58C2E29D9FD6F9C221")
192203
.unwrap(),
193204
)
194205
.unwrap();
@@ -231,7 +242,7 @@ mod sign_bench {
231242
fn libsm_sign_bench(bench: &mut test::Bencher) {
232243
let test_word = b"hello world";
233244
let ctx = libsm::sm2::signature::SigCtx::new();
234-
let (pk, sk) = ctx.new_keypair();
245+
let (pk, sk) = ctx.new_keypair().unwrap();
235246

236247
bench.iter(|| {
237248
let _ = ctx.sign(test_word, &sk, &pk);
@@ -265,8 +276,8 @@ mod sign_bench {
265276
fn libsm_verify_bench(bench: &mut test::Bencher) {
266277
let test_word = b"hello world";
267278
let ctx = libsm::sm2::signature::SigCtx::new();
268-
let (pk, sk) = ctx.new_keypair();
269-
let sig = ctx.sign(test_word, &sk, &pk);
279+
let (pk, sk) = ctx.new_keypair().unwrap();
280+
let sig = ctx.sign(test_word, &sk, &pk).unwrap();
270281

271282
bench.iter(|| {
272283
let _ = ctx.verify(test_word, &pk, &sig);

src/ec/verification.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::elem::{
1616
elem_mul, elem_reduced_to_scalar, elem_to_unencoded, point_x, point_z, scalar_add, scalar_sub,
1717
scalar_to_elem, twin_mul, Elem, Scalar, Unencoded,
1818
};
19-
use crate::err::KeyRejected;
19+
use crate::err::KeyRejectedError;
2020
use crate::jacobian::exchange::verify_jacobian_point_is_on_the_curve;
2121
use crate::key::public::PublicKey;
2222
use crate::limb::{Limb, LIMB_BYTES, LIMB_LENGTH};
@@ -30,7 +30,7 @@ pub struct Signature {
3030
}
3131

3232
impl Signature {
33-
pub fn new(r: &[u8], s: &[u8]) -> Result<Self, KeyRejected> {
33+
pub fn new(r: &[u8], s: &[u8]) -> Result<Self, KeyRejectedError> {
3434
let mut rl = [0; LIMB_LENGTH];
3535
parse_big_endian(&mut rl, r)?;
3636
let r = Scalar {
@@ -64,17 +64,19 @@ impl Signature {
6464
s_out
6565
}
6666

67-
pub fn verify(&self, pk: &PublicKey, msg: &[u8]) -> Result<(), KeyRejected> {
67+
pub fn verify(&self, pk: &PublicKey, msg: &[u8]) -> Result<(), KeyRejectedError> {
6868
let ctx = libsm::sm2::signature::SigCtx::new();
6969
let pk_point = ctx
7070
.load_pubkey(pk.bytes_less_safe())
71-
.map_err(|_| KeyRejected::verify_error())?;
72-
let digest = ctx.hash("1234567812345678", &pk_point, msg);
71+
.map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
72+
let digest = ctx
73+
.hash("1234567812345678", &pk_point, msg)
74+
.map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
7375

7476
self.verify_digest(pk, &digest)
7577
}
7678

77-
pub fn verify_digest(&self, pk: &PublicKey, digest: &[u8]) -> Result<(), KeyRejected> {
79+
pub fn verify_digest(&self, pk: &PublicKey, digest: &[u8]) -> Result<(), KeyRejectedError> {
7880
let mut dl = [0; LIMB_LENGTH];
7981
parse_big_endian(&mut dl, digest)?;
8082
let edl = Elem {
@@ -103,6 +105,6 @@ impl Signature {
103105
if sig_r_equals_x(&r, &point) {
104106
return Ok(());
105107
}
106-
Err(KeyRejected::verify_digest_error())
108+
Err(KeyRejectedError::VerifyDigestFailed)
107109
}
108110
}

src/err.rs

Lines changed: 10 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
1717
/// An error parsing or validating a key.
1818
///
19-
/// The `Display` implementation and `<KeyRejected as Error>::description()`
19+
/// The `Display` implementation and `<KeyRejectedError as Error>::description()`
2020
/// will return a string that will help you better understand why a key was
2121
/// rejected change which errors are reported in which situations while
2222
/// minimizing the likelihood that any applications will be broken.
@@ -45,61 +45,13 @@
4545
///
4646
/// * Unexpected errors: Report this as a bug.
4747
48-
#[derive(Copy, Clone, Debug)]
49-
pub struct KeyRejected(&'static str);
50-
51-
impl KeyRejected {
52-
/// The value returned from <Self as std::error::Error>::description()
53-
pub fn description_(&self) -> &'static str {
54-
self.0
55-
}
56-
57-
pub(crate) fn unexpected_error() -> Self {
58-
KeyRejected("UnexpectedError")
59-
}
60-
61-
pub(crate) fn seed_error() -> Self {
62-
KeyRejected("SeedOperationFailed")
63-
}
64-
65-
pub(crate) fn sign_digest_error() -> Self {
66-
KeyRejected("SignDigestFailed")
67-
}
68-
69-
pub(crate) fn sign_error() -> Self {
70-
KeyRejected("SignFailed")
71-
}
72-
73-
pub(crate) fn verify_digest_error() -> Self {
74-
KeyRejected("VerifyDigestFailed")
75-
}
76-
77-
pub(crate) fn verify_error() -> Self {
78-
KeyRejected("VerifyFailed")
79-
}
80-
81-
pub(crate) fn zero_error() -> Self {
82-
KeyRejected("ZeroError")
83-
}
84-
85-
pub(crate) fn not_on_curve_error() -> Self {
86-
KeyRejected("NotOnCurveError")
87-
}
88-
}
89-
90-
#[cfg(feature = "std")]
91-
impl std::error::Error for KeyRejected {
92-
fn description(&self) -> &str {
93-
self.description_()
94-
}
95-
96-
fn cause(&self) -> Option<&dyn std::error::Error> {
97-
None
98-
}
99-
}
100-
101-
impl core::fmt::Display for KeyRejected {
102-
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
103-
f.write_str(self.description_())
104-
}
48+
#[derive(PartialEq, Clone, Debug)]
49+
pub enum KeyRejectedError {
50+
SeedOperationFailed,
51+
SignDigestFailed,
52+
VerifyDigestFailed,
53+
ZeroError,
54+
NotOnCurveError,
55+
LibSmError(String),
56+
UnexpectedError,
10557
}

src/jacobian/exchange.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
use crate::elem::{
1616
elem_add, elem_inv_sqr_to_mont, elem_mul, elem_to_unencoded, point_x, point_y, point_z, Elem, R,
1717
};
18-
use crate::err::KeyRejected;
18+
use crate::err::KeyRejectedError;
1919
use crate::limb::{Limb, LIMB_BYTES, LIMB_LENGTH};
2020
use crate::norop::big_endian_from_limbs;
2121
use crate::sm2p256::CURVE_PARAMS;
@@ -24,7 +24,7 @@ pub fn big_endian_affine_from_jacobian(
2424
x_out: &mut [u8; LIMB_LENGTH * LIMB_BYTES],
2525
y_out: &mut [u8; LIMB_LENGTH * LIMB_BYTES],
2626
point: &[Limb; LIMB_LENGTH * 3],
27-
) -> Result<(), KeyRejected> {
27+
) -> Result<(), KeyRejectedError> {
2828
let (x_aff, y_aff) = affine_from_jacobian(point)?;
2929
let x = elem_to_unencoded(&x_aff);
3030
big_endian_from_limbs(&x.limbs, x_out);
@@ -36,7 +36,7 @@ pub fn big_endian_affine_from_jacobian(
3636

3737
pub fn affine_from_jacobian(
3838
point: &[Limb; LIMB_LENGTH * 3],
39-
) -> Result<(Elem<R>, Elem<R>), KeyRejected> {
39+
) -> Result<(Elem<R>, Elem<R>), KeyRejectedError> {
4040
let x = point_x(point);
4141
let y = point_y(point);
4242
let z = point_z(point);
@@ -58,11 +58,11 @@ pub fn affine_from_jacobian(
5858

5959
pub fn verify_jacobian_point_is_on_the_curve(
6060
point: &[Limb; LIMB_LENGTH * 3],
61-
) -> Result<(), KeyRejected> {
61+
) -> Result<(), KeyRejectedError> {
6262
let z = point_z(point);
6363

6464
if z.is_zero() {
65-
return Err(KeyRejected::zero_error());
65+
return Err(KeyRejectedError::ZeroError);
6666
}
6767

6868
let x = point_x(point);
@@ -81,7 +81,7 @@ pub fn verify_affine_point_is_on_the_curve(
8181
(x, y): (&Elem<R>, &Elem<R>),
8282
a: &Elem<R>,
8383
b: &Elem<R>,
84-
) -> Result<(), KeyRejected> {
84+
) -> Result<(), KeyRejectedError> {
8585
let lhs = elem_mul(y, y);
8686

8787
let x2 = elem_mul(x, x);
@@ -90,7 +90,7 @@ pub fn verify_affine_point_is_on_the_curve(
9090
let rhs = elem_add(&x2_a_x, b);
9191

9292
if !lhs.is_equal(&rhs) {
93-
return Err(KeyRejected::not_on_curve_error());
93+
return Err(KeyRejectedError::NotOnCurveError);
9494
}
9595
Ok(())
9696
}

src/key/private.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@
1313
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1414

1515
use crate::elem::Scalar;
16-
use crate::err::KeyRejected;
16+
use crate::err::KeyRejectedError;
1717
use crate::limb::{LIMB_BYTES, LIMB_LENGTH};
1818
use crate::norop::{norop_limbs_less_than, parse_big_endian};
1919
use crate::rand::SecureRandom;
2020
use crate::sm2p256::CURVE_PARAMS;
2121
use core::marker::PhantomData;
2222

23-
pub(crate) fn create_private_key(rng: &mut dyn SecureRandom) -> Result<Scalar, KeyRejected> {
23+
pub(crate) fn create_private_key(rng: &mut dyn SecureRandom) -> Result<Scalar, KeyRejectedError> {
2424
let mut seed = [0; LIMB_LENGTH * LIMB_BYTES];
2525
let mut candidate = [0; LIMB_LENGTH];
2626

@@ -38,5 +38,5 @@ pub(crate) fn create_private_key(rng: &mut dyn SecureRandom) -> Result<Scalar, K
3838
}
3939
}
4040

41-
Err(KeyRejected::seed_error())
41+
Err(KeyRejectedError::SeedOperationFailed)
4242
}

src/key/public.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1414

1515
use crate::elem::{scalar_to_unencoded, Scalar, R};
16-
use crate::err::KeyRejected;
16+
use crate::err::KeyRejectedError;
1717
use crate::jacobian::exchange::big_endian_affine_from_jacobian;
1818
use crate::limb::{Limb, LIMB_BYTES, LIMB_LENGTH};
1919
use crate::norop::parse_big_endian;
@@ -52,7 +52,7 @@ impl PublicKey {
5252
to_jacobi(&x_aff, &y_aff)
5353
}
5454

55-
pub fn public_from_private(d: &Scalar<R>) -> Result<PublicKey, KeyRejected> {
55+
pub fn public_from_private(d: &Scalar<R>) -> Result<PublicKey, KeyRejectedError> {
5656
let du = scalar_to_unencoded(d);
5757
let pk_point = base_point_mul(&du.limbs);
5858
let mut x = [0; LIMB_LENGTH * LIMB_BYTES];

0 commit comments

Comments
 (0)