| 1 | #include <stdbool.h> |
| 2 | #include <stdio.h> |
| 3 | #include <string.h> |
| 4 | |
| 5 | #include <sodium.h> |
| 6 | #include <xeddsa.h> |
| 7 | |
| 8 | #include <test.h> |
| 9 | |
| 10 | #define NUM_KEY_PAIRS 8192 |
| 11 | |
| 12 | int test_pub_derivation() { |
| 13 | uint8_t priv[32], curve_pub_original[32], curve_pub_derived[32]; |
| 14 | uint8_t seed[32], ed_pub_original[32], ed_pub_derived[32]; |
| 15 | |
| 16 | bool failed = false; |
| 17 | |
| 18 | // Test on a set of different key pairs |
| 19 | for (uint32_t i = 0; i < NUM_KEY_PAIRS; i++) { |
| 20 | // Generate a Curve25519 key pair |
| 21 | randombytes_buf(priv, 32); |
| 22 | priv_to_curve25519_pub(curve_pub_original, priv); |
| 23 | |
| 24 | // Derive the Curve25519 public key from the private key |
| 25 | priv_to_curve25519_pub(curve_pub_derived, priv); |
| 26 | |
| 27 | // Check whether the derived Curve25519 public key matches the original |
| 28 | if (memcmp(curve_pub_original, curve_pub_derived, 32) != 0) { |
| 29 | fprintf(stderr, "Derived Curve25519 public key does not match the original.\n"); |
| 30 | failed = true; |
| 31 | } |
| 32 | |
| 33 | // Generate an Ed25519 key pair (seed + pub) |
| 34 | randombytes_buf(seed, 32); |
| 35 | seed_to_ed25519_pub(ed_pub_original, seed); |
| 36 | |
| 37 | // Derive the Ed25519 public key from the seed (also tests private key from seed derivation) |
| 38 | seed_to_ed25519_pub(ed_pub_derived, seed); |
| 39 | |
| 40 | // Check whether the derived Ed25519 public key matches the original |
| 41 | if (memcmp(ed_pub_original, ed_pub_derived, 32) != 0) { |
| 42 | fprintf(stderr, "Derived Ed25519 public key does not match the original.\n"); |
| 43 | failed = true; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | return failed ? -1 : 0; |
| 48 | } |