dcrypt_algorithms/ec/k256/
scalar.rs

1//! secp256k1 scalar arithmetic operations
2
3use crate::ec::k256::constants::K256_SCALAR_SIZE;
4use crate::error::{Error, Result};
5use dcrypt_common::security::SecretBuffer;
6use zeroize::{Zeroize, ZeroizeOnDrop};
7
8/// secp256k1 scalar value for use in elliptic curve operations
9#[derive(Clone, Zeroize, ZeroizeOnDrop, Debug)]
10pub struct Scalar(SecretBuffer<K256_SCALAR_SIZE>);
11
12impl Scalar {
13    /// Create a new scalar from raw bytes.
14    ///
15    /// The bytes will be reduced modulo the curve order if necessary.
16    /// Returns an error if the resulting scalar would be zero.
17    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    /// Create a scalar from a `SecretBuffer`.
23    ///
24    /// The buffer contents will be reduced modulo the curve order if necessary.
25    /// Returns an error if the resulting scalar would be zero.
26    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    /// Get a reference to the underlying `SecretBuffer`.
34    pub fn as_secret_buffer(&self) -> &SecretBuffer<K256_SCALAR_SIZE> {
35        &self.0
36    }
37
38    /// Serialize this scalar to bytes.
39    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    /// Check if this scalar is zero.
46    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        // Check if the input is explicitly zero (reject literal zero inputs)
52        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        // After reduction, if the result is zero, that's OK - it means the input
86        // was a non-zero multiple of the group order (e.g., n itself).
87        // We only reject explicit zero inputs, not zeros that result from reduction.
88        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}