local testimony = require("testimony") local litls = require("litls.core") local hex = litls.hex_encode local unhex = litls.hex_decode local testify = testimony.new("== LITLS ECDSA P-256 ==") testify:that("P-256 keygen produces correct key sizes", function() local priv, pub = litls.p256_keygen() testimony.assert_equal(32, #priv) testimony.assert_equal(65, #pub) -- Uncompressed point format: starts with 0x04 testimony.assert_equal(4, string.byte(pub, 1)) end) testify:that("P-256 sign/verify round-trip with SHA-256", function() local priv, pub = litls.p256_keygen() local hash = litls.sha256("test message for ECDSA") local sig = litls.p256_ecdsa_sign(hash, priv) testimony.assert_equal(64, #sig) local ok = litls.p256_ecdsa_verify(hash, pub, sig) testimony.assert_equal(true, ok) end) testify:that("P-256 verify rejects wrong hash", function() local priv, pub = litls.p256_keygen() local hash = litls.sha256("correct message") local sig = litls.p256_ecdsa_sign(hash, priv) local wrong_hash = litls.sha256("wrong message") local ok = litls.p256_ecdsa_verify(wrong_hash, pub, sig) testimony.assert_equal(false, ok) end) testify:that("P-256 verify rejects wrong public key", function() local priv1, pub1 = litls.p256_keygen() local _, pub2 = litls.p256_keygen() local hash = litls.sha256("message") local sig = litls.p256_ecdsa_sign(hash, priv1) local ok = litls.p256_ecdsa_verify(hash, pub2, sig) testimony.assert_equal(false, ok) end) -- RFC 6979 A.2.5 - ECDSA with P-256 and SHA-256 known-answer vector testify:that("P-256 ECDSA deterministic signature (RFC 6979 A.2.5)", function() -- Private key from RFC 6979 A.2.5 local x = unhex("C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721") -- Message: "sample" local hash = litls.sha256("sample") local sig = litls.p256_ecdsa_sign(hash, x) -- Expected r and s from RFC 6979 A.2.5 local r = string.sub(sig, 1, 32) local s = string.sub(sig, 33, 64) testimony.assert_equal("efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716", hex(r)) testimony.assert_equal("f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8", hex(s)) end) testify:that("P-256 multiple keygens produce different keys", function() local priv1, pub1 = litls.p256_keygen() local priv2, pub2 = litls.p256_keygen() -- Extremely unlikely to be equal with random generation testimony.assert_equal(true, hex(priv1) ~= hex(priv2)) testimony.assert_equal(true, hex(pub1) ~= hex(pub2)) end) testify:conclude()