Formatting a string to PEM with headers and line breaks

Hi,

I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I need to convert it to

-----BEGIN CERTIFICATE-----
MIIDBTCCAe2......
....
-----END CERTIFICATE-----

Is there any library function that would do that for me?

Would appreciate if you could help.

Thanks in advance

1 Like

Maybe string interpolation can do the trick.

cert="MIIDBTCCAe2......"
"-----BEGIN CERTIFICATE-----\n#{cert}\n-----END CERTIFICATE-----\n"

Additional: You can concat 2 strings with

“string1” <> “string2”

Thank you very much for your reply.

With that approach, I’d also need to add the line breaks every 64th characters in the certificate and honestly, I’m a bit confused on the string iterations for the beginning.

You could try Enum.chunk and Enum.join. Chunk by 64 and change the \n to the line break you wish to use.

iex(1)> s = ['a','b','c','d']
['a', 'b', 'c', 'd']
iex(3)> s |> Enum.chunk(2)
[['a', 'b'], ['c', 'd']]
iex(4)> s |> Enum.chunk(2) |> Enum.join("\n")
"ab\ncd"

Cool. Thank you very much. I’ll try it and see how it goes.

Somehow |> Enum.chunk(64) trimmed some characters at the end of the string and I used Enum.chunk_every() to get the string properly sliced. But apparently no need to add line breaks every 64 characters, adding only header and footer is enough for :public_key.pem_decodeto read the certificate

Thank you.

If the input string is a base64 encoded certificate, there is no need to add the PEM headers just so the PEM parser can strip them off again. Just use Base.decode64!/1 to get the binary (DER) certificate.

In other words:

[{:Certificate, der, :not_encrypted}] = :public_key.pem_decode("-----BEGIN CERTIFICATE-----\n#{cert}\n-----END CERTIFICATE-----\n")

and

der = Base.decode64!(cert)

are equivalent.

1 Like

You’re right, this is a much better approach. Thanks.