Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-crypto

Source of release 0.6.1

0.6.1 / tests / chacha_kat / main.lucb

## ChaCha20, Poly1305 and ChaCha20-Poly1305 vectors: BearSSL's ChaCha20
## known answers at every prefix length (with counter and overrun checks) and
## its AEAD known answer, every RFC 8439 Appendix A vector, and the complete
## Wycheproof chacha20_poly1305 file and OpenSSL's ChaCha20 stanzas.
import aead
import chacha
import poly1305
import vector_file

func number(field: const u8[]) -> u32:
    var value: u32 = 0
    for i in 0..<field.length: value = value * 10 + (u32)(field[i] - '0')
    return value

## BearSSL test_ChaCha20_generic: every prefix length of each known answer,
## the returned counter, no write past the prefix, and a block-wise reverse.
func bearssl_chacha(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/chacha20.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var key: u8[32]
        var nonce: u8[12]
        var plain: u8[400]
        var cipher: u8[400]
        _ = try lines.decode(0, key)
        _ = try lines.decode(1, nonce)
        let counter = number(try lines.field(2))
        let n = try lines.decode(3, plain)
        _ = try lines.decode(4, cipher)
        for v in 0..<n:
            var tmp: u8[400]
            for i in 0..<v: tmp[i] = plain[i]
            let next = try chacha.xor(key, nonce, counter, tmp[..<v], tmp[..<v])
            assert(next == counter + (u32)((v + 63) // 64), "ChaCha20 returned the wrong counter")
            assert(tmp[..<v] == cipher[..<v], "ChaCha20 prefix mismatch")
            for i in v..<tmp.length: assert(tmp[i] == 0, "ChaCha20 wrote past its output")
            var at: usize = 0
            var block = counter
            while at < v:
                let take = 64 if v - at > 64 else v - at
                assert(try chacha.xor(key, nonce, block, tmp[at..<at + take], tmp[at..<at + take]) == block + 1)
                at += take
                block += 1
            assert(tmp[..<v] == plain[..<v], "ChaCha20 block-wise decryption mismatch")
        count += 1
    return count

## Seal and open, out of place and in place, then reject a flipped tag bit.
func aead_round_trip(key: const u8[], nonce: const u8[], aad: const u8[], plain: const u8[], cipher: const u8[], tag: const u8[]) -> !:
    var out: u8[2048]
    var out_tag: u8[16]
    let n = plain.length
    try aead.seal(key, nonce, aad, plain, out[..<n], out_tag)
    assert(out[..<n] == cipher and out_tag == tag, "ChaCha20-Poly1305 seal mismatch")
    try aead.open(key, nonce, aad, cipher, tag, out[..<n])
    assert(out[..<n] == plain, "ChaCha20-Poly1305 open mismatch")
    try aead.seal(key, nonce, aad, out[..<n], out[..<n], out_tag)
    try aead.open(key, nonce, aad, out[..<n], out_tag, out[..<n])
    assert(out[..<n] == plain, "ChaCha20-Poly1305 in-place mismatch")
    out_tag[15] ^= 1
    assert(rejected(key, nonce, aad, cipher, out_tag), "ChaCha20-Poly1305 forged tag accepted")

func rejected(key: const u8[], nonce: const u8[], aad: const u8[], cipher: const u8[], tag: const u8[]) -> bool:
    var out: u8[2048]
    var refused = false
    aead.open(key, nonce, aad, cipher, tag, out[..<cipher.length]) catch failure:
        assert(failure.code == aead.forged or failure.code == aead.invalid)
        refused = true
        recover ()
    return refused

func bearssl_aead(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "bearssl/chacha20_poly1305.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var plain: u8[400]
        var aad: u8[64]
        var key: u8[32]
        var nonce: u8[12]
        var cipher: u8[400]
        var tag: u8[16]
        let n = try lines.decode(0, plain)
        let a = try lines.decode(1, aad)
        _ = try lines.decode(2, key)
        _ = try lines.decode(3, nonce)
        _ = try lines.decode(4, cipher)
        _ = try lines.decode(5, tag)
        try aead_round_trip(key, nonce, aad[..<a], plain[..<n], cipher[..<n], tag)
        count += 1
    return count

## RFC 8439 Appendix A: block function, encryption, Poly1305, Poly1305 key
## generation and AEAD decryption.
func rfc8439(directory: str) -> usize!:
    var lines = try vector_file.Lines.open(directory, "rfc/rfc8439.txt")
    defer lines.close()
    var count: usize = 0
    while lines.next():
        var key: u8[32]
        var nonce: u8[12]
        var a: u8[400]
        var b: u8[400]
        var c: u8[400]
        var out: u8[400]
        if try lines.is(0, "block"):
            _ = try lines.decode(1, key)
            _ = try lines.decode(2, nonce)
            let n = try lines.decode(4, a)
            try chacha.block(key, number(try lines.field(3)), nonce, out[..<64])
            assert(out[..<n] == a[..<n], "RFC 8439 A.1 mismatch")
        elif try lines.is(0, "encrypt"):
            _ = try lines.decode(1, key)
            _ = try lines.decode(2, nonce)
            let n = try lines.decode(4, a)
            _ = try lines.decode(5, b)
            _ = try chacha.xor(key, nonce, number(try lines.field(3)), a[..<n], out[..<n])
            assert(out[..<n] == b[..<n], "RFC 8439 A.2 mismatch")
        elif try lines.is(0, "poly1305"):
            _ = try lines.decode(1, key)
            let n = try lines.decode(2, a)
            _ = try lines.decode(3, b)
            try poly1305.authenticate(key, a[..<n], out[..<16])
            assert(out[..<16] == b[..<16], "RFC 8439 A.3 mismatch")
        elif try lines.is(0, "keygen"):
            _ = try lines.decode(1, key)
            _ = try lines.decode(2, nonce)
            _ = try lines.decode(3, b)
            var zeros: u8[64]
            _ = try chacha.xor(key, nonce, 0, zeros, out[..<64])
            assert(out[..<32] == b[..<32], "RFC 8439 A.4 mismatch")
        else:
            _ = try lines.decode(1, key)
            _ = try lines.decode(2, nonce)
            let n_aad = try lines.decode(3, c)
            let n = try lines.decode(4, a)
            _ = try lines.decode(5, b)
            var tag: u8[16]
            _ = try lines.decode(6, tag)
            try aead_round_trip(key, nonce, c[..<n_aad], a[..<n], b[..<n], tag)
        count += 1
    return count

## The complete Wycheproof chacha20_poly1305 file. Nonces other than 96 bits
## must be refused; this API reads a 24-byte nonce as XChaCha20, so such a
## case is refused by its tag.
func wycheproof(directory: str, valid: usize*, invalid: usize*) -> !:
    var lines = try vector_file.Lines.open(directory, "wycheproof/chacha20_poly1305.txt")
    defer lines.close()
    var key: u8[32]
    var iv: u8[64]
    var aad: u8[600]
    var msg: u8[600]
    var ct: u8[600]
    var tag: u8[16]
    while lines.next():
        _ = try lines.decode(1, key)
        let v = try lines.decode(2, iv)
        let a = try lines.decode(3, aad)
        let n = try lines.decode(4, msg)
        _ = try lines.decode(5, ct)
        let t = try lines.decode(6, tag)
        if try lines.is(0, "valid"):
            assert(v == 12 and t == 16)
            try aead_round_trip(key, iv[..<v], aad[..<a], msg[..<n], ct[..<n], tag)
            *valid += 1
        else:
            assert(rejected(key, iv[..<v], aad[..<a], ct[..<n], tag[..<t]), "invalid Wycheproof ChaCha20-Poly1305 case accepted")
            *invalid += 1

## OpenSSL evpciph_chacha.txt: raw ChaCha20 (a 16-byte IV of little-endian
## counter and nonce) and ChaCha20-Poly1305, including its refused IV lengths
## and a forged tag.
func openssl(directory: str, passed: usize*, refused: usize*) -> !:
    var lines = try vector_file.Lines.open(directory, "openssl/cipher.txt")
    defer lines.close()
    var key: u8[32]
    var iv: u8[16]
    var aad: u8[64]
    var plain: u8[2048]
    var cipher: u8[2048]
    var out: u8[2048]
    var tag: u8[16]
    while lines.next():
        if not (try lines.is(0, "chacha20")) and not (try lines.is(0, "chacha20-poly1305")):
            continue
        _ = try lines.decode(3, key)
        let v = try lines.decode(4, iv)
        let p = try lines.decode(6, plain)
        let c = 0 if try lines.is(7, "absent") else try lines.decode(7, cipher)
        if try lines.is(0, "chacha20"):
            assert(v == 16 and p == c and try lines.is(2, "ok"))
            let counter = (u32)iv[0] | ((u32)iv[1] << 8) | ((u32)iv[2] << 16) | ((u32)iv[3] << 24)
            _ = try chacha.xor(key, iv[4..<16], counter, plain[..<p], out[..<p])
            assert(out[..<p] == cipher[..<c], "OpenSSL ChaCha20 mismatch")
            *passed += 1
            continue
        let a = try lines.decode(5, aad)
        _ = try lines.decode(8, tag)
        if try lines.is(2, "ok"):
            try aead_round_trip(key, iv[..<v], aad[..<a], plain[..<p], cipher[..<c], tag)
            *passed += 1
        elif try lines.is(2, "INVALID_IV_LENGTH"):
            var failed = false
            aead.seal(key, iv[..<v], aad[..<a], plain[..<p], out[..<p], tag) catch failure:
                assert(failure.code == aead.invalid)
                failed = true
                recover ()
            assert(failed, "ChaCha20-Poly1305 accepted an invalid IV length")
            *refused += 1
        else:
            assert(rejected(key, iv[..<v], aad[..<a], cipher[..<c], tag), "forged OpenSSL ChaCha20-Poly1305 accepted")
            *refused += 1

## 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"
    let chacha_count = try bearssl_chacha(directory)
    let aead_count = try bearssl_aead(directory)
    let rfc = try rfc8439(directory)
    var valid: usize = 0
    var invalid: usize = 0
    try wycheproof(directory, &valid, &invalid)
    var ossl_passed: usize = 0
    var ossl_refused: usize = 0
    try openssl(directory, &ossl_passed, &ossl_refused)
    assert(ossl_passed == 24 and ossl_refused == 3, "unexpected OpenSSL ChaCha20 counts")
    assert(chacha_count == 3 and aead_count == 1 and rfc == 23, "unexpected BearSSL/RFC ChaCha20 counts")
    assert(valid == 256 and invalid == 69, "unexpected Wycheproof ChaCha20-Poly1305 counts")
    print(f"PASS ChaCha20/Poly1305: BearSSL {chacha_count} ChaCha20 (all prefixes) + {aead_count} AEAD, RFC 8439 {rfc}, Wycheproof {valid} valid, {invalid} invalid, OpenSSL {ossl_passed} ok, {ossl_refused} refused")
    return 0