logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

keys.ex (1434B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Keys do
  5. # Native generation of RSA keys is only available since OTP 20+ and in default build conditions
  6. # We try at compile time to generate natively an RSA key otherwise we fallback on the old way.
  7. try do
  8. _ = :public_key.generate_key({:rsa, 2048, 65_537})
  9. def generate_rsa_pem do
  10. key = :public_key.generate_key({:rsa, 2048, 65_537})
  11. entry = :public_key.pem_entry_encode(:RSAPrivateKey, key)
  12. pem = :public_key.pem_encode([entry]) |> String.trim_trailing()
  13. {:ok, pem}
  14. end
  15. rescue
  16. _ ->
  17. def generate_rsa_pem do
  18. port = Port.open({:spawn, "openssl genrsa"}, [:binary])
  19. {:ok, pem} =
  20. receive do
  21. {^port, {:data, pem}} -> {:ok, pem}
  22. end
  23. Port.close(port)
  24. if Regex.match?(~r/RSA PRIVATE KEY/, pem) do
  25. {:ok, pem}
  26. else
  27. :error
  28. end
  29. end
  30. end
  31. def keys_from_pem(pem) do
  32. with [private_key_code] <- :public_key.pem_decode(pem),
  33. private_key <- :public_key.pem_entry_decode(private_key_code),
  34. {:RSAPrivateKey, _, modulus, exponent, _, _, _, _, _, _, _} <- private_key do
  35. {:ok, private_key, {:RSAPublicKey, modulus, exponent}}
  36. else
  37. error -> {:error, error}
  38. end
  39. end
  40. end