efficient_sm2/key/
public.rs1use crate::elem::{scalar_to_unencoded, Scalar, R};
16use crate::err::KeyRejectedError;
17use crate::jacobian::exchange::big_endian_affine_from_jacobian;
18use crate::limb::{Limb, LIMB_BYTES, LIMB_LENGTH};
19use crate::norop::parse_big_endian;
20use crate::sm2p256::{base_point_mul, to_jacobi, to_mont};
21
22#[derive(Copy, Clone, Eq, PartialEq)]
23pub struct PublicKey {
24 bytes: [u8; PUBLIC_KEY_LEN],
25}
26
27impl PublicKey {
28 pub fn new(x: &[u8], y: &[u8]) -> Self {
29 let mut public = PublicKey {
30 bytes: [0; PUBLIC_KEY_LEN],
31 };
32 public.bytes[0] = 4;
33 public.bytes[1..1 + LIMB_LENGTH * LIMB_BYTES].copy_from_slice(x);
34 public.bytes[1 + LIMB_LENGTH * LIMB_BYTES..].copy_from_slice(y);
35
36 public
37 }
38
39 pub fn from_slice(slice: &[u8]) -> Self {
40 let mut bytes = [0; PUBLIC_KEY_LEN];
41 bytes[0] = 4;
42 bytes[1..].copy_from_slice(slice);
43 PublicKey { bytes }
44 }
45
46 pub fn bytes_less_safe(&self) -> &[u8] {
47 &self.bytes
48 }
49
50 pub fn to_point(&self) -> [Limb; LIMB_LENGTH * 3] {
51 let mut x = [0; LIMB_LENGTH];
52 parse_big_endian(&mut x, &self.bytes[1..LIMB_LENGTH * LIMB_BYTES + 1]).unwrap();
53 let x_aff = to_mont(&x);
54
55 let mut y = [0; LIMB_LENGTH];
56 parse_big_endian(&mut y, &self.bytes[LIMB_LENGTH * LIMB_BYTES + 1..]).unwrap();
57 let y_aff = to_mont(&y);
58
59 to_jacobi(&x_aff, &y_aff)
60 }
61
62 pub fn public_from_private(d: &Scalar<R>) -> Result<PublicKey, KeyRejectedError> {
63 let du = scalar_to_unencoded(d);
64 let pk_point = base_point_mul(&du.limbs);
65 let mut x = [0; LIMB_LENGTH * LIMB_BYTES];
66 let mut y = [0; LIMB_LENGTH * LIMB_BYTES];
67
68 big_endian_affine_from_jacobian(&mut x, &mut y, &pk_point)?;
69
70 Ok(PublicKey::new(&x, &y))
71 }
72}
73
74pub const PUBLIC_KEY_LEN: usize = 1 + (2 * LIMB_LENGTH * LIMB_BYTES);