sm2/
arithmetic.rs

1//! Pure Rust implementation of group operations on the SM2 elliptic curve.
2//!
3//! Curve parameters can be found in [draft-shen-sm2-ecdsa Appendix D]:
4//! Recommended Parameters.
5//!
6//! [draft-shen-sm2-ecdsa Appendix D]: https://datatracker.ietf.org/doc/html/draft-shen-sm2-ecdsa-02#appendix-D
7
8pub(crate) mod field;
9pub(crate) mod scalar;
10
11pub use self::scalar::Scalar;
12
13use self::field::FieldElement;
14use crate::Sm2;
15use elliptic_curve::{CurveArithmetic, PrimeCurveArithmetic};
16use primeorder::{point_arithmetic, PrimeCurveParams};
17
18/// Elliptic curve point in affine coordinates.
19pub type AffinePoint = primeorder::AffinePoint<Sm2>;
20
21/// Elliptic curve point in projective coordinates.
22pub type ProjectivePoint = primeorder::ProjectivePoint<Sm2>;
23
24impl CurveArithmetic for Sm2 {
25    type AffinePoint = AffinePoint;
26    type ProjectivePoint = ProjectivePoint;
27    type Scalar = Scalar;
28}
29
30impl PrimeCurveArithmetic for Sm2 {
31    type CurveGroup = ProjectivePoint;
32}
33
34/// Adapted from [draft-shen-sm2-ecdsa Appendix D]: Recommended Parameters.
35///
36/// [draft-shen-sm2-ecdsa Appendix D]: https://datatracker.ietf.org/doc/html/draft-shen-sm2-ecdsa-02#appendix-D
37impl PrimeCurveParams for Sm2 {
38    type FieldElement = FieldElement;
39    type PointArithmetic = point_arithmetic::EquationAIsMinusThree;
40
41    /// a = -3 (0xFFFFFFFE FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF 00000000 FFFFFFFF FFFFFFFC)
42    const EQUATION_A: FieldElement = FieldElement::from_u64(3).neg();
43
44    /// b = 0x28E9FA9E 9D9F5E34 4D5A9E4B CF6509A7 F39789F5 15AB8F92 DDBCBD41 4D940E93
45    const EQUATION_B: FieldElement =
46        FieldElement::from_hex("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93");
47
48    /// Base point of SM2.
49    ///
50    /// ```text
51    /// Gₓ = 0x32C4AE2C 1F198119 5F990446 6A39C994 8FE30BBF F2660BE1 715A4589 334C74C7
52    /// Gᵧ = 0xBC3736A2 F4F6779C 59BDCEE3 6B692153 D0A9877C C62A4740 02DF32E5 2139F0A0
53    /// ```
54    const GENERATOR: (FieldElement, FieldElement) = (
55        FieldElement::from_hex("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7"),
56        FieldElement::from_hex("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0"),
57    );
58}