efficient_sm2/ec/
verification.rs

1// Copyright 2020 Yao Pengfei.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15use crate::elem::{
16    elem_mul, elem_reduced_to_scalar, elem_to_unencoded, point_x, point_z, scalar_add, scalar_sub,
17    scalar_to_elem, twin_mul, Elem, Scalar, Unencoded,
18};
19use crate::err::KeyRejectedError;
20use crate::jacobian::exchange::verify_jacobian_point_is_on_the_curve;
21use crate::key::public::PublicKey;
22use crate::limb::{Limb, LIMB_BYTES, LIMB_LENGTH};
23use crate::norop::{big_endian_from_limbs, parse_big_endian};
24use std::marker::PhantomData;
25
26#[derive(Clone)]
27pub struct Signature {
28    r: Scalar,
29    s: Scalar,
30}
31
32impl Signature {
33    pub fn new(r: &[u8], s: &[u8]) -> Result<Self, KeyRejectedError> {
34        let mut rl = [0; LIMB_LENGTH];
35        parse_big_endian(&mut rl, r)?;
36        let r = Scalar {
37            limbs: rl,
38            m: PhantomData,
39        };
40
41        let mut sl = [0; LIMB_LENGTH];
42        parse_big_endian(&mut sl, s)?;
43        let s = Scalar {
44            limbs: sl,
45            m: PhantomData,
46        };
47
48        Ok(Signature { r, s })
49    }
50
51    pub fn from_slice(sig: &[u8]) -> Result<Self, KeyRejectedError> {
52        Self::new(
53            &sig[..LIMB_LENGTH * LIMB_BYTES],
54            &sig[LIMB_LENGTH * LIMB_BYTES..],
55        )
56    }
57
58    pub fn from_scalars(r: Scalar, s: Scalar) -> Self {
59        Signature { r, s }
60    }
61
62    pub fn r(&self) -> [u8; LIMB_LENGTH * LIMB_BYTES] {
63        let mut r_out = [0; LIMB_LENGTH * LIMB_BYTES];
64        big_endian_from_limbs(&self.r.limbs, &mut r_out);
65        r_out
66    }
67
68    pub fn s(&self) -> [u8; LIMB_LENGTH * LIMB_BYTES] {
69        let mut s_out = [0; LIMB_LENGTH * LIMB_BYTES];
70        big_endian_from_limbs(&self.s.limbs, &mut s_out);
71        s_out
72    }
73
74    pub fn verify(&self, pk: &PublicKey, msg: &[u8]) -> Result<(), KeyRejectedError> {
75        let ctx = libsm::sm2::signature::SigCtx::new();
76        let pk_point = ctx
77            .load_pubkey(pk.bytes_less_safe())
78            .map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
79        let digest = ctx
80            .hash("1234567812345678", &pk_point, msg)
81            .map_err(|e| KeyRejectedError::LibSmError(format!("{e}")))?;
82
83        self.verify_digest(pk, &digest)
84    }
85
86    pub fn verify_digest(&self, pk: &PublicKey, digest: &[u8]) -> Result<(), KeyRejectedError> {
87        let mut dl = [0; LIMB_LENGTH];
88        parse_big_endian(&mut dl, digest)?;
89        let edl = Elem {
90            limbs: dl,
91            m: PhantomData,
92        };
93        let e = elem_reduced_to_scalar(&edl);
94
95        let (u1, u2) = (&self.s, scalar_add(&self.r, &self.s));
96        let r = scalar_sub(&self.r, &e);
97
98        let point = twin_mul(u1, &u2, pk);
99
100        verify_jacobian_point_is_on_the_curve(&point)?;
101
102        fn sig_r_equals_x(r: &Elem<Unencoded>, point: &[Limb; LIMB_LENGTH * 3]) -> bool {
103            let x = point_x(point);
104            let z = point_z(point);
105            let z2 = elem_mul(&z, &z);
106            let r_jacobian = elem_mul(&z2, r);
107            let x = elem_to_unencoded(&x);
108            r_jacobian.is_equal(&x)
109        }
110
111        let r = scalar_to_elem(&r);
112        if sig_r_equals_x(&r, &point) {
113            return Ok(());
114        }
115        Err(KeyRejectedError::VerifyDigestFailed)
116    }
117}