Created
April 24, 2018 18:55
-
-
Save maartenvanvliet/0a36355b71ad6eca9f61cf8a75d24991 to your computer and use it in GitHub Desktop.
Elixir Cloudfront signed urls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule CloudfrontSigner do | |
def signed_url(cloudfront_key_pem, key_pair, url, expiry_time) do | |
decoded_key = cloudfront_key_pem |> decode_key | |
expiry_time = :os.system_time(:second) + expiry_time | |
policy = policy(url, expiry_time) | |
signature = | |
:public_key.sign(policy, :sha, decoded_key) | |
|> Base.encode64() | |
|> String.replace("+", "-") | |
|> String.replace("=", "_") | |
|> String.replace("/", "~") | |
"#{url}?Expires=#{expiry_time}&Signature=#{signature}&Key-Pair-Id=#{key_pair}" | |
end | |
defp decode_key(key) do | |
key |> :public_key.pem_decode() |> hd |> :public_key.pem_entry_decode() | |
end | |
defp policy(url, expiry) do | |
%{ | |
Statement: [ | |
%{ | |
Resource: url, | |
Condition: %{ | |
DateLessThan: %{ | |
"AWS:EpochTime": expiry | |
} | |
} | |
} | |
] | |
} | |
|> Poison.encode!() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment