Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-crypto

Source of release 0.6.1

0.6.1 / tests / ec_kat / main.lucb

## P-256 and P-384 point arithmetic and P-256 ECDH: BearSSL's multiplication
## known answers, P-256 carry cases, multiply-add identities and key
## generation checks; the complete Wycheproof ecdh_secp256r1 (SPKI) and
## ecdh_secp256r1_ecpoint files; and OpenSSL's P-256 ECDH stanzas.
import p256
import p384
import vector_file

## Point multiply-add on either curve.
func muladd(wide: bool, ax: const u8[], ay: const u8[], u: const u8[], bx: const u8[], by: const u8[], v: const u8[],
    x: u8[], y: u8[]) -> bool!:
    if wide:
        return try p384.multiply_add(ax, ay, u, bx, by, v, x, y)
    return try p256.multiply_add(ax, ay, u, bx, by, v, x, y)

func generator(wide: bool, k: const u8[], x: u8[], y: u8[]) -> bool!:
    if wide:
        return try p384.multiply_generator(k, x, y)
    return try p256.multiply_generator(k, x, y)

func split_point(encoded: const u8[], width: usize, x: u8[], y: u8[]):
    for i in 0..<width:
        x[i] = encoded[1 + i]
        y[i] = encoded[1 + width + i]

## BearSSL test_EC_inner and test_EC_P256_carry.
func bearssl(directory: str, out_of_scope: usize*) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/ec.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var x: u8[48]
        var y: u8[48]
        var ex: u8[48]
        var ey: u8[48]
        if try lines.is(0, "c25519"):
            continue
        if try lines.is(0, "secp521r1"):
            *out_of_scope += 1
            continue
        if try lines.is(0, "p256carry"):
            var p: u8[65]
            var q: u8[65]
            _ = try lines.decode(1, p)
            _ = try lines.decode(2, q)
            var k: u8[32]
            k[31] = 0x10
            assert(try p256.multiply(k, p[1..<33], p[33..<65], x[..<32], y[..<32]))
            assert(x[..<32] == q[1..<33] and y[..<32] == q[33..<65], "P-256 carry case mismatch")
            count += 1
            continue
        let wide = try lines.is(1, "secp384r1") or try lines.is(0, "secp384r1")
        let w: usize = 48 if wide else 32
        if try lines.is(0, "muladd"):
            var values: u8[336]
            for i in 0..<(usize)7:
                _ = try lines.decode(2 + i, values[i * w..<(i + 1) * w])
            let a = values[..<w]
            let b = values[w..<2 * w]
            let u = values[2 * w..<3 * w]
            let v = values[3 * w..<4 * w]
            var ax: u8[48]
            var ay: u8[48]
            var bx: u8[48]
            var by: u8[48]
            assert(try generator(wide, a, ax[..<w], ay[..<w]))
            assert(try generator(wide, b, bx[..<w], by[..<w]))
            # u*A + v*B == (a*u + b*v)*G
            assert(try muladd(wide, ax[..<w], ay[..<w], u, bx[..<w], by[..<w], v, x[..<w], y[..<w]))
            assert(try generator(wide, values[4 * w..<5 * w], ex[..<w], ey[..<w]))
            assert(x[..<w] == ex[..<w] and y[..<w] == ey[..<w], "multiply-add identity (1)")
            # With B = u*G and v = a: u*A + a*B == 2*a*u*G.
            assert(try generator(wide, u, bx[..<w], by[..<w]))
            assert(try muladd(wide, ax[..<w], ay[..<w], u, bx[..<w], by[..<w], a, x[..<w], y[..<w]))
            assert(try generator(wide, values[5 * w..<6 * w], ex[..<w], ey[..<w]))
            assert(x[..<w] == ex[..<w] and y[..<w] == ey[..<w], "multiply-add identity (2)")
            # With v = -a the sum is the point at infinity.
            assert(not (try muladd(wide, ax[..<w], ay[..<w], u, bx[..<w], by[..<w], values[6 * w..<7 * w], x[..<w], y[..<w])))
            count += 1
            continue
        var k: u8[48]
        var point: u8[97]
        _ = try lines.decode(1, k[..<w])
        _ = try lines.decode(2, point[..<1 + 2 * w])
        assert(try generator(wide, k[..<w], x[..<w], y[..<w]))
        assert(x[..<w] == point[1..<1 + w] and y[..<w] == point[1 + w..<1 + 2 * w], "EC multiplication known answer")
        count += 1
    return count

## BearSSL test_EC_keygen for P-256: fresh keys are nonzero, differ, and
## their public points match public_from_private.
func keygen() -> usize!:
    var previous: u8[32]
    for round in 0..<(usize)10:
        var d: u8[32]
        var x: u8[32]
        var y: u8[32]
        try p256.keygen(d, x, y)
        assert(d != previous, "P-256 keygen stutter")
        var ex: u8[32]
        var ey: u8[32]
        try p256.public_from_private(d, ex, ey)
        assert(x == ex and y == ey, "P-256 keygen public key mismatch")
        var gx: u8[32]
        var gy: u8[32]
        assert(try p256.multiply_generator(d, gx, gy))
        assert(x == gx and y == gy)
        previous = d
        _ = round
    return 10

