Blog | G5 Cyber Security

Find Public Key Offset in DER Certificate

TL;DR

Use OpenSSL to decode the DER certificate chain and identify the offset of the public key within each certificate. This guide shows how.

Finding the Public Key Offset

  1. Understand DER Encoding: DER (Distinguished Encoding Rules) is a standard way to represent data structures like certificates. Certificates are often stored in binary DER format.
  2. Extract the Certificate Chain: If your certificate chain is within a file (e.g., chain.pem), you’ll need to extract each individual certificate.
    • If it’s a PEM file, convert it to DER format using OpenSSL:
      openssl x509 -in chain.pem -outform der -out chain.der
  3. Decode the Certificate: Use OpenSSL to decode the DER encoded certificate.
    openssl asn1parse -i chain.der | less

    This command will output a lot of information about the ASN.1 structure of the certificate. Use the less command to scroll through it.

  4. Identify the Public Key Sequence: Look for lines in the OpenSSL output that indicate the public key sequence. You’ll be looking for something like:
    • 0: SEQUENCE (2 octets) followed by further nested sequences.
    • Within those sequences, find 1: SEQUENCE (variable octets) which often contains the algorithm and parameters.
    • Then look for 2: BIT STRING (variable octets) – this is where the actual public key data resides.
  5. Calculate the Offset: The offset of the public key is determined by adding up the lengths of all preceding sections in the ASN.1 structure.
    • Start at byte 0 (the beginning of the certificate).
    • Add the length of the first SEQUENCE.
    • Continue adding the lengths of each subsequent sequence until you reach the BIT STRING containing the public key.

    For example, if you see:

    • 0: SEQUENCE (2 octets)
    • 1: INTEGER (3 octets)
    • 4: SEQUENCE (5 octets)
    • 9: BIT STRING (variable octets)

    The public key offset would be 9 bytes.

  6. Automating with a Script (Advanced): For multiple certificates, you can write a script to parse the OpenSSL output and automatically calculate the offsets. This is beyond the scope of this basic guide but involves parsing text using tools like awk or Python.
Exit mobile version