vegabook

vegabook

How to encrypt a string using a pem-encoded public key (obtained from Python)

I’m communicating between Python and Elixir. Python reads my (Linux-standard, ssh-keygen with no options) ~/.ssh/id_rsa.pub, pem-encodes it, and sends it to Elixir via encrypted websocket. This is a (fake) version of it

pry(7)> key
"-----BEGIN PUBLIC KEY-----\nMIIBojANBgkqhkiG9w0BEH6ycVAgMBAAE=\n-----END PUBLIC KEY-----\n"

(of course it’s much longer)

Now how do I use this plaintext pem public key, to encrypt a string say, “hello python”, so that I can send the encrypted version back via the same websocket, to be decoded python side using the local corresponding private key ~/.ssh/id_rsa.

Basically I’m looking for some way to get an industry standard cross-language public-private key interaction between Elixir and Python. There’s a lot on the web about pem vs der but I’m a bit confused by it.

(for guide I’m basically rolling my own python ↔ elixir authentication mechanism. If something that does this already exists, then happy to hear about it)

Marked As Solved

danj

danj

This works for strings up to about the size of the key, then doesn’t. You need a box. The most ubiquitous box JWE (encryption) which is supported by jose. JWK does your PEM decoding and key management. It’s not easy to figure all out, but nothing with crypto is.

Also Liked

ErikNaslund

ErikNaslund

I completely get what you mean @vegabook. I too struggled longer than I’d like to admit before I got my assymetric RSA encryption working. Please see below for a module I wrote, that hopefully explains things well enough.

defmodule Ls.Crypto.Assymetric do
  @moduledoc """
  Functionality releated to assymetric encryption, e.g. public key encryption.

  Create the keys used here in the following way:

  # Public key.
  openssl genrsa -out private.pem 2048

  # Private key.
  openssl rsa -in private.pem -pubout -out public.pem
  """
  @encrypt_decrypt_opts [rsa_padding: :rsa_pkcs1_oaep_padding]

  def encrypt_rsa(text, key_path) do
    key = load_key(key_path, :RSAPublicKey)
    :public_key.encrypt_public(text, key, @encrypt_decrypt_opts)
  end

  def decrypt_rsa(cipher_text, key_path) do
    key = load_key(key_path, :RSAPrivateKey)
    :public_key.decrypt_private(cipher_text, key, @encrypt_decrypt_opts)
  end

  defp load_key(key_path, expected_key_type) do
    {:ok, raw_key} = File.read(key_path)

    [enc_key] = :public_key.pem_decode(raw_key)
    pem_entry = :public_key.pem_entry_decode(enc_key)

    # Check that we loaded a key that's of the expected type (private vs public).
    # It's an easy mistake to load the wrong key, so this check can
    # save a lot of debugging time.
    if elem(pem_entry, 0) != expected_key_type do
        raise("Expected a key of type #{expected_key_type}, got #{elem(pem_entry, 0)}")
    end      

    pem_entry
  end
end

Caveats

  1. A .pem file is a container format, so it can contain many different things. This is why we need to do the :public_key.pem_decode/1 and :public_key.pem_entry_decode/1. My code assumes the PEM file contains just a single key.

  2. It works on my machine and for my particular use case. It’s definitely not the most general, universally applicable way of doing things :slight_smile: .

vegabook

vegabook

It’s a thing of beauty!

danj

danj

I had the exact “fun” you’re talking about. Crypto is really interesting, deep and complex. Learning more about how any part of it works is well worth the effort (or rabbit hole). Good luck!

Where Next?

Popular in Questions Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

We're in Beta

About us Mission Statement