2 #include "knuth-lfib.h"
4 /* Check if y^2 = x^3 - 3x + b */
6 ecc_valid_p (struct ecc_point *pub)
13 size = pub->ecc->p.size;
15 /* First check range */
16 if (mpn_cmp (pub->p, pub->ecc->p.m, size) >= 0
17 || mpn_cmp (pub->p + size, pub->ecc->p.m, size) >= 0)
23 mpz_roinit_n (x, pub->p, size);
24 mpz_roinit_n (y, pub->p + size, size);
28 if (pub->ecc->p.bit_size == 255)
31 121666 (1 + x^2 - y^2) = 121665 x^2 y^2 */
34 mpz_mul (x2, x, x); /* x^2 */
35 mpz_mul (rhs, x2, lhs); /* x^2 y^2 */
36 mpz_sub (lhs, x2, lhs); /* x^2 - y^2 */
37 mpz_add_ui (lhs, lhs, 1); /* 1 + x^2 - y^2 */
38 mpz_mul_ui (lhs, lhs, 121666);
39 mpz_mul_ui (rhs, rhs, 121665);
45 /* Check y^2 = x^3 - 3 x + b */
47 mpz_sub_ui (rhs, rhs, 3);
48 mpz_mul (rhs, rhs, x);
49 mpz_add (rhs, rhs, mpz_roinit_n (t, pub->ecc->b, size));
51 res = mpz_congruent_p (lhs, rhs, mpz_roinit_n (t, pub->ecc->p.m, size));
63 struct knuth_lfib_ctx rctx;
64 struct dsa_signature signature;
66 struct tstring *digest;
68 knuth_lfib_init (&rctx, 4711);
69 dsa_signature_init (&signature);
71 digest = SHEX (/* sha256("abc") */
72 "BA7816BF 8F01CFEA 414140DE 5DAE2223"
73 "B00361A3 96177A9C B410FF61 F20015AD");
75 for (i = 0; ecc_curves[i]; i++)
77 const struct ecc_curve *ecc = ecc_curves[i];
79 struct ecc_scalar key;
82 fprintf (stderr, "Curve %d\n", ecc->p.bit_size);
84 ecc_point_init (&pub, ecc);
85 ecc_scalar_init (&key, ecc);
87 ecdsa_generate_keypair (&pub, &key,
89 (nettle_random_func *) knuth_lfib_random);
93 fprintf (stderr, "Public key:\nx = ");
94 write_mpn (stderr, 16, pub.p, ecc->p.size);
95 fprintf (stderr, "\ny = ");
96 write_mpn (stderr, 16, pub.p + ecc->p.size, ecc->p.size);
97 fprintf (stderr, "\nPrivate key: ");
98 write_mpn (stderr, 16, key.p, ecc->p.size);
99 fprintf (stderr, "\n");
101 if (!ecc_valid_p (&pub))
102 die ("ecdsa_generate_keypair produced an invalid point.\n");
105 &rctx, (nettle_random_func *) knuth_lfib_random,
106 digest->length, digest->data,
109 if (!ecdsa_verify (&pub, digest->length, digest->data,
111 die ("ecdsa_verify failed.\n");
113 digest->data[3] ^= 17;
114 if (ecdsa_verify (&pub, digest->length, digest->data,
116 die ("ecdsa_verify returned success with invalid digest.\n");
117 digest->data[3] ^= 17;
119 mpz_combit (signature.r, 117);
120 if (ecdsa_verify (&pub, digest->length, digest->data,
122 die ("ecdsa_verify returned success with invalid signature.r.\n");
124 mpz_combit (signature.r, 117);
125 mpz_combit (signature.s, 93);
126 if (ecdsa_verify (&pub, digest->length, digest->data,
128 die ("ecdsa_verify returned success with invalid signature.s.\n");
130 ecc_point_clear (&pub);
131 ecc_scalar_clear (&key);
133 dsa_signature_clear (&signature);