I made the following steps before getting struck
1) I got the certificate of a server using
s_client -connect hostname.org:443 -showcerts
The certificates looks good
-----BEGIN CERTIFICATE-----
MIIICTCCBvGgAwIBAgIQA8mdxgOCgSdtPdwJY/c3FzANBgkqhkiG9w0BAQsFADBk
MQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9vcmQtSG9sbGFuZDESMBAGA1UEBxMJ
and so on
-----END CERTIFICATE-----
2) I saved it as myCert.pem file.(I am not sure if i should have saved it as .cer file )
3) I extracted the public key in PEM format, form the above saved certificate file, using
openssl x509 -pubkey -noout -in myCert.pem > pubkey.pem
The PEM format public key looks good too
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAwFQpwmpIDxhGeuKGxn1a
oWOytrvD5m6dQLv9EUEWkCZPNr48su3G2vGxWtUNNU5kA8lYxGo4kqo1R2J8nM6I
CXANY3tO6/j82AueiK93qTTFdJVDTjtYUd8CI9frzxQ+XyJvBeIj3l0tNLsND4HD
hSV+dteikKGiAwXOR0SA4pUyMCNuO1xqyK0YI2eZvQCOLpXd1DMyV7bmPUJINvwV
nT3iweeaBiX6HHXbSb/zHvAQZzOti939D/NTbLbJwSBYxnUR9uBR/JtcfZaoSjEa
1QHCIPgLJ2oQT/udCdb66IHEZfrjNHArQC3prXvuV25S043VlqssdVQnSz0bV+Tk
+CK3D2Ht42QKewVx6/uFzuf0btkMvhxvY6zLmM4UhRDFhMKbewsI9tAV7tKBdwtc
qYSuFvRLFdJWx1WsUsHhMWE34AVYUu/ocAOsiTBtsLfLR0OPNB05RZI7x6XJL3XV
PCnkIw4nfHf8fqyXfBkqkSBlNVL26t+bVW9E3ksl9eqh4VxZl6XGLOy0jBc8/96E
iRJaydsutraiqevdAwvRkebj2SR0pXLwigZFXm1hPSrtI7cuytsfqNE4DNwD+yQw
d/iMyiPgxG0Mv9fmmpx8VHNNkchhrtDRIvZx6C11eaZ0Ng7Y4JCFtnAfL3XbBCXB
Y8y052YLhGd+lE4/J76bAokCAwEAAQ==
-----END PUBLIC KEY-----
Now I am trying to decode this PEM format public key to der format. How can i do it?
The PEM encoded file is the header, the footer, and base64-encoded contents (which, for certs and keys and stuff, is BER/DER encoded data).
When OpenSSL writes data it uses the constraints from DER (as far as I've seen), so for OpenSSL-written data you just need to base64-decode the contents. openssl base64 -d
will do that (ignoring the PEM header/footer)
openssl base64 -d -in pubkey.key -out pubkey.der
If you were worried that the PEM contents were legal BER but not legal DER (for example, that it used indefinite-length constructed values), you could ask OpenSSL to read and write it.
openssl rsa -pubin -in pubkey.key -outform der -out pubkey.der
or, programmatically
FILE* fp = fopen("pubkey.key", "r");
EVP_PKEY* pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL);
fclose(fp);
fp = fopen("pubkey.der", "wb");
i2d_PUBKEY_fp(fp, pkey);
fclose(fp);
EVP_PKEY_free(pkey);
Optionally with error checking.