- SHA512_Bytes(&ss, digest, sizeof(digest));
- SHA512_Final(&ss, digest512);
+ SHA512_Bytes(&ss, digest, digest_len);
+
+ while (1) {
+ SHA512_State ss2 = ss; /* structure copy */
+ SHA512_Final(&ss2, digest512);
+
+ smemclr(&ss2, sizeof(ss2));
+
+ /*
+ * Now convert the result into a bignum, and reduce it mod q.
+ */
+ proto_k = bignum_from_bytes(digest512, 64);
+ k = bigmod(proto_k, modulus);
+ freebn(proto_k);
+
+ if (bignum_cmp(k, One) != 0 && bignum_cmp(k, Zero) != 0) {
+ smemclr(&ss, sizeof(ss));
+ smemclr(digest512, sizeof(digest512));
+ return k;
+ }
+
+ /* Very unlikely we get here, but if so, k was unsuitable. */
+ freebn(k);
+ /* Perturb the hash to think of a different k. */
+ SHA512_Bytes(&ss, "x", 1);
+ /* Go round and try again. */
+ }
+}