| 1 |
#include <string.h> |
| 2 |
#include "ge.h" |
| 3 |
#include "crypto_additions.h" |
| 4 |
#include "zeroize.h" |
| 5 |
#include "xeddsa.h" |
| 6 |
#include "crypto_verify_32.h" |
| 7 |
|
| 8 |
int xed25519_sign(unsigned char* signature_out, |
| 9 |
const unsigned char* curve25519_privkey, |
| 10 |
const unsigned char* msg, const unsigned long msg_len, |
| 11 |
const unsigned char* random) |
| 12 |
{ |
| 13 |
unsigned char a[32], aneg[32]; |
| 14 |
unsigned char A[32]; |
| 15 |
ge_p3 ed_pubkey_point; |
| 16 |
unsigned char *sigbuf; /* working buffer */ |
| 17 |
unsigned char sign_bit = 0; |
| 18 |
|
| 19 |
if ((sigbuf = malloc(msg_len + 128)) == 0) { |
| 20 |
memset(signature_out, 0, 64); |
| 21 |
return -1; |
| 22 |
} |
| 23 |
|
| 24 |
/* Convert the Curve25519 privkey to an Ed25519 public key */ |
| 25 |
ge_scalarmult_base(&ed_pubkey_point, curve25519_privkey); |
| 26 |
ge_p3_tobytes(A, &ed_pubkey_point); |
| 27 |
|
| 28 |
/* Force Edwards sign bit to zero */ |
| 29 |
sign_bit = (A[31] & 0x80) >> 7; |
| 30 |
memcpy(a, curve25519_privkey, 32); |
| 31 |
sc_neg(aneg, a); |
| 32 |
sc_cmov(a, aneg, sign_bit); |
| 33 |
A[31] &= 0x7F; |
| 34 |
|
| 35 |
/* Perform an Ed25519 signature with explicit private key */ |
| 36 |
crypto_sign_modified(sigbuf, msg, msg_len, a, A, random); |
| 37 |
memmove(signature_out, sigbuf, 64); |
| 38 |
|
| 39 |
zeroize(a, 32); |
| 40 |
zeroize(aneg, 32); |
| 41 |
free(sigbuf); |
| 42 |
return 0; |
| 43 |
} |
| 44 |
|
| 45 |
int xed25519_verify(const unsigned char* signature, |
| 46 |
const unsigned char* curve25519_pubkey, |
| 47 |
const unsigned char* msg, const unsigned long msg_len) |
| 48 |
{ |
| 49 |
fe u; |
| 50 |
fe y; |
| 51 |
unsigned char ed_pubkey[32]; |
| 52 |
unsigned char verifybuf[MAX_MSG_LEN + 64]; /* working buffer */ |
| 53 |
unsigned char verifybuf2[MAX_MSG_LEN + 64]; /* working buffer #2 */ |
| 54 |
|
| 55 |
if (msg_len > MAX_MSG_LEN) { |
| 56 |
return -1; |
| 57 |
} |
| 58 |
|
| 59 |
/* Convert the Curve25519 public key into an Ed25519 public key. |
| 60 |
|
| 61 |
y = (u - 1) / (u + 1) |
| 62 |
|
| 63 |
NOTE: u=-1 is converted to y=0 since fe_invert is mod-exp |
| 64 |
*/ |
| 65 |
if (!fe_isreduced(curve25519_pubkey)) |
| 66 |
return -1; |
| 67 |
fe_frombytes(u, curve25519_pubkey); |
| 68 |
fe_montx_to_edy(y, u); |
| 69 |
fe_tobytes(ed_pubkey, y); |
| 70 |
|
| 71 |
memmove(verifybuf, signature, 64); |
| 72 |
memmove(verifybuf+64, msg, msg_len); |
| 73 |
|
| 74 |
/* Then perform a normal Ed25519 verification, return 0 on success */ |
| 75 |
/* The below call has a strange API: */ |
| 76 |
/* verifybuf = R || S || message */ |
| 77 |
/* verifybuf2 = internal to next call gets a copy of verifybuf, S gets |
| 78 |
replaced with pubkey for hashing */ |
| 79 |
return crypto_sign_open_modified(verifybuf2, verifybuf, 64 + msg_len, ed_pubkey); |
| 80 |
} |