///|
/// Constant-time 256-bit arithmetic over NIST P-256 base field F_p and scalar
/// field F_n using CIOS Montgomery multiplication (8 x 32-bit little-endian limbs).
///|
#derive(Debug, Eq)
pub suberror P256Error {
InvalidEncoding
InvalidScalar
InvalidLength(Int32)
ZeroScalar
IdentityElement
}
///|
/// 256-bit unsigned integer represented as 8 little-endian 32-bit limbs.
#derive(Debug)
priv struct U256 {
l0 : UInt32
l1 : UInt32
l2 : UInt32
l3 : UInt32
l4 : UInt32
l5 : UInt32
l6 : UInt32
l7 : UInt32
}
///|
/// Field element in Montgomery representation modulo NIST P-256 prime p.
#derive(Debug)
priv struct Fe {
v : U256
}
///|
/// Scalar modulo NIST P-256 prime group order n (stored in canonical form < n).
#derive(Debug)
pub struct Scalar {
priv v : U256
}
// ============================================================================
// NIST P-256 Field & Order Constants
// ============================================================================
///|
/// p = 2^256 - 2^224 + 2^192 + 2^96 - 1
/// = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF
let p_mod : U256 = {
l0: 0xFFFFFFFFU,
l1: 0xFFFFFFFFU,
l2: 0xFFFFFFFFU,
l3: 0x00000000U,
l4: 0x00000000U,
l5: 0x00000000U,
l6: 0x00000001U,
l7: 0xFFFFFFFFU,
}
///|
/// R mod p = 2^256 mod p (Montgomery representation of 1 in F_p)
let p_r1 : U256 = {
l0: 0x00000001U,
l1: 0x00000000U,
l2: 0x00000000U,
l3: 0xFFFFFFFFU,
l4: 0xFFFFFFFFU,
l5: 0xFFFFFFFFU,
l6: 0xFFFFFFFEU,
l7: 0x00000000U,
}
///|
/// R^2 mod p = 2^512 mod p
let p_r2 : U256 = {
l0: 0x00000003U,
l1: 0x00000000U,
l2: 0xFFFFFFFFU,
l3: 0xFFFFFFFBU,
l4: 0xFFFFFFFEU,
l5: 0xFFFFFFFFU,
l6: 0xFFFFFFFDU,
l7: 0x00000004U,
}
///|
/// p - 2 (exponent for Fermat inversion in F_p)
let p_minus_2 : U256 = {
l0: 0xFFFFFFFDU,
l1: 0xFFFFFFFFU,
l2: 0xFFFFFFFFU,
l3: 0x00000000U,
l4: 0x00000000U,
l5: 0x00000000U,
l6: 0x00000001U,
l7: 0xFFFFFFFFU,
}
///|
/// (p + 1) / 4 = 0x3fffffffc0000000400000000000000000000000400000000000000000000000
/// (exponent for square root in F_p since p == 3 (mod 4))
let p_plus_1_div_4 : U256 = {
l0: 0x00000000U,
l1: 0x00000000U,
l2: 0x40000000U,
l3: 0x00000000U,
l4: 0x00000000U,
l5: 0x40000000U,
l6: 0xC0000000U,
l7: 0x3FFFFFFFU,
}
///|
/// n = 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551
let n_mod : U256 = {
l0: 0xFC632551U,
l1: 0xF3B9CAC2U,
l2: 0xA7179E84U,
l3: 0xBCE6FAADU,
l4: 0xFFFFFFFFU,
l5: 0xFFFFFFFFU,
l6: 0x00000000U,
l7: 0xFFFFFFFFU,
}
///|
/// -n^(-1) mod 2^32
let n_n0 : UInt32 = 0xEE00BC4FU
///|
/// R^2 mod n = 2^512 mod n
let n_r2 : U256 = {
l0: 0xBE79EEA2U,
l1: 0x83244C95U,
l2: 0x49BD6FA6U,
l3: 0x4699799CU,
l4: 0x2B6BEC59U,
l5: 0x2845B239U,
l6: 0xF3D95620U,
l7: 0x66E12D94U,
}
///|
/// n - 2 (exponent for constant-time Fermat inversion in F_n)
let n_minus_2 : U256 = {
l0: 0xFC63254FU,
l1: 0xF3B9CAC2U,
l2: 0xA7179E84U,
l3: 0xBCE6FAADU,
l4: 0xFFFFFFFFU,
l5: 0xFFFFFFFFU,
l6: 0x00000000U,
l7: 0xFFFFFFFFU,
}
///|
let u256_zero : U256 = {
l0: 0U,
l1: 0U,
l2: 0U,
l3: 0U,
l4: 0U,
l5: 0U,
l6: 0U,
l7: 0U,
}
///|
let u256_one : U256 = {
l0: 1U,
l1: 0U,
l2: 0U,
l3: 0U,
l4: 0U,
l5: 0U,
l6: 0U,
l7: 0U,
}
// ============================================================================
// Constant-Time U256 Primitives
// ============================================================================
///|
fn u256_is_zero(a : U256) -> UInt32 {
@ct.ct_is_zero_u32(a.l0 | a.l1 | a.l2 | a.l3 | a.l4 | a.l5 | a.l6 | a.l7)
}
///|
fn u256_eq(a : U256, b : U256) -> UInt32 {
@ct.ct_is_zero_u32(
(a.l0 ^ b.l0) |
(a.l1 ^ b.l1) |
(a.l2 ^ b.l2) |
(a.l3 ^ b.l3) |
(a.l4 ^ b.l4) |
(a.l5 ^ b.l5) |
(a.l6 ^ b.l6) |
(a.l7 ^ b.l7),
)
}
///|
fn u256_ct_select(cond : UInt32, a : U256, b : U256) -> U256 {
{
l0: @ct.ct_select_u32(cond, a.l0, b.l0),
l1: @ct.ct_select_u32(cond, a.l1, b.l1),
l2: @ct.ct_select_u32(cond, a.l2, b.l2),
l3: @ct.ct_select_u32(cond, a.l3, b.l3),
l4: @ct.ct_select_u32(cond, a.l4, b.l4),
l5: @ct.ct_select_u32(cond, a.l5, b.l5),
l6: @ct.ct_select_u32(cond, a.l6, b.l6),
l7: @ct.ct_select_u32(cond, a.l7, b.l7),
}
}
///|
/// Computes `(a + b, carry)` where `carry` is `0U` or `1U`.
fn u256_add_carry(a : U256, b : U256) -> (U256, UInt32) {
let s0 = a.l0.to_uint64() + b.l0.to_uint64()
let s1 = a.l1.to_uint64() + b.l1.to_uint64() + (s0 >> 32)
let s2 = a.l2.to_uint64() + b.l2.to_uint64() + (s1 >> 32)
let s3 = a.l3.to_uint64() + b.l3.to_uint64() + (s2 >> 32)
let s4 = a.l4.to_uint64() + b.l4.to_uint64() + (s3 >> 32)
let s5 = a.l5.to_uint64() + b.l5.to_uint64() + (s4 >> 32)
let s6 = a.l6.to_uint64() + b.l6.to_uint64() + (s5 >> 32)
let s7 = a.l7.to_uint64() + b.l7.to_uint64() + (s6 >> 32)
(
{
l0: s0.to_uint(),
l1: s1.to_uint(),
l2: s2.to_uint(),
l3: s3.to_uint(),
l4: s4.to_uint(),
l5: s5.to_uint(),
l6: s6.to_uint(),
l7: s7.to_uint(),
},
(s7 >> 32).to_uint(),
)
}
///|
/// Computes `(a - b, borrow)` where `borrow` is `0U` if `a >= b` else `1U`.
fn u256_sub_borrow(a : U256, b : U256) -> (U256, UInt32) {
let d0 = a.l0.to_uint64() - b.l0.to_uint64()
let b0 = (d0 >> 63) & 1UL
let d1 = a.l1.to_uint64() - b.l1.to_uint64() - b0
let b1 = (d1 >> 63) & 1UL
let d2 = a.l2.to_uint64() - b.l2.to_uint64() - b1
let b2 = (d2 >> 63) & 1UL
let d3 = a.l3.to_uint64() - b.l3.to_uint64() - b2
let b3 = (d3 >> 63) & 1UL
let d4 = a.l4.to_uint64() - b.l4.to_uint64() - b3
let b4 = (d4 >> 63) & 1UL
let d5 = a.l5.to_uint64() - b.l5.to_uint64() - b4
let b5 = (d5 >> 63) & 1UL
let d6 = a.l6.to_uint64() - b.l6.to_uint64() - b5
let b6 = (d6 >> 63) & 1UL
let d7 = a.l7.to_uint64() - b.l7.to_uint64() - b6
let b7 = (d7 >> 63) & 1UL
(
{
l0: d0.to_uint(),
l1: d1.to_uint(),
l2: d2.to_uint(),
l3: d3.to_uint(),
l4: d4.to_uint(),
l5: d5.to_uint(),
l6: d6.to_uint(),
l7: d7.to_uint(),
},
b7.to_uint(),
)
}
///|
fn u256_gte(a : U256, b : U256) -> UInt32 {
let (_, borrow) = u256_sub_borrow(a, b)
1U - borrow
}
///|
fn u256_get_limb(a : U256, idx : Int32) -> UInt32 {
match idx {
0 => a.l0
1 => a.l1
2 => a.l2
3 => a.l3
4 => a.l4
5 => a.l5
6 => a.l6
_ => a.l7
}
}
///|
fn u256_get_bit(a : U256, bit : Int32) -> UInt32 {
let limb = u256_get_limb(a, bit >> 5)
(limb >> (bit & 31)) & 1U
}
///|
fn read_be32_view(b : BytesView, off : Int32) -> UInt32 {
(b[off].to_uint() << 24) |
(b[off + 1].to_uint() << 16) |
(b[off + 2].to_uint() << 8) |
b[off + 3].to_uint()
}
///|
fn write_be32_arr(out : FixedArray[Byte], off : Int32, v : UInt32) -> Unit {
out[off] = ((v >> 24) & 0xFFU).to_byte()
out[off + 1] = ((v >> 16) & 0xFFU).to_byte()
out[off + 2] = ((v >> 8) & 0xFFU).to_byte()
out[off + 3] = (v & 0xFFU).to_byte()
}
///|
fn u256_from_be_view(b : BytesView) -> U256 {
{
l7: read_be32_view(b, 0),
l6: read_be32_view(b, 4),
l5: read_be32_view(b, 8),
l4: read_be32_view(b, 12),
l3: read_be32_view(b, 16),
l2: read_be32_view(b, 20),
l1: read_be32_view(b, 24),
l0: read_be32_view(b, 28),
}
}
///|
fn u256_from_be16_view(b : BytesView) -> U256 {
{
l7: 0U,
l6: 0U,
l5: 0U,
l4: 0U,
l3: read_be32_view(b, 0),
l2: read_be32_view(b, 4),
l1: read_be32_view(b, 8),
l0: read_be32_view(b, 12),
}
}
///|
fn u256_to_be_bytes(a : U256) -> Bytes {
let out = FixedArray::make(32, b'\x00')
write_be32_arr(out, 0, a.l7)
write_be32_arr(out, 4, a.l6)
write_be32_arr(out, 8, a.l5)
write_be32_arr(out, 12, a.l4)
write_be32_arr(out, 16, a.l3)
write_be32_arr(out, 20, a.l2)
write_be32_arr(out, 24, a.l1)
write_be32_arr(out, 28, a.l0)
Bytes::from_array(out)
}
///|
/// Constant-time CIOS Montgomery multiplication: `a * b * R^(-1) mod m`.
fn mont_mul(a : U256, b : U256, m : U256, n0 : UInt32) -> U256 {
let t = FixedArray::make(10, 0UL)
let b_limbs : FixedArray[UInt64] = [
b.l0.to_uint64(),
b.l1.to_uint64(),
b.l2.to_uint64(),
b.l3.to_uint64(),
b.l4.to_uint64(),
b.l5.to_uint64(),
b.l6.to_uint64(),
b.l7.to_uint64(),
]
let m_limbs : FixedArray[UInt64] = [
m.l0.to_uint64(),
m.l1.to_uint64(),
m.l2.to_uint64(),
m.l3.to_uint64(),
m.l4.to_uint64(),
m.l5.to_uint64(),
m.l6.to_uint64(),
m.l7.to_uint64(),
]
let n0_u64 = n0.to_uint64()
for i = 0; i < 8; i = i + 1 {
let ai = u256_get_limb(a, i).to_uint64()
// Multiply-accumulate: t += ai * b
let mut c : UInt64 = 0UL
for j = 0; j < 8; j = j + 1 {
let prod = t[j] + ai * b_limbs[j] + c
t[j] = prod & 0xFFFFFFFFUL
c = prod >> 32
}
let s8 = t[8] + c
t[8] = s8 & 0xFFFFFFFFUL
t[9] = s8 >> 32
// Reduction step: k = (t[0] * n0) mod 2^32; t = (t + k * m) / 2^32
let k = (t[0] * n0_u64) & 0xFFFFFFFFUL
let mut c2 = (t[0] + k * m_limbs[0]) >> 32
for j = 1; j < 8; j = j + 1 {
let prod = t[j] + k * m_limbs[j] + c2
t[j - 1] = prod & 0xFFFFFFFFUL
c2 = prod >> 32
}
let r7 = t[8] + c2
t[7] = r7 & 0xFFFFFFFFUL
t[8] = t[9] + (r7 >> 32)
t[9] = 0UL
}
let res : U256 = {
l0: t[0].to_uint(),
l1: t[1].to_uint(),
l2: t[2].to_uint(),
l3: t[3].to_uint(),
l4: t[4].to_uint(),
l5: t[5].to_uint(),
l6: t[6].to_uint(),
l7: t[7].to_uint(),
}
let (sub, borrow) = u256_sub_borrow(res, m)
// Select `sub` if overflow carry t[8] != 0 OR borrow == 0 (i.e., res >= m)
let need_sub = (t[8].to_uint() & 1U) | (1U - borrow)
u256_ct_select(need_sub, sub, res)
}
// ============================================================================
// Base Field F_p Operations (Montgomery Domain)
// ============================================================================
///|
fn fp_zero() -> Fe {
{ v: u256_zero, }
}
///|
fn fp_one() -> Fe {
{ v: p_r1, }
}
///|
fn fp_from_u256(a : U256) -> Fe {
{ v: mont_mul(a, p_r2, p_mod, 1U), }
}
///|
fn fp_to_u256(a : Fe) -> U256 {
mont_mul(a.v, u256_one, p_mod, 1U)
}
///|
fn fp_is_zero(a : Fe) -> UInt32 {
u256_is_zero(a.v)
}
///|
fn fp_eq(a : Fe, b : Fe) -> UInt32 {
u256_eq(a.v, b.v)
}
///|
fn fp_ct_select(cond : UInt32, a : Fe, b : Fe) -> Fe {
{ v: u256_ct_select(cond, a.v, b.v), }
}
///|
fn fp_add(a : Fe, b : Fe) -> Fe {
let (sum, carry) = u256_add_carry(a.v, b.v)
let (sub, borrow) = u256_sub_borrow(sum, p_mod)
let need_sub = carry | (1U - borrow)
{ v: u256_ct_select(need_sub, sub, sum), }
}
///|
fn fp_sub(a : Fe, b : Fe) -> Fe {
let (diff, borrow) = u256_sub_borrow(a.v, b.v)
let (fixed, _) = u256_add_carry(diff, p_mod)
{ v: u256_ct_select(borrow, fixed, diff), }
}
///|
fn fp_neg(a : Fe) -> Fe {
let (neg, _) = u256_sub_borrow(p_mod, a.v)
{ v: u256_ct_select(u256_is_zero(a.v), u256_zero, neg), }
}
///|
fn fp_mul(a : Fe, b : Fe) -> Fe {
{ v: mont_mul(a.v, b.v, p_mod, 1U), }
}
///|
fn fp_sqr(a : Fe) -> Fe {
{ v: mont_mul(a.v, a.v, p_mod, 1U), }
}
///|
/// Constant-time modular exponentiation `base^exp mod p`.
fn fp_pow(base : Fe, exp : U256) -> Fe {
let mut acc = fp_one()
for bit = 255; bit >= 0; bit = bit - 1 {
acc = fp_sqr(acc)
let prod = fp_mul(acc, base)
acc = fp_ct_select(u256_get_bit(exp, bit), prod, acc)
}
acc
}
///|
/// Constant-time Fermat inversion `a^(p-2) mod p` (maps `0` to `0`, matching RFC 9380 `inv0`).
fn fp_inv(a : Fe) -> Fe {
fp_pow(a, p_minus_2)
}
///|
/// Constant-time square root candidate `a^((p+1)/4) mod p` (for `p == 3 mod 4`).
fn fp_sqrt(a : Fe) -> Fe {
fp_pow(a, p_plus_1_div_4)
}
///|
/// RFC 9380 `sgn0(x)` in `F_p`: returns `1U` if canonical `x` is odd, else `0U`.
fn fp_sgn0(a : Fe) -> UInt32 {
fp_to_u256(a).l0 & 1U
}
///|
/// Reduces a 48-byte big-endian unsigned integer modulo `p` in constant time
/// (used for RFC 9380 `hash_to_field` with `L = 48`).
fn fp_from_be48(buf : BytesView) -> Fe {
let hi = u256_from_be16_view(buf[0:16])
let lo_raw = u256_from_be_view(buf[16:48])
let (lo_sub, borrow) = u256_sub_borrow(lo_raw, p_mod)
let lo = u256_ct_select(1U - borrow, lo_sub, lo_raw)
// hi_mont = to_mont(hi); p_r2 = to_mont(2^256 mod p)
let hi_mont = fp_from_u256(hi)
let hi_shifted = fp_mul(hi_mont, { v: p_r2, })
fp_add(hi_shifted, fp_from_u256(lo))
}
// ============================================================================
// Scalar Field F_n Operations & Public Scalar API
// ============================================================================
///|
fn fn_from_u256(a : U256) -> U256 {
mont_mul(a, n_r2, n_mod, n_n0)
}
///|
fn fn_to_u256(a : U256) -> U256 {
mont_mul(a, u256_one, n_mod, n_n0)
}
///|
fn fn_add(a : U256, b : U256) -> U256 {
let (sum, carry) = u256_add_carry(a, b)
let (sub, borrow) = u256_sub_borrow(sum, n_mod)
let need_sub = carry | (1U - borrow)
u256_ct_select(need_sub, sub, sum)
}
///|
fn fn_sub(a : U256, b : U256) -> U256 {
let (diff, borrow) = u256_sub_borrow(a, b)
let (fixed, _) = u256_add_carry(diff, n_mod)
u256_ct_select(borrow, fixed, diff)
}
///|
fn fn_neg(a : U256) -> U256 {
let (neg, _) = u256_sub_borrow(n_mod, a)
u256_ct_select(u256_is_zero(a), u256_zero, neg)
}
///|
fn fn_mul(a : U256, b : U256) -> U256 {
let am = fn_from_u256(a)
let bm = fn_from_u256(b)
fn_to_u256(mont_mul(am, bm, n_mod, n_n0))
}
///|
/// Constant-time modular inversion `a^(n-2) mod n`.
fn fn_inv(a : U256) -> U256 {
let base = fn_from_u256(a)
let mut acc = fn_from_u256(u256_one)
for bit = 255; bit >= 0; bit = bit - 1 {
acc = mont_mul(acc, acc, n_mod, n_n0)
let prod = mont_mul(acc, base, n_mod, n_n0)
acc = u256_ct_select(u256_get_bit(n_minus_2, bit), prod, acc)
}
fn_to_u256(acc)
}
///|
pub impl Eq for Scalar with fn equal(self, other) {
u256_eq(self.v, other.v) == 1U
}
///|
/// Returns the additive identity scalar `0`.
pub fn Scalar::zero() -> Scalar {
{ v: u256_zero, }
}
///|
/// Returns the multiplicative identity scalar `1`.
pub fn Scalar::one() -> Scalar {
{ v: u256_one, }
}
///|
/// Constructs a canonical scalar from a 32-bit unsigned integer `n` (`n < 2^32 < n_mod`).
pub fn Scalar::from_u32(n : UInt32) -> Scalar {
{ v: { l0: n, l1: 0U, l2: 0U, l3: 0U, l4: 0U, l5: 0U, l6: 0U, l7: 0U, }, }
}
///|
/// Constant-time comparison of canonical scalars as integers in `[0, n - 1]`.
/// Returns `-1` if `self < other`, `0` if `self == other`, `1` if `self > other`.
pub fn Scalar::compare(self : Scalar, other : Scalar) -> Int32 {
let (_, lt) = u256_sub_borrow(self.v, other.v)
let (_, gt) = u256_sub_borrow(other.v, self.v)
gt.reinterpret_as_int() - lt.reinterpret_as_int()
}
///|
/// Returns `true` if `self == 0` in constant time.
pub fn Scalar::is_zero(self : Scalar) -> Bool {
u256_is_zero(self.v) == 1U
}
///|
/// Strictly decodes a 32-byte big-endian canonical scalar (`0 <= s < n`).
pub fn Scalar::from_bytes_canonical(data : Bytes) -> Scalar raise P256Error {
if data.length() != 32 {
raise InvalidLength(data.length())
}
let v = u256_from_be_view(data[:])
if u256_gte(v, n_mod) == 1U {
raise InvalidScalar
}
{ v, }
}
///|
/// Reduces a 48-byte big-endian integer modulo the P-256 group order `n`
/// in constant time (RFC 9497 §4.3 `L = 48` `HashToScalar`).
pub fn Scalar::from_bytes_mod_order_wide(
data : Bytes,
) -> Scalar raise P256Error {
if data.length() != 48 {
raise InvalidLength(data.length())
}
let hi = u256_from_be16_view(data[0:16])
let lo_raw = u256_from_be_view(data[16:48])
let (lo_sub, borrow) = u256_sub_borrow(lo_raw, n_mod)
let lo = u256_ct_select(1U - borrow, lo_sub, lo_raw)
let hi_mont = fn_from_u256(hi)
// n_r2 is the Montgomery representation of 2^256 mod n
let hi_shifted_mont = mont_mul(hi_mont, n_r2, n_mod, n_n0)
let lo_mont = fn_from_u256(lo)
let sum_mont = fn_add(hi_shifted_mont, lo_mont)
{ v: fn_to_u256(sum_mont), }
}
///|
/// Encodes a canonical scalar as 32 big-endian bytes.
pub fn Scalar::to_bytes(self : Scalar) -> Bytes {
u256_to_be_bytes(self.v)
}
///|
pub fn Scalar::add(self : Scalar, other : Scalar) -> Scalar {
{ v: fn_add(self.v, other.v), }
}
///|
pub fn Scalar::sub(self : Scalar, other : Scalar) -> Scalar {
{ v: fn_sub(self.v, other.v), }
}
///|
pub fn Scalar::mul(self : Scalar, other : Scalar) -> Scalar {
{ v: fn_mul(self.v, other.v), }
}
///|
pub fn Scalar::neg(self : Scalar) -> Scalar {
{ v: fn_neg(self.v), }
}
///|
/// Constant-time modular inverse `s^(-1) mod n` via Fermat's Little Theorem.
/// Raises `ZeroScalar` if `self == 0`.
pub fn Scalar::invert(self : Scalar) -> Scalar raise P256Error {
if self.is_zero() {
raise ZeroScalar
}
{ v: fn_inv(self.v), }
}
///|
/// RFC 9497 §4.3 `HashToScalar(msg, dst)` using `expand_message_xmd(SHA-256)`
/// with `L = 48` bytes reduced modulo `n`.
pub fn Scalar::hash_to_scalar(
msg : Bytes,
dst : Bytes,
) -> Scalar raise P256Error {
let uniform = @sha2.expand_message_xmd_sha256(msg, dst, 48) catch {
@sha2.InvalidLength(len) => raise InvalidLength(len)
}
Scalar::from_bytes_mod_order_wide(uniform)
}