Last active
July 30, 2021 18:42
-
-
Save chalmagean/417fad6215d185ba92752415d50c2d76 to your computer and use it in GitHub Desktop.
RC4 encryption/decryption in Elixir/Erlang
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
# 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