Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace Poison with Jason #32

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"],
line_length: 120
ybod marked this conversation as resolved.
Show resolved Hide resolved
]
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ rsa_pub_key = ExPublicKey.load!("/path/to/public_key.pem")
msg = %{"name_first"=>"Chuck","name_last"=>"Norris"}

# serialize the JSON
msg_serialized = Poison.encode!(msg)
msg_serialized = Jason.encode!(msg)

# generate time-stamp
ts = DateTime.utc_now |> DateTime.to_unix
Expand Down Expand Up @@ -73,7 +73,7 @@ recv_msg_serialized = Enum.fetch!(parts, 1)
assert(sig_valid)

# un-serialize the JSON
recv_msg_unserialized = Poison.Parser.parse!(recv_msg_serialized)
recv_msg_unserialized = Jason.decode!(recv_msg_serialized)
assert(msg == recv_msg_unserialized)
```
*Note: this example is similar to the test "sign and verify a JSON payload" in `test/ex_public_key_test.exs`.*
Expand Down
8 changes: 3 additions & 5 deletions lib/ex_crypto/token.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ defmodule ExCrypto.Token do
is available after the token is verified like this:

iex> payload = %{"user_id" => 12345}
iex> encoded_payload = Poison.encode!(payload)
iex> encoded_payload = Jason.encode!(payload)
iex> {:ok, secret} = ExCrypto.generate_aes_key(:aes_256, :bytes)
iex> {:ok, token} = ExCrypto.Token.create(encoded_payload, secret)
iex> ttl = (15 * 60) # 15 minute TTL (in seconds)
iex> {:ok, verified_payload} = ExCrypto.Token.verify(token, secret, ttl)
iex> decoded_verified_payload = Poison.decode!(verified_payload)
iex> decoded_verified_payload = Jason.decode!(verified_payload)
iex> assert(decoded_verified_payload == payload)
iex> Map.get(decoded_verified_payload, "user_id")
12345
Expand Down Expand Up @@ -218,9 +218,7 @@ defmodule ExCrypto.Token do
end
end

defp decode_token_0(
<<mac::bits-size(256), iv::bits-size(128), sig_ts::integer-size(64), payload::binary>>
) do
defp decode_token_0(<<mac::bits-size(256), iv::bits-size(128), sig_ts::integer-size(64), payload::binary>>) do
{:ok, [iv, payload, sig_ts, mac]}
end

Expand Down
9 changes: 2 additions & 7 deletions lib/ex_public_key.ex
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,7 @@ defmodule ExPublicKey do
{:ok, ExPublicKey.RSAPublicKey.from_sequence(key_tup)}

x ->
{:error,
"invalid argument, expected one of[ExPublicKey.RSAPublicKey, ExPublicKey.RSAPrivateKey], found: #{
x
}"}
{:error, "invalid argument, expected one of[ExPublicKey.RSAPublicKey, ExPublicKey.RSAPrivateKey], found: #{x}"}
end
end

Expand Down Expand Up @@ -300,9 +297,7 @@ defmodule ExPublicKey do
"""
def public_key_from_private_key(private_key = %ExPublicKey.RSAPrivateKey{}) do
{:ok,
ExPublicKey.RSAPublicKey.from_sequence(
{:RSAPublicKey, private_key.public_modulus, private_key.public_exponent}
)}
ExPublicKey.RSAPublicKey.from_sequence({:RSAPublicKey, private_key.public_modulus, private_key.public_exponent})}
end

@doc """
Expand Down
10 changes: 5 additions & 5 deletions lib/ex_public_key/ex_rsa_private_key.ex
Original file line number Diff line number Diff line change
Expand Up @@ -68,21 +68,21 @@ defmodule ExPublicKey.RSAPrivateKey do
{:ok, rsa_private_key}
end

def encode_der(rsa_private_key=%__MODULE__{}) do
def encode_der(rsa_private_key = %__MODULE__{}) do
with {:ok, key_sequence} <- as_sequence(rsa_private_key) do
der_encoded = :public_key.der_encode(:RSAPrivateKey, key_sequence)
{:ok, der_encoded}
end
end

def get_public(rsa_private_key=%__MODULE__{}) do
def get_public(rsa_private_key = %__MODULE__{}) do
%ExPublicKey.RSAPublicKey{
public_modulus: rsa_private_key.public_modulus,
public_exponent: rsa_private_key.public_exponent,
public_exponent: rsa_private_key.public_exponent
}
end

def get_fingerprint(rsa_private_key=%__MODULE__{}, opts \\ []) do
def get_fingerprint(rsa_private_key = %__MODULE__{}, opts \\ []) do
get_public(rsa_private_key)
|> ExPublicKey.RSAPublicKey.get_fingerprint(opts)
end
Expand All @@ -108,7 +108,7 @@ defmodule ExPublicKey.RSAPrivateKey do
fp_sha256_parts_doc =
ExPublicKey.RSAPrivateKey.get_fingerprint(data, fp_opts)
|> String.split(":")
|> fold_doc(fn(doc, acc) -> glue(doc, ":", acc) end)
|> fold_doc(fn doc, acc -> glue(doc, ":", acc) end)

fp_sha256_doc =
glue("fingerprint_sha256=", "", fp_sha256_parts_doc)
Expand Down
26 changes: 16 additions & 10 deletions lib/ex_public_key/ex_rsa_public_key.ex
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ defmodule ExPublicKey.RSAPublicKey do
end
end

def get_fingerprint(rsa_public_key=%__MODULE__{}, opts \\ []) do
def get_fingerprint(rsa_public_key = %__MODULE__{}, opts \\ []) do
# parse opts
digest_type = Keyword.get(opts, :digest_type, :sha256)
colons = Keyword.get(opts, :colons, false)
Expand All @@ -41,27 +41,30 @@ defmodule ExPublicKey.RSAPublicKey do
with {:ok, der_encoded} <- encode_der(rsa_public_key),
digest = :crypto.hash(digest_type, der_encoded),
hex_fp = Base.encode16(digest, case: :lower),
do: add_fingerprint_colons(hex_fp, colons)
do: add_fingerprint_colons(hex_fp, colons)
end

def encode_der(rsa_public_key=%__MODULE__{}) do
def encode_der(rsa_public_key = %__MODULE__{}) do
# hack to encode same defaults as openssl in SubjectPublicKeyInfo format
with {:ok, key_sequence} <- as_sequence(rsa_public_key) do
pem_entry = :public_key.pem_entry_encode(:SubjectPublicKeyInfo, key_sequence)

der_encoded =
:public_key.pem_encode([pem_entry])
|> String.trim()
|> String.split("\n")
|> Enum.filter(fn(line) -> !String.contains?(line, "-----") end)
|> Enum.filter(fn line -> !String.contains?(line, "-----") end)
|> Enum.join("")
|> Base.decode64!()

{:ok, der_encoded}
end
end

def decode_der(der_encoded, opts \\ []) do
# parse opts
format = Keyword.get(opts, :format, :SubjectPublicKeyInfo) # also supports :RSAPublicKey
# also supports :RSAPublicKey
format = Keyword.get(opts, :format, :SubjectPublicKeyInfo)

# decode and parse
:public_key.der_decode(format, der_encoded)
Expand Down Expand Up @@ -89,7 +92,7 @@ defmodule ExPublicKey.RSAPublicKey do
fp_sha256_parts_doc =
ExPublicKey.RSAPublicKey.get_fingerprint(data, fp_opts)
|> String.split(":")
|> fold_doc(fn(doc, acc) -> glue(doc, ":", acc) end)
|> fold_doc(fn doc, acc -> glue(doc, ":", acc) end)

fp_sha256_doc =
glue("fingerprint_sha256=", "", fp_sha256_parts_doc)
Expand All @@ -108,29 +111,32 @@ defmodule ExPublicKey.RSAPublicKey do
case String.valid?(data) do
true ->
String.splitter(data, "", trim: true)
|> Enum.chunk(2)
|> Enum.map(fn(chunk_list) ->
|> Enum.chunk_every(2)
|> Enum.map(fn chunk_list ->
Enum.join(chunk_list, "")
end)
|> Enum.join(":")

false ->
data
end
end

defp add_fingerprint_colons(data, _false) do
data
end

def from_der_encoded_0({:SubjectPublicKeyInfo, _, der_key}) do
with {:RSAPublicKey, pub_mod, pub_exp} <- :public_key.der_decode(:RSAPublicKey, der_key),
do: from_der_encoded_0({:RSAPublicKey, pub_mod, pub_exp})
do: from_der_encoded_0({:RSAPublicKey, pub_mod, pub_exp})
end

def from_der_encoded_0({:RSAPublicKey, pub_mod, pub_exp}) do
rsa_pub_key = from_sequence({:RSAPublicKey, pub_mod, pub_exp})
{:ok, rsa_pub_key}
end

def from_der_encoded_0(_other) do
{:error, :invalid_public_key}
end

end
4 changes: 2 additions & 2 deletions mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ defmodule ExCrypto.Mixfile do

defp deps do
[
{:poison, ">= 2.0.0"},
{:jason, "~> 1.1"},
{:dialyxir, "~> 0.5", only: [:dev], runtime: false},
{:ex_doc, "~> 0.15", only: :dev}
{:ex_doc, "~> 0.20.1", only: :dev}
]
end

Expand Down
13 changes: 9 additions & 4 deletions mix.lock
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
%{"dialyxir": {:hex, :dialyxir, "0.5.1", "b331b091720fd93e878137add264bac4f644e1ddae07a70bf7062c7862c4b952", [:mix], [], "hexpm"},
"earmark": {:hex, :earmark, "1.2.3", "206eb2e2ac1a794aa5256f3982de7a76bf4579ff91cb28d0e17ea2c9491e46a4", [:mix], [], "hexpm"},
"ex_doc": {:hex, :ex_doc, "0.17.1", "39f777415e769992e6732d9589dc5846ea587f01412241f4a774664c746affbb", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, repo: "hexpm", optional: false]}], "hexpm"},
"poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [:mix], [], "hexpm"}}
%{
"dialyxir": {:hex, :dialyxir, "0.5.1", "b331b091720fd93e878137add264bac4f644e1ddae07a70bf7062c7862c4b952", [:mix], [], "hexpm"},
"earmark": {:hex, :earmark, "1.3.2", "b840562ea3d67795ffbb5bd88940b1bed0ed9fa32834915125ea7d02e35888a5", [:mix], [], "hexpm"},
"ex_doc": {:hex, :ex_doc, "0.20.1", "88eaa16e67c505664fd6a66f42ddb962d424ad68df586b214b71443c69887123", [:mix], [{:earmark, "~> 1.3", [hex: :earmark, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.10", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm"},
"jason": {:hex, :jason, "1.1.2", "b03dedea67a99223a2eaf9f1264ce37154564de899fd3d8b9a21b1a6fd64afe7", [:mix], [{:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm"},
"makeup": {:hex, :makeup, "0.8.0", "9cf32aea71c7fe0a4b2e9246c2c4978f9070257e5c9ce6d4a28ec450a839b55f", [:mix], [{:nimble_parsec, "~> 0.5.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm"},
"makeup_elixir": {:hex, :makeup_elixir, "0.13.0", "be7a477997dcac2e48a9d695ec730b2d22418292675c75aa2d34ba0909dcdeda", [:mix], [{:makeup, "~> 0.8", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm"},
"nimble_parsec": {:hex, :nimble_parsec, "0.5.0", "90e2eca3d0266e5c53f8fbe0079694740b9c91b6747f2b7e3c5d21966bba8300", [:mix], [], "hexpm"},
}
3 changes: 1 addition & 2 deletions test/ex_crypto_hmac_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ defmodule ExCryptoHMACTest do
assert(invalid_mac !== nil)
assert(is_binary(invalid_mac))

{:ok, mac_is_valid} =
ExCrypto.HMAC.verify_hmac(context[:data], context[:aes_128_key], invalid_mac)
{:ok, mac_is_valid} = ExCrypto.HMAC.verify_hmac(context[:data], context[:aes_128_key], invalid_mac)

assert(mac_is_valid === false)
end
Expand Down
3 changes: 1 addition & 2 deletions test/ex_crypto_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,7 @@ defmodule ExCryptoTest do
{:ok, bad_iv} = ExCrypto.rand_bytes(17)
clear_text = "secret_message"
# encrypt
{:error, error_message} =
ExCrypto.encrypt(aes_256_key, clear_text, %{initialization_vector: bad_iv})
{:error, error_message} = ExCrypto.encrypt(aes_256_key, clear_text, %{initialization_vector: bad_iv})

assert(is_binary(error_message))
end
Expand Down
Loading