dcrypt_algorithms/ec/k256/
scalar.rs1use crate::ec::k256::constants::K256_SCALAR_SIZE;
4use crate::error::{Error, Result};
5use dcrypt_common::security::SecretBuffer;
6use zeroize::{Zeroize, ZeroizeOnDrop};
7
8#[derive(Clone, Zeroize, ZeroizeOnDrop, Debug)]
10pub struct Scalar(SecretBuffer<K256_SCALAR_SIZE>);
11
12impl Scalar {
13 pub fn new(mut data: [u8; K256_SCALAR_SIZE]) -> Result<Self> {
18 Self::reduce_scalar_bytes(&mut data)?;
19 Ok(Scalar(SecretBuffer::new(data)))
20 }
21
22 pub fn from_secret_buffer(buffer: SecretBuffer<K256_SCALAR_SIZE>) -> Result<Self> {
27 let mut bytes = [0u8; K256_SCALAR_SIZE];
28 bytes.copy_from_slice(buffer.as_ref());
29 Self::reduce_scalar_bytes(&mut bytes)?;
30 Ok(Scalar(SecretBuffer::new(bytes)))
31 }
32
33 pub fn as_secret_buffer(&self) -> &SecretBuffer<K256_SCALAR_SIZE> {
35 &self.0
36 }
37
38 pub fn serialize(&self) -> [u8; K256_SCALAR_SIZE] {
40 let mut result = [0u8; K256_SCALAR_SIZE];
41 result.copy_from_slice(self.0.as_ref());
42 result
43 }
44
45 pub fn is_zero(&self) -> bool {
47 self.0.as_ref().iter().all(|&b| b == 0)
48 }
49
50 fn reduce_scalar_bytes(bytes: &mut [u8; K256_SCALAR_SIZE]) -> Result<()> {
51 let is_explicit_zero = bytes.iter().all(|&b| b == 0);
53 if is_explicit_zero {
54 return Err(Error::param("K256 Scalar", "Scalar cannot be zero"));
55 }
56
57 let mut is_ge = false;
58 for (i, (&byte, &order_byte)) in bytes.iter().zip(Self::ORDER.iter()).enumerate() {
59 if byte > order_byte {
60 is_ge = true;
61 break;
62 }
63 if byte < order_byte {
64 break;
65 }
66 if i == K256_SCALAR_SIZE - 1 {
67 is_ge = true;
68 }
69 }
70
71 if is_ge {
72 let mut borrow = 0i16;
73 for i in (0..K256_SCALAR_SIZE).rev() {
74 let diff = (bytes[i] as i16) - (Self::ORDER[i] as i16) - borrow;
75 if diff < 0 {
76 bytes[i] = (diff + 256) as u8;
77 borrow = 1;
78 } else {
79 bytes[i] = diff as u8;
80 borrow = 0;
81 }
82 }
83 }
84
85 Ok(())
89 }
90
91 const ORDER: [u8; 32] = [
92 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
93 0xFE, 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36,
94 0x41, 0x41,
95 ];
96}