clacks/lib/clacks/keys.ex

36 lines
1.0 KiB
Elixir

defmodule Clacks.Keys do
def generate_rsa_pem() do
key = :public_key.generate_key({:rsa, 2048, 65_537})
entry = :public_key.pem_entry_encode(:RSAPrivateKey, key)
pem = :public_key.pem_encode([entry]) |> String.trim_trailing()
{:ok, pem}
end
def keys_from_private_key_pem(pem) do
with [private_key_code] <- :public_key.pem_decode(pem),
private_key <- :public_key.pem_entry_decode(private_key_code),
{:RSAPrivateKey, _, modulus, exponent, _, _, _, _, _, _, _} <- private_key do
{:ok, private_key, {:RSAPublicKey, modulus, exponent}}
else
error ->
{:error, error}
end
end
def key_from_pem(pem) do
with [entry] <- :public_key.pem_decode(pem),
key <- :public_key.pem_entry_decode(entry) do
{:ok, key}
else
error ->
{:error, error}
end
end
def public_key_pem({:RSAPublicKey, _, _} = key) do
entry = :public_key.pem_entry_encode(:SubjectPublicKeyInfo, key)
pem = :public_key.pem_encode([entry])
{:ok, pem}
end
end