favetelinguis

favetelinguis

Need help converting Java encryption example to Elixir

Im writing an integration in Elixir and as one part I need to create an encrypted login string. However I have zero experience with encryption and im not able to understand the Erlang docs well enogh to understand. I would rather use pure Erlang to do this that add some dependency to a Elexir wrapper if possible.

The Java code I need to write in Elixir looks as follows.

  private String encryptAuthParameter(String user, String password)
      throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, NoSuchPaddingException,
          InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    // Construct the base for the auth parameter
    String login =
        Base64.getEncoder().encodeToString(user.getBytes())
            + ":"
            + Base64.getEncoder().encodeToString(password.getBytes())
            + ":"
            + Base64.getEncoder()
                .encodeToString(String.valueOf(System.currentTimeMillis()).getBytes());

    // RSA encrypt it using NNAPI public key
    PublicKey pubKey = getKeyFromPEM(Main.PUBLIC_KEY_FILENAME);
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    byte[] encryptedBytes = cipher.doFinal(login.getBytes("UTF-8"));

    // Encode the encrypted data in Base64
    String encodedEncryptedBytes = Base64.getEncoder().encodeToString(encryptedBytes);

    return URLEncoder.encode(encodedEncryptedBytes, "UTF-8");
  }

  private static PublicKey getKeyFromPEM(String filename)
      throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    BufferedReader reader = null;
    try {
      reader = new BufferedReader(new FileReader(filename));
      String line = null;
      String key = "";
      while (true) {
        line = reader.readLine();
        if (line == null) break;
        else if (line.startsWith("-----BEGIN PUBLIC KEY-----")) continue;
        else if (line.startsWith("-----END PUBLIC KEY-----")) continue;
        else key += line.trim();
      }
      byte[] binary = Base64.getDecoder().decode(key);
      X509EncodedKeySpec spec = new X509EncodedKeySpec(binary);
      KeyFactory kf = KeyFactory.getInstance("RSA");
      return kf.generatePublic(spec);
    } finally {
      if (reader != null) {
        reader.close();
      }
    }
  }

The only thing I have so far is:

  def encryptAuthParameter(user, password) do
    now = DateTime.utc_now() |> DateTime.to_unix(:millisecond) |> Integer.to_string()
    # Convert to Base64
    login = Base.encode64(user) <> ":" <> Base.encode64(password) <> ":" <> Base.encode64(now)
    # Use public key to encode message
    File.read!()
    # Base 64 encode the encrypted string
    login
  end

Most Liked

favetelinguis

favetelinguis

Turns out it was not that hard. Here is the code that got it working.

  def encryptAuthParameter(user, password) do
    # Convert to Base64
    now_str = DateTime.utc_now() |> DateTime.to_unix(:millisecond) |> Integer.to_string()
    login_msg = Base.encode64(user) <> ":" <> Base.encode64(password) <> ":" <> Base.encode64(now_str)
    # Use public key to encode message
    raw_p_key = getKeyFromPEM(@key)
    [enc_p_key] = :public_key.pem_decode(raw_p_key)
    p_key = :public_key.pem_entry_decode(enc_p_key)
    enc_msg = :public_key.encrypt_public(login_msg, p_key)
    # Base 64 encode the encrypted string
    Base.encode64(enc_msg)
  end

  def getKeyFromPEM(filename) do
    File.read!(filename)
  end

Where Next?

Popular in Questions Top

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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
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
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
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
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

We're in Beta

About us Mission Statement