When viewing an SSL certificate using the `openssl`

cli tool the output contains a line in the public key information that shows the key length: `Public-Key: (2048 bit)`

. Is there a way to get the bit length value from an `OTPCertificate`

tuple? The great X509 library returns a public key tuple, but I can’t seem to figure out how to derive the bit length. Does anyone know how to derive this value?

# Finding the Public Key "BIT STRING" from an OTPCertificate tuple

Presumably we’re talking about an RSA key here, in which case the key length is determined by the length of the modulus. So given a public key `k`

you can calculate the key length using `8 * byte_size(:binary.encode_unsigned(elem(k, 1)))`

.

Instead of using `elem/2`

you might want to use the record definition from `:public_key`

, to avoid making assumptions about the internal representation of the key, e.g.:

```
require Record
Record.defrecordp(
:rsa_public_key,
:RSAPublicKey,
Record.extract(:RSAPublicKey, from_lib: "public_key/include/OTP-PUB-KEY.hrl")
)
modulus = rsa_public_key(k, :modulus)
```

3 Likes