Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-crypto

Source of release 0.6.0

0.6.0 / tools / p256_table.py

#!/usr/bin/env python3
"""Generate src/p256_table.lucb: k*G for k = 1..15 on P-256, affine,
in Montgomery form (x * 2^256 mod p) as eight little-endian 32-bit limbs per
coordinate. This is the fixed-base window of BearSSL's ec_p256_m31 (`Gwin`),
recomputed here from the curve constants of SEC 2 / FIPS 186-4."""
from pathlib import Path

P = 2**256 - 2**224 + 2**192 + 2**96 - 1
GX = 0x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
GY = 0x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5
ROOT = Path(__file__).resolve().parents[1]


def add(a, b):
    if a is None:
        return b
    (x1, y1), (x2, y2) = a, b
    if a == b:
        slope = 3 * (x1 * x1 - 1) * pow(2 * y1, -1, P) % P
    else:
        slope = (y2 - y1) * pow(x2 - x1, -1, P) % P
    x3 = (slope * slope - x1 - x2) % P
    return x3, (slope * (x1 - x3) - y1) % P


def limbs(value):
    value = value * 2**256 % P
    return ", ".join(f"0x{(value >> (32 * i)) & 0xffffffff:08x}" for i in range(8))


def main():
    point, rows = None, []
    for k in range(1, 16):
        point = add(point, (GX, GY))
        rows.append(f"    {limbs(point[0])}, {limbs(point[1])}")
    text = ("## Generated by tools/p256_table.py; do not edit. k*G for k = 1..15 on\n"
            "## P-256 in affine Montgomery form, sixteen limbs (x then y) per point.\n\n"
            "pub let generator_window: u32[240] = [\n" + ",\n".join(rows) + "\n]\n")
    (ROOT / "src/p256_table.lucb").write_text(text)


if __name__ == "__main__":
    main()