Skip to content

Commit

Permalink
ExPublicKey.generate_key compatibility with OTP 20.0 (#15)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Narnach authored and ntrepid8 committed Nov 6, 2017
1 parent bd38e75 commit e47a790
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
12 changes: 7 additions & 5 deletions lib/ex_public_key.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
8 changes: 7 additions & 1 deletion lib/ex_public_key/ex_rsa_private_key.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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

0 comments on commit e47a790

Please sign in to comment.