From e47a790e13da04d60a9019b485d298657e3c4c30 Mon Sep 17 00:00:00 2001 From: Wes Oldenbeuving Date: Mon, 6 Nov 2017 16:36:36 +0100 Subject: [PATCH] ExPublicKey.generate_key compatibility with OTP 20.0 (#15) * generate_key compatibility with OTP 20.0 The old implementation was tested against OTP 20.1, which had slightly different internal library versions than OTP 20.0, which introduced the generate_key feature. I've lowered the version requirement for Erlang public_key from 1.5 to 1.4.1 and switched to Version.match?() to do proper version checking. The internal data format for RSAPrivateKey was not consistently generated in OTP 20.0, generating version=0, but when parsing the PEM version it returned version=:"two-prime". Turns out this is an internal code vs named code thing, and they are the same. * Version.match? only matches SemVer. List compare always works --- lib/ex_public_key.ex | 12 +++++++----- lib/ex_public_key/ex_rsa_private_key.ex | 8 +++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/ex_public_key.ex b/lib/ex_public_key.ex index 1679b4a..ab59550 100644 --- a/lib/ex_public_key.ex +++ b/lib/ex_public_key.ex @@ -313,16 +313,18 @@ defmodule ExPublicKey do Base.encode64(payload_bytes) end + # Erlang public_key v1.4.1 corresponds to Erlang/OTP 20.0 defp otp_has_rsa_gen_support do - case (to_string(Application.spec(:public_key, :vsn)) |> Float.parse) do - :error -> false - {version, _remainder} -> version >= 1.5 - end + integer_list_version = Application.spec(:public_key, :vsn) + |> Kernel.to_string + |> String.split(".") + |> Enum.map(&Integer.parse/1) + + integer_list_version >= [1, 4, 1] end defp generate_rsa_openssl_fallback(bits) do {pem_entry, _exit_code} = System.cmd("openssl", ["genrsa", to_string(bits)]) loads(pem_entry) end - end diff --git a/lib/ex_public_key/ex_rsa_private_key.ex b/lib/ex_public_key/ex_rsa_private_key.ex index 2627de8..3cbaba3 100644 --- a/lib/ex_public_key/ex_rsa_private_key.ex +++ b/lib/ex_public_key/ex_rsa_private_key.ex @@ -28,7 +28,7 @@ defmodule ExPublicKey.RSAPrivateKey do def from_sequence(rsa_key_seq) do %ExPublicKey.RSAPrivateKey{} |> struct( - version: elem(rsa_key_seq, 1), + version: maybe_convert_version_to_atom(elem(rsa_key_seq, 1)), public_modulus: elem(rsa_key_seq, 2), public_exponent: elem(rsa_key_seq, 3), private_exponent: elem(rsa_key_seq, 4), @@ -62,4 +62,10 @@ defmodule ExPublicKey.RSAPrivateKey do end end + # Generating a RSA key on OTP 20.0 results in a RSAPrivateKey with version 0, which is the internal number that matches to :"two-prime". + # Parsing this structure to PEM and then converting it back will yield a version not of 0, but of :"two-prime". + # This conversion ensures it is always the symbol. + defp maybe_convert_version_to_atom(0), do: :"two-prime" + defp maybe_convert_version_to_atom(version), do: version + end