Skip to content

Instantly share code, notes, and snippets.

@chalmagean chalmagean/enc.ex
Last active Nov 2, 2016

Embed
What would you like to do?
RC4 encryption/decryption in Elixir/Erlang
# Install https://github.com/rubencaro/cipher first
require Cipher.Helpers, as: H
defmodule Enc do
@random_key H.env(:keyphrase) |> Cipher.Digest.generate_key
def stream_encrypt(xml) do
{_, result} =
:crypto.stream_init(:rc4, @random_key)
|> :crypto.stream_encrypt(xml)
Base.encode64(result)
end
def stream_decrypt(encoded_data, encoded_env_key) do
{:ok, data} = Base.decode64(encoded_data)
{:ok, env_key} = Base.decode64(encoded_env_key)
random_key = :public_key.decrypt_private(env_key, private_key)
{_, result} =
:crypto.stream_init(:rc4, random_key)
|> :crypto.stream_decrypt(data)
result
end
def env_key do
:public_key.encrypt_public(@random_key, public_key)
|> Base.encode64
end
# Check this comment to see what's going on
# https://github.com/potatosalad/erlang-jose/issues/13#issuecomment-160718744
defp private_key do
{:ok, pem_bin} = File.read "prv.key"
pem_key = decode_key(pem_bin)
private_key = elem(pem_key, 3)
:public_key.der_decode(:RSAPrivateKey, private_key)
end
defp public_key do
{:ok, pem_bin} = File.read "pub.pem"
pem_bin |> decode_key
end
defp decode_key(key) do
key
|> :public_key.pem_decode
|> hd
|> :public_key.pem_entry_decode
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.