Getting different output with openssl in shell and Erlang pem_decode in Elixir

I’m trying to extract an RSA public key from a X509 certificate. I’m running the following commands in Elixir

iex(1)> {:ok, cert} = File.read("/tmp/new.cer")
iex(2)> [certificates] = :public_key.pem_decode cert
iex(3)> cert_entry = :public_key.pem_entry_decode certificates
iex(4)> public_key = cert_entry |> elem(1) |> elem(7) |> elem(2) |> Base.encode64

and I’m getting something like

# "MIIBCgKCAQEAw+SDUgtC2...."

I get very similar but different output when I use openssl in shell

% openssl x509 -pubkey -noout -in /tmp/new.cer

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw+SDUgtC2....
-----END PUBLIC KEY-----

How can I obtain the same public key with Elixir?

Thanks.

Try using the pem encode functions in public key instead and see if it works better.

pem_entry = :public_key.pem_entry_encode(:"RSAPublicKey", cert_entry)
:public_key.pem_encode([pem_entry])

That’s because OpenSSL exports a “SubjectPublicKeyInfo” structure, which includes a field that identifies the algorithm, while your Elixir code takes the raw RSA key.

You can achieve the same output as OpenSSL as follows:

spki = "/tmp/new.cer" |> File.read! |> :public_key.pem_decode |> hd |> :public_key.pem_entry_decode |> elem(1) |> elem(7)
:public_key.pem_entry_encode(:SubjectPublicKeyInfo, spki) |> List.wrap |> :public_key.pem_encode
4 Likes

Thank you so much. I’ve been dealing with this for the last 2 days.

You have been very helpful again :smiley:

Cheers

One tries one’s best…

Shameless plug :wink: : I will be covering :public_key and related topics in my ElixirConf EU workshop in April. More info here and here

1 Like

Yes indeed! Thanks to you now I’m developing my own module for oauth authentication to Azure here. There are still lots to do but at least it’s a start :smiley:

This event seems great especially for the ones who just met with Erlang / Elixir / Phoenix, like me : )

1 Like