Generating a SSH key pair in Elixir

Below is some boiler plate code to create and manage SSH keys inside a Phoenix application. The keys should be in your priv/static directory so that they get copied to your application code. ssh-keygen is the executable that needs to be installed for this process to work.

defmodule MyApplication.KeyManager do
  @moduledoc """
  Provides functions to manage SSH keys used for MyApplication
  """

  @ssh_keygen System.find_executable("ssh-keygen")
  @path Application.app_dir(:my_application, "priv/keys") <> "/"
  @key @path <> "id_rsa"

  @doc """
  Generates a new private/public key set by removing the old key and creating
  a new set. Returns if they keys exist.
  """
  def generate_keys do
    remove_old_keys()
    create_keys()
    keys_exist?()
  end

  @doc """
  Checks to see if the ssh keys exist
  """
  def keys_exist? do
    File.exists?(@key) && File.exists?(@key <> ".pub")
  end

  @doc """
  Returns the content of the SSH public ket
  """
  def public_key do
    key = File.open!(@key <> ".pub",[:read])
          |> IO.read(:line)
          |> String.replace("\n", "")
    File.close(@key <> ".pub")
    key
  end

  defp create_keys do
    args = ["-t", "rsa", "-b", "4096", "-f", @key, "-C", "MyApplication"]
    System.cmd(@ssh_keygen, args)
  end

  defp remove_old_keys do
    @path
    |> File.ls!
    |> Enum.each(&(File.rm! @path <>  &1 ))
  end

end