use crate::elem::{scalar_to_unencoded, Scalar, R};
use crate::err::KeyRejectedError;
use crate::jacobian::exchange::big_endian_affine_from_jacobian;
use crate::limb::{Limb, LIMB_BYTES, LIMB_LENGTH};
use crate::norop::parse_big_endian;
use crate::sm2p256::{base_point_mul, to_jacobi, to_mont};
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct PublicKey {
bytes: [u8; PUBLIC_KEY_LEN],
}
impl PublicKey {
pub fn new(x: &[u8], y: &[u8]) -> Self {
let mut public = PublicKey {
bytes: [0; PUBLIC_KEY_LEN],
};
public.bytes[0] = 4;
public.bytes[1..1 + LIMB_LENGTH * LIMB_BYTES].copy_from_slice(x);
public.bytes[1 + LIMB_LENGTH * LIMB_BYTES..].copy_from_slice(y);
public
}
pub fn from_slice(slice: &[u8]) -> Self {
let mut bytes = [0; PUBLIC_KEY_LEN];
bytes[0] = 4;
bytes[1..].copy_from_slice(slice);
PublicKey { bytes }
}
pub fn bytes_less_safe(&self) -> &[u8] {
&self.bytes
}
pub fn to_point(&self) -> [Limb; LIMB_LENGTH * 3] {
let mut x = [0; LIMB_LENGTH];
parse_big_endian(&mut x, &self.bytes[1..LIMB_LENGTH * LIMB_BYTES + 1]).unwrap();
let x_aff = to_mont(&x);
let mut y = [0; LIMB_LENGTH];
parse_big_endian(&mut y, &self.bytes[LIMB_LENGTH * LIMB_BYTES + 1..]).unwrap();
let y_aff = to_mont(&y);
to_jacobi(&x_aff, &y_aff)
}
pub fn public_from_private(d: &Scalar<R>) -> Result<PublicKey, KeyRejectedError> {
let du = scalar_to_unencoded(d);
let pk_point = base_point_mul(&du.limbs);
let mut x = [0; LIMB_LENGTH * LIMB_BYTES];
let mut y = [0; LIMB_LENGTH * LIMB_BYTES];
big_endian_affine_from_jacobian(&mut x, &mut y, &pk_point)?;
Ok(PublicKey::new(&x, &y))
}
}
pub const PUBLIC_KEY_LEN: usize = 1 + (2 * LIMB_LENGTH * LIMB_BYTES);