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
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
1
Popular in Questions
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this:
...
New
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
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
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Hi,
I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
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
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Other popular topics
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
Hi all,
Trying to get some more clarity over utc_datetime and naive_datetime for Ecto:
https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
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
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
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
Hello everybody,
usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
New
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
Hi guys, i’m new in the Elixir world, and i have to say, that i love it!
i’m having some problem to understand anonymous functions with ...
New
I have a super simple question about elixir - how would I take a file like this
foo bar baz
and output a new file that enumerates th...
New







