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!

ErikNaslund

ErikNaslund

That sounds like a great idea @vegabook! Using something standardized / well thought out that someone else spent a lot of time thinking about is almost always the way to go. It’s way too easy to miss out on some subtleties otherwise, especially when it comes to security and cryptography.

Like @danj wisely pointed out - using asymmetric encryption limits your data to approx. the size of the key. If you want to send more data you need to mix in symmetric encryption (e.g. AES) as well and encrypt the AES key using RSA. Suddenly you need to make sure you don’t make yourself vulnerable to silly things like the two-time-pad attack etc etc. TL;DR - it gets hairy very quickly! I don’t even know this stuff particularly well, just well enough to be dangerous :slight_smile: .

I was re-reading your original question a bit more properly just now…

If what you really want it a secure and authenticated websocket link between Python and Elixir…I’m thinking about it like this.

  • A websocket connection always starts out with a normal HTTP connection that then gets UPGRADEd to a websocket connection.
  • HTTPS has pretty solid security built in. Could you perhaps simply use server + client certificates, and make sure you use HTTPS / WSS connections. This way the HTTPS/Websocket libraries you use should take care of all the heavy lifting when it comes to securing the connection, and authenticating the user.
  • I don’t really know your use case that well, so this idea might make no sense at all :slight_smile:

If you’re not completely married to the idea of websockets, but still need bidirectional communications, then there’s always the option of going with something like Postgres listen/notify (pubsub), Redis Pubsub or something like ZeroMQ.

If you want something more “ready made” and opinionated it might also make sense to look at gRPC or Thrift. They’re creates specifically for cross-language function calls, and they can come in very handy at times.

If you don’t even need the bidirectional bit then good ol HTTPS with client & server certificates probably makes a lot of sense.

ErikNaslund

ErikNaslund

Ah you’re interactiving with Bloomberg over the internet - gotcha!

Cool that you used ZeroMQ before. I only suggested it because most people I know never heard of it, and much less used it :slight_smile: .

But you’re 100% right - it won’t be a good solution in this case. Seems like you have a pretty good plan on how to do it. Good luck, hope it works out great!

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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 Postg...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement