Internal change

PiperOrigin-RevId: 402623632
diff --git a/quic/test_tools/quic_test_client.cc b/quic/test_tools/quic_test_client.cc
index 598e14c..6b1f831 100644
--- a/quic/test_tools/quic_test_client.cc
+++ b/quic/test_tools/quic_test_client.cc
@@ -102,6 +102,7 @@
       return QUIC_FAILURE;
     }
 
+    // Parse the cert into an X509 structure.
     const uint8_t* data;
     data = reinterpret_cast<const uint8_t*>(certs[0].data());
     bssl::UniquePtr<X509> cert(d2i_X509(nullptr, &data, certs[0].size()));
@@ -109,15 +110,28 @@
       return QUIC_FAILURE;
     }
 
-    static const unsigned kMaxCommonNameLength = 256;
-    char buf[kMaxCommonNameLength];
-    X509_NAME* subject_name = X509_get_subject_name(cert.get());
-    if (X509_NAME_get_text_by_NID(subject_name, NID_commonName, buf,
-                                  sizeof(buf)) <= 0) {
+    // Extract the CN field
+    X509_NAME* subject = X509_get_subject_name(cert.get());
+    const int index = X509_NAME_get_index_by_NID(subject, NID_commonName, -1);
+    if (index < 0) {
+      return QUIC_FAILURE;
+    }
+    ASN1_STRING* name_data =
+        X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject, index));
+    if (name_data == nullptr) {
       return QUIC_FAILURE;
     }
 
-    common_name_ = buf;
+    // Convert the CN to UTF8, in case the cert represents it in a different
+    // format.
+    unsigned char* buf = nullptr;
+    const int len = ASN1_STRING_to_UTF8(&buf, name_data);
+    if (len <= 0) {
+      return QUIC_FAILURE;
+    }
+    bssl::UniquePtr<unsigned char> deleter(buf);
+
+    common_name_.assign(reinterpret_cast<const char*>(buf), len);
     cert_sct_ = cert_sct;
     return QUIC_SUCCESS;
   }