verify.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "ed25519.h"
  2. #include "sha512.h"
  3. #include "ge.h"
  4. #include "sc.h"
  5. static int consttime_equal(const unsigned char *x, const unsigned char *y) {
  6. unsigned char r = 0;
  7. r = x[0] ^ y[0];
  8. #define F(i) r |= x[i] ^ y[i]
  9. F(1);
  10. F(2);
  11. F(3);
  12. F(4);
  13. F(5);
  14. F(6);
  15. F(7);
  16. F(8);
  17. F(9);
  18. F(10);
  19. F(11);
  20. F(12);
  21. F(13);
  22. F(14);
  23. F(15);
  24. F(16);
  25. F(17);
  26. F(18);
  27. F(19);
  28. F(20);
  29. F(21);
  30. F(22);
  31. F(23);
  32. F(24);
  33. F(25);
  34. F(26);
  35. F(27);
  36. F(28);
  37. F(29);
  38. F(30);
  39. F(31);
  40. #undef F
  41. return !r;
  42. }
  43. int ed25519_verify(const unsigned char *signature, const unsigned char *message, size_t message_len, const unsigned char *public_key) {
  44. unsigned char h[64];
  45. unsigned char checker[32];
  46. sha512_context hash;
  47. ge_p3 A;
  48. ge_p2 R;
  49. if (signature[63] & 224) {
  50. return 0;
  51. }
  52. if (ge_frombytes_negate_vartime(&A, public_key) != 0) {
  53. return 0;
  54. }
  55. sha512_init(&hash);
  56. sha512_update(&hash, signature, 32);
  57. sha512_update(&hash, public_key, 32);
  58. sha512_update(&hash, message, message_len);
  59. sha512_final(&hash, h);
  60. sc_reduce(h);
  61. ge_double_scalarmult_vartime(&R, h, &A, signature + 32);
  62. ge_tobytes(checker, &R);
  63. if (!consttime_equal(checker, signature)) {
  64. return 0;
  65. }
  66. return 1;
  67. }