+/*
+ * Given a public key/subkey packet return the key length.
+ */
+unsigned int keylength(struct openpgp_packet *keydata)
+{
+ unsigned int length;
+
+ switch (keydata->data[0]) {
+ case 2:
+ case 3:
+ length = (keydata->data[8] << 8) +
+ keydata->data[9];
+ break;
+ case 4:
+ switch (keydata->data[5]) {
+ case OPENPGP_PKALGO_EC:
+ case OPENPGP_PKALGO_ECDSA:
+ /* Elliptic curve key size is based on OID */
+ if ((keydata->data[6] == 8) &&
+ (keydata->data[7] == 0x2A) &&
+ (keydata->data[8] == 0x86) &&
+ (keydata->data[9] == 0x48) &&
+ (keydata->data[10] == 0xCE) &&
+ (keydata->data[11] == 0x3D) &&
+ (keydata->data[12] == 0x03) &&
+ (keydata->data[13] == 0x01) &&
+ (keydata->data[14] == 0x07)) {
+ length = 256;
+ } else if ((keydata->data[6] == 5) &&
+ (keydata->data[7] == 0x2B) &&
+ (keydata->data[8] == 0x81) &&
+ (keydata->data[9] == 0x04) &&
+ (keydata->data[10] == 0x00) &&
+ (keydata->data[11] == 0x22)) {
+ length = 384;
+ } else if ((keydata->data[6] == 5) &&
+ (keydata->data[7] == 0x2B) &&
+ (keydata->data[8] == 0x81) &&
+ (keydata->data[9] == 0x04) &&
+ (keydata->data[10] == 0x00) &&
+ (keydata->data[11] == 0x23)) {
+ length = 521;
+ } else {
+ logthing(LOGTHING_ERROR,
+ "Unknown elliptic curve size");
+ length = 0;
+ }
+ break;
+ default:
+ length = (keydata->data[6] << 8) +
+ keydata->data[7];
+ }
+ break;
+ default:
+ logthing(LOGTHING_ERROR, "Unknown key version: %d",
+ keydata->data[0]);
+ length = 0;
+ }
+
+ return length;
+}
+