x25519.ha (1390B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 use crypto::curve25519; 5 6 // Type for private, public or shared keys. 7 export type key = [KEYSZ]u8; 8 9 // The size of a x25519 key. 10 export def KEYSZ: size = 32; 11 12 // The size of a x25519 key seed. 13 export def SEEDSZ: size = 32; 14 15 // Initializes a new x25519 private key from the provided 32-byte seed, 16 // which should be generated with [[crypto::random::]]. 17 export fn newkey(priv: []u8, seed: []u8) void = { 18 assert(len(priv) == KEYSZ); 19 assert(len(seed) == SEEDSZ); 20 21 priv[..] = seed[..]; 22 curve25519::clamp(priv); 23 }; 24 25 // Derives the public key from a private key prepared with [[newkey]], 26 // writing it to the 'pub' parameter. 27 export fn pubkey(pub: []u8, priv: const []u8) void = { 28 assert(len(priv) == KEYSZ); 29 assert(len(pub) == KEYSZ); 30 31 curve25519::scalarmult_base(pub, priv); 32 }; 33 34 // Derives a 32-byte shared key from the private key of one key-pair and 35 // the public key of a second key-pair. 36 export fn derive(shared: []u8, priv: []u8, pub: []u8) void = { 37 assert(len(shared) == KEYSZ); 38 assert(len(priv) == KEYSZ); 39 assert(len(pub) == KEYSZ); 40 41 curve25519::x25519(shared, priv, pub); 42 43 // TODO figure out if checking for low order points is required 44 // https://github.com/jedisct1/libsodium/blob/cec56d867f741e66f78b9fde37d9081643599a2a/src/libsodium/crypto_scalarmult/curve25519/ref10/x25519_ref10.c#L90 45 };