hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

validate.ha (1362B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 // Checks whether the point is encoded in the curves point format. Does NOT
      5 // check if it is a valid point on the curve. For such point validation use
      6 // [[validate_point]].
      7 export fn validate_pointformat(c: *curve, p: []u8) (void | invalid) = {
      8 	if (len(p) != c.pointsz || p[0] != 0x04) {
      9 		return invalid;
     10 	};
     11 };
     12 
     13 // Checks if given point is properly encoded and a valid point on given curve
     14 // 'c'. This operation is quite expensive. Note that in any case point
     15 // validation will be done on every mul and muladd operation.
     16 export fn validate_point(c: *curve, p: []u8) (void | invalid) = {
     17 	validate_pointformat(c, p)?;
     18 
     19 	static let scalarbuf: [MAX_POINTSZ]u8 = [0...];
     20 	let scalarbuf = scalarbuf[..len(c.order())];
     21 	scalarbuf[len(scalarbuf) - 1] = 1;
     22 
     23 	if (c.mul(p, scalarbuf) == 0) {
     24 		return invalid;
     25 	};
     26 };
     27 
     28 // Validates if given scalar is less than the curve order and greater then zero.
     29 export fn validate_scalar(c: *curve, n: []u8) (void | invalid) = {
     30 	const order = c.order();
     31 	let cc: u16 = 0;
     32 	let zz: u8 = 0;
     33 	for (let i = len(n); i > 0; i -= 1) {
     34 		// subtraction with carry
     35 		cc = ((n[i - 1]: u16 - order[i - 1] - cc) >> 8) & 1;
     36 		zz |= n[i - 1];
     37 	};
     38 
     39 	// cc == 0 means the carry is not set because order < priv
     40 	if (cc == 0 || zz == 0) {
     41 		return invalid;
     42 	};
     43 };