Handle NULL public key in |EC_KEY_set_public_key|.

Node.js expects to be able to pass NULL to this function to clear the
current public key:
https://github.com/nodejs/node/blob/adbe3b837e8a2285238ec0fcba89c20882eb4cdb/src/node_crypto.cc#L5316

Change-Id: Id4e34d8e8b556c28000e4df12ff6f4432ad9220c
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/35124
Reviewed-by: Adam Langley <agl@google.com>
Commit-Queue: Adam Langley <agl@google.com>
diff --git a/crypto/fipsmodule/ec/ec_key.c b/crypto/fipsmodule/ec/ec_key.c
index 04650ed..3ef17d9 100644
--- a/crypto/fipsmodule/ec/ec_key.c
+++ b/crypto/fipsmodule/ec/ec_key.c
@@ -267,7 +267,7 @@
     return 0;
   }
 
-  if (EC_GROUP_cmp(key->group, pub_key->group, NULL) != 0) {
+  if (pub_key != NULL && EC_GROUP_cmp(key->group, pub_key->group, NULL) != 0) {
     OPENSSL_PUT_ERROR(EC, EC_R_GROUP_MISMATCH);
     return 0;
   }
diff --git a/crypto/fipsmodule/ec/ec_test.cc b/crypto/fipsmodule/ec/ec_test.cc
index 97c6d45..dd4c75a 100644
--- a/crypto/fipsmodule/ec/ec_test.cc
+++ b/crypto/fipsmodule/ec/ec_test.cc
@@ -347,6 +347,20 @@
       EC_KEY_set_public_key(key.get(), EC_GROUP_get0_generator(group.get())));
 }
 
+TEST(ECTest, SetNULLKey) {
+  bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(NID_X9_62_prime256v1));
+  ASSERT_TRUE(key);
+
+  EXPECT_TRUE(EC_KEY_set_public_key(
+      key.get(), EC_GROUP_get0_generator(EC_KEY_get0_group(key.get()))));
+  EXPECT_TRUE(EC_KEY_get0_public_key(key.get()));
+
+  // Setting a NULL public-key should clear the public-key and return zero, in
+  // order to match OpenSSL behaviour exactly.
+  EXPECT_FALSE(EC_KEY_set_public_key(key.get(), nullptr));
+  EXPECT_FALSE(EC_KEY_get0_public_key(key.get()));
+}
+
 TEST(ECTest, GroupMismatch) {
   bssl::UniquePtr<EC_KEY> key(EC_KEY_new_by_curve_name(NID_secp384r1));
   ASSERT_TRUE(key);