Add ECDSA2 KeyPair CAVP test driver.

Change-Id: I64533d2b4a6b075fa3ccea1abfd0ec5106673453
Reviewed-on: https://boringssl-review.googlesource.com/15704
Reviewed-by: David Benjamin <davidben@google.com>
Commit-Queue: David Benjamin <davidben@google.com>
CQ-Verified: CQ bot account: commit-bot@chromium.org <commit-bot@chromium.org>
diff --git a/crypto/test/file_test.cc b/crypto/test/file_test.cc
index a0afabb..a730a66 100644
--- a/crypto/test/file_test.cc
+++ b/crypto/test/file_test.cc
@@ -130,6 +130,12 @@
         // Delimit instruction block from test with a blank line.
         current_test_ += "\r\n";
       }
+    } else if (buf[0] == '#' ||
+               strcmp("[B.4.2 Key Pair Generation by Testing Candidates]\r\n",
+                      buf.get()) == 0) {
+      // Ignore comments. The above instruction-like line is treated as a
+      // comment because the FIPS lab's request files are hopelessly
+      // inconsistent.
     } else if (buf[0] == '[') {  // Inside an instruction block.
       if (start_line_ != 0) {
         // Instructions should be separate blocks.
@@ -163,7 +169,7 @@
           break;
         kv = kv.substr(idx + 1);
       }
-    } else if (buf[0] != '#') {  // Comment lines are ignored.
+    } else {
       if (in_instruction_block) {
         // Test cases should be separate blocks.
         fprintf(stderr, "Line %u is a test case attribute in an instruction block.\n",
diff --git a/fipsoracle/CMakeLists.txt b/fipsoracle/CMakeLists.txt
index 11215e0..ca0b6cf 100644
--- a/fipsoracle/CMakeLists.txt
+++ b/fipsoracle/CMakeLists.txt
@@ -18,6 +18,14 @@
   )
 
   add_executable(
+    cavp_ecdsa2_keypair_test
+
+    cavp_ecdsa2_keypair_test.cc
+    cavp_test_util.cc
+    $<TARGET_OBJECTS:test_support>
+  )
+
+  add_executable(
     cavp_ecdsa2_pkv_test
 
     cavp_ecdsa2_pkv_test.cc
@@ -71,6 +79,7 @@
   target_link_libraries(cavp_aes_test crypto)
   target_link_libraries(cavp_aes_gcm_test crypto)
 
+  target_link_libraries(cavp_ecdsa2_keypair_test crypto)
   target_link_libraries(cavp_ecdsa2_pkv_test crypto)
   target_link_libraries(cavp_ecdsa2_siggen_test crypto)
   target_link_libraries(cavp_ecdsa2_sigver_test crypto)
diff --git a/fipsoracle/cavp_ecdsa2_keypair_test.cc b/fipsoracle/cavp_ecdsa2_keypair_test.cc
new file mode 100644
index 0000000..d342254
--- /dev/null
+++ b/fipsoracle/cavp_ecdsa2_keypair_test.cc
@@ -0,0 +1,96 @@
+/* Copyright (c) 2017, Google Inc.
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
+ * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+ * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
+
+// cavp_ecdsa2_keypair_test processes a NIST CAVP ECDSA2 KeyPair test vector
+// request file and emits the corresponding response.
+
+#include <stdlib.h>
+
+#include <vector>
+
+#include <openssl/bn.h>
+#include <openssl/crypto.h>
+#include <openssl/ec_key.h>
+#include <openssl/err.h>
+#include <openssl/nid.h>
+
+#include "../crypto/test/file_test.h"
+#include "cavp_test_util.h"
+
+
+static bool TestECDSA2KeyPair(FileTest *t, void *arg) {
+  std::string n_str;
+  const char *group_str;
+  int nid = GetECGroupNIDFromInstruction(t, &group_str);
+  if (nid == NID_undef ||
+      !t->GetAttribute(&n_str, "N")) {
+    return false;
+  }
+
+  // Don't use CurrentTestToString to avoid printing the N.
+  printf(
+      "[%s]\r\n\r\n[B.4.2 Key Pair Generation by Testing Candidates]\r\n\r\n",
+      group_str);
+
+  unsigned long n = strtoul(n_str.c_str(), nullptr, 10);
+  for (unsigned long i = 0; i < n; i++) {
+    bssl::UniquePtr<BIGNUM> qx(BN_new()), qy(BN_new());
+    bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(nid));
+    if (!key ||
+        !EC_KEY_generate_key(key.get()) ||
+        !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(key.get()),
+                                             EC_KEY_get0_public_key(key.get()),
+                                             qx.get(), qy.get(), nullptr)) {
+      return false;
+    }
+
+    size_t degree_len =
+        (EC_GROUP_get_degree(EC_KEY_get0_group(key.get())) + 7) / 8;
+    size_t order_len =
+        BN_num_bytes(EC_GROUP_get0_order(EC_KEY_get0_group(key.get())));
+    std::vector<uint8_t> qx_bytes(degree_len), qy_bytes(degree_len);
+    std::vector<uint8_t> d_bytes(order_len);
+    if (!BN_bn2bin_padded(qx_bytes.data(), qx_bytes.size(), qx.get()) ||
+        !BN_bn2bin_padded(qy_bytes.data(), qy_bytes.size(), qy.get()) ||
+        !BN_bn2bin_padded(d_bytes.data(), d_bytes.size(),
+                          EC_KEY_get0_private_key(key.get()))) {
+      return false;
+    }
+
+    printf("Qx = %s\r\nQy = %s\r\nd = %s\r\n\r\n",
+           EncodeHex(qx_bytes.data(), qx_bytes.size()).c_str(),
+           EncodeHex(qy_bytes.data(), qy_bytes.size()).c_str(),
+           EncodeHex(d_bytes.data(), d_bytes.size()).c_str());
+  }
+
+  return true;
+}
+
+int main(int argc, char **argv) {
+  CRYPTO_library_init();
+
+  if (argc != 2) {
+    fprintf(stderr, "usage: %s <test file>\n",
+            argv[0]);
+    return 1;
+  }
+
+  printf("# Generated by");
+  for (int i = 0; i < argc; i++) {
+    printf(" %s", argv[i]);
+  }
+  printf("\r\n\r\n");
+
+  return FileTestMainSilent(TestECDSA2KeyPair, nullptr, argv[1]);
+}
diff --git a/fipsoracle/cavp_test_util.cc b/fipsoracle/cavp_test_util.cc
index c3d2cdf..b8578fa 100644
--- a/fipsoracle/cavp_test_util.cc
+++ b/fipsoracle/cavp_test_util.cc
@@ -181,17 +181,26 @@
   return ret;
 }
 
-int GetECGroupNIDFromInstruction(FileTest *t) {
+int GetECGroupNIDFromInstruction(FileTest *t, const char **out_str) {
+  const char *dummy;
+  if (out_str == nullptr) {
+    out_str = &dummy;
+  }
+
   if (t->HasInstruction("P-224")) {
+    *out_str = "P-224";
     return NID_secp224r1;
   }
   if (t->HasInstruction("P-256")) {
+    *out_str = "P-256";
     return NID_X9_62_prime256v1;
   }
   if (t->HasInstruction("P-384")) {
+    *out_str = "P-384";
     return NID_secp384r1;
   }
   if (t->HasInstruction("P-521")) {
+    *out_str = "P-521";
     return NID_secp521r1;
   }
   t->PrintLine("No supported group specified.");
diff --git a/fipsoracle/cavp_test_util.h b/fipsoracle/cavp_test_util.h
index 44bb496..3f5330c 100644
--- a/fipsoracle/cavp_test_util.h
+++ b/fipsoracle/cavp_test_util.h
@@ -48,7 +48,7 @@
 
 bssl::UniquePtr<BIGNUM> GetBIGNUM(FileTest *t, const char *attribute);
 
-int GetECGroupNIDFromInstruction(FileTest *t);
+int GetECGroupNIDFromInstruction(FileTest *t, const char **out_str = nullptr);
 
 const EVP_MD *GetDigestFromInstruction(FileTest *t);
 
diff --git a/fipsoracle/run_cavp.go b/fipsoracle/run_cavp.go
index 84cdef0..95483e0 100644
--- a/fipsoracle/run_cavp.go
+++ b/fipsoracle/run_cavp.go
@@ -99,6 +99,12 @@
 	},
 }
 
+var ecdsa2KeyPairTests = testSuite{
+	"ECDSA2",
+	"cavp_ecdsa2_keypair_test",
+	[]test{{"KeyPair", nil, true}},
+}
+
 var ecdsa2PKVTests = testSuite{
 	"ECDSA2",
 	"cavp_ecdsa2_pkv_test",
@@ -159,6 +165,7 @@
 	&aesGCMTests,
 	&aesTests,
 	&ctrDRBGTests,
+	&ecdsa2KeyPairTests,
 	&ecdsa2PKVTests,
 	&ecdsa2SigGenTests,
 	&ecdsa2SigVerTests,