Change ECDSA_METHOD's size() to group_order_size()

The |size| method was documented to return the same as |ECDSA_size| -
the max size of an ECDSA signature. However, this involves some ASN.1
calculations which is best done once. What custom implementations want
to give is the size of the group order on which the ASN.1 computations
are based.

This change switches the |size| method to allow that.

Change-Id: I95b6e0c2b52bfcd0d74850c2c4e9bc01269255e2
Reviewed-on: https://boringssl-review.googlesource.com/1200
Reviewed-by: David Benjamin <davidben@chromium.org>
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/ecdsa/ecdsa_asn1.c b/crypto/ecdsa/ecdsa_asn1.c
index 9d68361..e54dcca 100644
--- a/crypto/ecdsa/ecdsa_asn1.c
+++ b/crypto/ecdsa/ecdsa_asn1.c
@@ -69,35 +69,39 @@
 IMPLEMENT_ASN1_FUNCTIONS_const(ECDSA_SIG);
 
 size_t ECDSA_size(const EC_KEY *key) {
-  size_t ret, i;
+  size_t ret, i, group_order_size;
   ASN1_INTEGER bs;
   BIGNUM *order = NULL;
   unsigned char buf[4];
   const EC_GROUP *group;
 
-  if (key->ecdsa_meth && key->ecdsa_meth->size) {
-    return key->ecdsa_meth->size(key);
+  if (key->ecdsa_meth && key->ecdsa_meth->group_order_size) {
+    group_order_size = key->ecdsa_meth->group_order_size(key);
+  } else {
+    size_t num_bits;
+
+    if (key == NULL) {
+      return 0;
+    }
+    group = EC_KEY_get0_group(key);
+    if (group == NULL) {
+      return 0;
+    }
+
+    order = BN_new();
+    if (order == NULL) {
+      return 0;
+    }
+    if (!EC_GROUP_get_order(group, order, NULL)) {
+      BN_clear_free(order);
+      return 0;
+    }
+
+    num_bits = BN_num_bits(order);
+    group_order_size = (num_bits + 7) / 8;
   }
 
-  if (key == NULL) {
-    return 0;
-  }
-  group = EC_KEY_get0_group(key);
-  if (group == NULL) {
-    return 0;
-  }
-
-  order = BN_new();
-  if (order == NULL) {
-    return 0;
-  }
-  if (!EC_GROUP_get_order(group, order, NULL)) {
-    BN_clear_free(order);
-    return 0;
-  }
-
-  i = BN_num_bits(order);
-  bs.length = (i + 7) / 8;
+  bs.length = group_order_size;
   bs.data = buf;
   bs.type = V_ASN1_INTEGER;
   /* If the top bit is set the ASN.1 encoding is 1 larger. */
diff --git a/include/openssl/ec_key.h b/include/openssl/ec_key.h
index ce4846b..ac58a8f 100644
--- a/include/openssl/ec_key.h
+++ b/include/openssl/ec_key.h
@@ -239,9 +239,10 @@
   int (*init)(EC_KEY *key);
   int (*finish)(EC_KEY *key);
 
-  /* size returns the maximum size of the DER encoded, ECDSA signature
-   * resulting from |key|. */
-  size_t (*size)(const EC_KEY *key);
+  /* group_order_size returns the number of bytes needed to represent the order
+   * of the group. This is used to calculate the maximum size of an ECDSA
+   * signature in |ECDSA_size|. */
+  size_t (*group_order_size)(const EC_KEY *key);
 
   /* sign matches the arguments and behaviour of |ECDSA_sign|. */
   int (*sign)(const uint8_t *digest, size_t digest_len, uint8_t *sig,