Align DH keygen with NIST's formulation when q is available

Section 5.6.1.1.4 of SP 800-56A Rev 3 and Appendix B.1.2 of FIPS 186-4
select the private key out of the range [1, q-1]. We used [2, q-1]. This
distinction is unimportant. 0, 1, 2, 3, 4, etc. all make equally bad
private keys. The defense against each of these is their negligible
probability, not rejection sampling.

Nonetheless, we may as well align with *some* specification, and NIST's
formulation works fine.

Change-Id: I33352061f3fbdbec5b14b576d15be98464a57536
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/62227
Commit-Queue: David Benjamin <davidben@google.com>
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/fipsmodule/dh/dh.c b/crypto/fipsmodule/dh/dh.c
index 1e8971a..400a8eb 100644
--- a/crypto/fipsmodule/dh/dh.c
+++ b/crypto/fipsmodule/dh/dh.c
@@ -229,7 +229,13 @@
 
   if (generate_new_key) {
     if (dh->q) {
-      if (!BN_rand_range_ex(priv_key, 2, dh->q)) {
+      // Section 5.6.1.1.4 of SP 800-56A Rev3 generates a private key uniformly
+      // from [1, min(2^N-1, q-1)].
+      //
+      // Although SP 800-56A Rev3 now permits a private key length N,
+      // |dh->priv_length| historically was ignored when q is available. We
+      // continue to ignore it and interpret such a configuration as N = len(q).
+      if (!BN_rand_range_ex(priv_key, 1, dh->q)) {
         goto err;
       }
     } else {