b6335f3993c42b1b7adfbeb37497f1609273016b
[trex.git] /
1
2 #include <string.h>
3
4 #include "api.h"
5 #include "crypto_hash_sha512.h"
6 #include "crypto_scalarmult_curve25519.h"
7 #include "randombytes.h"
8 #include "utils.h"
9 #include "fe.h"
10 #include "ge.h"
11
12 int crypto_sign_seed_keypair(unsigned char *pk, unsigned char *sk,
13                              const unsigned char *seed)
14 {
15     ge_p3 A;
16
17     crypto_hash_sha512(sk,seed,32);
18     sk[0] &= 248;
19     sk[31] &= 63;
20     sk[31] |= 64;
21
22     ge_scalarmult_base(&A,sk);
23     ge_p3_tobytes(pk,&A);
24
25     memmove(sk, seed, 32);
26     memmove(sk + 32, pk, 32);
27     return 0;
28 }
29
30 int crypto_sign_keypair(unsigned char *pk, unsigned char *sk)
31 {
32     unsigned char seed[32];
33     int           ret;
34
35     randombytes_buf(seed, sizeof seed);
36     ret = crypto_sign_seed_keypair(pk, sk, seed);
37     sodium_memzero(seed, sizeof seed);
38
39     return ret;
40 }
41
42 int crypto_sign_ed25519_pk_to_curve25519(unsigned char *curve25519_pk,
43                                          const unsigned char *ed25519_pk)
44 {
45     ge_p3 A;
46     fe    x;
47     fe    one_minus_y;
48
49     if (ge_frombytes_negate_vartime(&A, ed25519_pk) != 0) {
50         return -1;
51     }
52     fe_1(one_minus_y);
53     fe_sub(one_minus_y, one_minus_y, A.Y);
54     fe_invert(one_minus_y, one_minus_y);
55     fe_1(x);
56     fe_add(x, x, A.Y);
57     fe_mul(x, x, one_minus_y);
58     fe_tobytes(curve25519_pk, x);
59
60     return 0;
61 }
62
63 int crypto_sign_ed25519_sk_to_curve25519(unsigned char *curve25519_sk,
64                                          const unsigned char *ed25519_sk)
65 {
66     unsigned char h[crypto_hash_sha512_BYTES];
67
68     crypto_hash_sha512(h, ed25519_sk,
69                        crypto_sign_ed25519_SECRETKEYBYTES -
70                        crypto_sign_ed25519_PUBLICKEYBYTES);
71     h[0] &= 248;
72     h[31] &= 127;
73     h[31] |= 64;
74     memcpy(curve25519_sk, h, crypto_scalarmult_curve25519_BYTES);
75     sodium_memzero(h, sizeof h);
76
77     return 0;
78 }