Debian Codegraph @

src/seed_priv_utils.c

raw symbols SCIP
1 #include <ge.h>
2 #include <sodium.h>
3
4 #include <xeddsa.h>
5 #include "utils.c"
6
7 /**
8 * Negate a Curve25519/Ed25519 private key if necessary, such that the corresponding Ed25519 public key has
9 * the sign bit set (or not set) as requested.
10 *
11 * @param priv_out (out): The adjusted Curve25519/Ed25519 private key.
12 * @param priv_in (in): The original Curve25519/Ed25519 private key.
13 * @param set_sign_bit: Whether the goal is for the sign bit to be set on the Ed25519 public key corresponding
14 * to the adjusted Curve25519/Ed25519 private key.
15 */
16 void priv_force_sign(uint8_t* priv_out, const uint8_t* priv_in, const bool set_sign_bit) {
17 ge_p3 ed25519_pub_ge;
18 uint8_t ed25519_pub[32];
19
20 uint8_t priv_neg[32];
21
22 // Clamp the private key before using it
23 sc_clamp(priv_out, priv_in);
24
25 // Calculate the Ed25519 public key from the private key
26 ge_scalarmult_base(&ed25519_pub_ge, priv_out);
27 ge_p3_tobytes(ed25519_pub, &ed25519_pub_ge);
28
29 // Create a negated copy of the clamped private key
30 sc_neg(priv_neg, priv_out);
31
32 // If the sign bit of the calculated Ed25519 public key is zero, the private key doesn't have to be
33 // touched. If the sign bit is one, the private key has to be inverted prior to using it. The challenge is
34 // to do so without conditional branching. This code dodges conditional branching by always calculating
35 // the negated private key and using XOR-based conditional moving of the negated private key into the
36 // untouched private key.
37 sc_cmov(priv_out, priv_neg, ((ed25519_pub[31] & 0x80) >> 7) == !set_sign_bit);
38
39 sodium_memzero(priv_neg, sizeof(priv_neg));
40 sodium_stackzero(STACKZERO_SIZE);
41 }
42
43 /**
44 * Derive the Curve25519/Ed25519 private key from a Curve25519/Ed25519 seed. Re-export of libsodiums/ref10s
45 * `crypto_sign_ed25519_sk_to_curve25519` function for convenience.
46 *
47 * @param priv (out): The Curve25519/Ed25519 private key derived from the seed.
48 * @param seed (in): The Curve25519/Ed25519 seed.
49 */
50 void seed_to_priv(uint8_t* priv, const uint8_t* seed) {
51 // Returns the constant value of 0, thus the return value can be ignored.
52 crypto_sign_ed25519_sk_to_curve25519(priv, seed);
53 }