## The P-256 point inside a strict SubjectPublicKeyInfo with the named curve
## and an uncompressed point; false for any other encoding.
func spki_point(der: const u8[], x: u8[], y: u8[]) -> bool:
    let prefix = b"\x30\x59\x30\x13\x06\x07\x2a\x86\x48\xce\x3d\x02\x01\x06\x08\x2a\x86\x48\xce\x3d\x03\x01\x07\x03\x42\x00\x04"
    if der.length != prefix.length + 64 or der[..<prefix.length] != prefix:
        return false
    for i in 0..<(usize)32:
        x[i] = der[prefix.length + i]
        y[i] = der[prefix.length + 32 + i]
    return true

func derive(d: const u8[], x: const u8[], y: const u8[], out: u8[]) -> bool:
    var ok = true
    p256.ecdh(d, x, y, out) catch failure:
        _ = failure
        ok = false
        recover ()
    return ok

## Wycheproof ECDH: valid cases must agree; invalid ones must be refused;
## "acceptable" ones (compressed points, unusual encodings) are refused, as
## TLS 1.3 key shares are uncompressed points.
func wycheproof(directory: str, name: str, spki: bool, valid: usize*, invalid: usize*, acceptable: usize*) -> !:
    var lines = try vector_file.Lines.open(directory, name)
    defer lines.close()
    while lines.next():
        var public: u8[8192]
        var private: u8[64]
        var shared: u8[64]
        var out: u8[32]
        var x: u8[32]
        var y: u8[32]
        let p = try lines.decode(1, public)
        var d = try lines.decode(2, private)
        let s = try lines.decode(3, shared)
        var scalar: u8[32]
        var usable = true
        while d > 32 and private[0] == 0:
            for i in 0..<d - 1: private[i] = private[i + 1]
            d -= 1
        if d > 32:
            usable = false
        else:
            for i in 0..<d: scalar[32 - d + i] = private[i]
        if spki:
            usable = usable and spki_point(public[..<p], x, y)
        else:
            usable = usable and p == 65 and public[0] == 4
            if usable:
                for i in 0..<(usize)32:
                    x[i] = public[1 + i]
                    y[i] = public[33 + i]
        let agreed = usable and derive(scalar, x, y, out) and out == shared[..<s]
        if try lines.is(0, "valid"):
            assert(agreed, "valid Wycheproof ECDH case failed")
            *valid += 1
        elif try lines.is(0, "invalid"):
            assert(not agreed, "invalid Wycheproof ECDH case accepted")
            *invalid += 1
        else:
            assert(not agreed, "acceptable Wycheproof ECDH encoding accepted")
            *acceptable += 1

func openssl(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "openssl/ecdh.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var d: u8[32]
        var x: u8[32]
        var y: u8[32]
        var expected: u8[32]
        var out: u8[32]
        _ = try lines.decode(2, d)
        _ = try lines.decode(3, x)
        _ = try lines.decode(4, y)
        if try lines.is(0, "derive"):
            _ = try lines.decode(5, expected)
            assert(derive(d, x, y, out) and (out == expected) == try lines.is(1, "ok"), "OpenSSL ECDH mismatch")
        else:
            try p256.public_from_private(d, out, expected)
            assert((out == x and expected == y) == try lines.is(1, "ok"), "OpenSSL key pair check failed")
        count += 1
    return count

## Optional argument: the vector directory (default tests/vectors).
pub func main(arguments: str[]) -> i32!:
    let directory = arguments[1] if arguments.length > 1 else "tests/vectors"
    var out_of_scope: usize = 0
    let known = try bearssl(directory, &out_of_scope)
    let keys = try keygen()
    var valid: usize = 0
    var invalid: usize = 0
    var acceptable: usize = 0
    try wycheproof(directory, "wycheproof/ecdh_secp256r1.txt", true, &valid, &invalid, &acceptable)
    try wycheproof(directory, "wycheproof/ecdh_secp256r1_ecpoint.txt", false, &valid, &invalid, &acceptable)
    let ossl = try openssl(directory)
    assert(known == 24 and out_of_scope == 1, "unexpected BearSSL EC counts")
    assert(valid == 660 and invalid == 76 and acceptable == 231, "unexpected Wycheproof ECDH counts")
    assert(ossl == 16, "unexpected OpenSSL ECDH count")
    print(f"PASS P-256/P-384 points and P-256 ECDH: BearSSL {known} (+{out_of_scope} P-521 out of scope), keygen {keys}, Wycheproof {valid} valid, {invalid} invalid, {acceptable} acceptable refused, OpenSSL {ossl}")
    return 0