Debian Codegraph @

crypto/ec/keygen.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use io;
5
6
7 // Generates a random private key scalar suitable for given curve 'c'.
8 // 'rand' must be cryptographic random stream like the one provided by
9 // [[crypto::random::stream]].
10 export fn keygen(c: *curve, priv: []u8, rand: io::handle) (size | io::error) =
11 c.keygen(c, priv, rand);
12
13 // A keygen that generates random keys until one is found that fits within
14 // the order of curve 'c'.
15 fn mask_keygen(
16 c: *curve,
17 priv: []u8,
18 rand: io::handle
19 ) (size | io::error) = {
20 const order = c.order();
21 assert(len(priv) == len(order));
22 assert(order[0] != 0);
23
24 // mask all bits until including the highest value one.
25 let mask = order[0];
26 mask |= (mask >> 1);
27 mask |= (mask >> 2);
28 mask |= (mask >> 4);
29
30 for (true) {
31 match (io::readall(rand, priv)?) {
32 case let s: size =>
33 assert(s == len(priv));
34 case io::EOF =>
35 return (0: io::underread): io::error;
36 };
37 priv[0] &= mask;
38
39 if (validate_scalar(c, priv) is void) {
40 return len(priv);
41 };
42 };
43 };