Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-crypto

Source of release 0.6.0

0.6.0 / src / vector_file.lucb

## Test support: reads the line-oriented vector files under tests/vectors/
## (written by tools/wycheproof.py). A line is space-separated fields; "-" is
## an empty field. Not exported by the package.
import c
import interop
from luce_std import files
import sha2

## A whole vector file and a cursor over its lines and fields.
pub struct Lines:
    var contents: interop.Owned[const u8[]]?
    var text: const u8[]
    var line_start: usize
    var line_end: usize
    var next_start: usize

    ## Load `directory`/`name`.
    pub static func open(directory: str, name: str) -> Lines!:
        var path: u8[1024]
        if directory.length + name.length + 2 > path.length:
            error(sha2.invalid, "vector path is too long")
        for i in 0..<directory.length:
            path[i] = directory.bytes[i]
        path[directory.length] = '/'
        for i in 0..<name.length:
            path[directory.length + 1 + i] = name.bytes[i]
        let size = directory.length + 1 + name.length
        path[size] = 0
        let contents = try files.read((c.str)(str)path[..<size])
        return Lines(contents = contents, text = contents.value)

    ## Release the file contents.
    pub func close():
        if let contents = self.contents:
            contents.release()
        self.contents = none
        self.text = self.text[..<0]

    ## Advance to the next nonempty line; false at the end of the file.
    pub func next() -> bool:
        while self.next_start < self.text.length:
            self.line_start = self.next_start
            var end = self.line_start
            while end < self.text.length and self.text[end] != '\n':
                end += 1
            self.line_end = end
            self.next_start = end + 1
            if end > self.line_start:
                return true
        return false

    ## The raw text of field `index` (0-based) on the current line.
    pub func field(index: usize) -> const u8[]!:
        var at = self.line_start
        var current: usize = 0
        while at < self.line_end:
            var end = at
            while end < self.line_end and self.text[end] != ' ':
                end += 1
            if current == index:
                let value = self.text[at..<end]
                if value.length == 1 and value[0] == '-':
                    return value[..<0]
                return value
            current += 1
            at = end + 1
        error(sha2.invalid, "vector line has too few fields")

    ## The number of fields on the current line.
    pub func count() -> usize:
        var fields: usize = 0
        var at = self.line_start
        while at < self.line_end:
            fields += 1
            while at < self.line_end and self.text[at] != ' ':
                at += 1
            at += 1
        return fields

    ## Whether field `index` equals `word`.
    pub func is(index: usize, word: str) -> bool!:
        let value = try self.field(index)
        if value.length != word.length:
            return false
        for i in 0..<value.length:
            if value[i] != word.bytes[i]:
                return false
        return true

    ## Decode hex field `index` into `out`; returns the byte count.
    pub func decode(index: usize, out: u8[]) -> usize!:
        return try decode_hex(try self.field(index), out)

## Decode hex text ("-" is empty) into `out`; returns the byte count.
pub func decode_hex(value: const u8[], out: u8[]) -> usize!:
    if value.length == 1 and value[0] == '-':
        return 0
    if value.length % 2 != 0 or value.length // 2 > out.length:
        error(sha2.invalid, "vector hex field has an odd length or is too long")
    for i in 0..<value.length // 2:
        out[i] = (try nibble(value[2 * i]) << 4) | try nibble(value[2 * i + 1])
    return value.length // 2

func nibble(digit: u8) -> u8!:
    if digit >= '0' and digit <= '9': return digit - '0'
    if digit >= 'a' and digit <= 'f': return digit - 'a' + 10
    if digit >= 'A' and digit <= 'F': return digit - 'A' + 10
    error(sha2.invalid, "vector field is not hex")

## Strictly decode a DER Ecdsa-Sig-Value into fixed-width big-endian r and s;
## false when it is not minimal DER or a value is wider than the outputs.
pub func ecdsa_from_der(der: const u8[], r: u8[], s: u8[]) -> bool:
    if der.length < 8 or der[0] != 0x30:
        return false
    var at: usize = 2
    var length = (usize)der[1]
    if der[1] == 0x81:
        if der[2] < 0x80:
            return false
        length = (usize)der[2]
        at = 3
    elif der[1] >= 0x80:
        return false
    if length != der.length - at:
        return false
    let after_r = der_integer(der, at, r) else return false
    let after_s = der_integer(der, after_r, s) else return false
    return after_s == der.length

func der_integer(der: const u8[], at: usize, out: u8[]) -> usize?:
    if der.length - at < 3 or der[at] != 0x02 or der[at + 1] >= 0x80:
        return none
    let length = (usize)der[at + 1]
    let start = at + 2
    if length == 0 or length > der.length - start or (der[start] & 0x80) != 0:
        return none
    if length > 1 and der[start] == 0 and der[start + 1] < 0x80:
        return none
    var first = start
    var count = length
    if count > 1 and der[first] == 0:
        first += 1
        count -= 1
    if count > out.length:
        return none
    for i in 0..<out.length:
        out[i] = 0
    for i in 0..<count:
        out[out.length - count + i] = der[first + i]
    return start + length

## DER-encode (r, s) into `out`; returns its length.
pub func ecdsa_to_der(r: const u8[], s: const u8[], out: u8[]) -> usize:
    var body: u8[140]
    var used: usize = 0
    for part in 0..<(usize)2:
        let value = r if part == 0 else s
        var first: usize = 0
        while first + 1 < value.length and value[first] == 0:
            first += 1
        let sign = value[first] >= 0x80
        body[used] = 0x02
        body[used + 1] = (u8)(value.length - first + (1 if sign else 0))
        used += 2
        if sign:
            body[used] = 0
            used += 1
        for i in first..<value.length:
            body[used] = value[i]
            used += 1
    var at: usize = 0
    out[at] = 0x30
    at += 1
    if used >= 0x80:
        out[at] = 0x81
        at += 1
    out[at] = (u8)used
    at += 1
    for i in 0..<used:
        out[at + i] = body[i]
    return at + used