Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do AES-256-ECB encryption in Elixir?

I have got a legacy application which has the following PHP code

<?php
  $ivSize = openssl_cipher_iv_length('AES-256-ECB');
  $iv = openssl_random_pseudo_bytes($ivSize);   
  $input = "eeeeeeeeeeeeeeee";
  $key = "dddddddddddddddd";
  print base64_encode(openssl_encrypt($input,"AES-256-ECB", $key,OPENSSL_RAW_DATA,$iv));
?>

This script gives the following output

wenBZciza683mhjk3ydcMeOZBIFais5RNpIQ6jkxLGA=

I tried to convert the above PHP script into Elixir as below

 input = "eeeeeeeeeeeeeeee"
 key = "dddddddddddddddd"
 Base.encode64 :crypto.block_encrypt(:aes_ecb, key, string)

And I am getting the following output in Elixir:

 "Br5nc46qS2eAXajEbP0pGw=="

What am I missing? What should I do to get the same output in Elixir as in PHP?

like image 455
shankardevy Avatar asked Mar 06 '23 02:03

shankardevy


1 Answers

You're using a 256 bit encryption but your inputs are 128 bits. PHP automatically pads the key to 256 bits and input to the next multiple of 256 bits since you explicitly specified you want AES-256-ECB. I didn't know exactly how it pads them but through some trial and error I've found out that the key is padded with null bytes and the input is padded with PKCS7.

Here's an implementation of PKCS7 padding:

defmodule PKCS7 do
  def pad(data, block_size) do
    to_add = block_size - rem(byte_size(data), block_size)
    data <> String.duplicate(<<to_add>>, to_add)
  end
end

Here's the final code:

input = "eeeeeeeeeeeeeeee" |> PKCS7.pad(32)
key = "dddddddddddddddd" <> <<0::128>>
IO.puts Base.encode64(:crypto.block_encrypt(:aes_ecb, key, input))

Output:

wenBZciza683mhjk3ydcMeOZBIFais5RNpIQ6jkxLGA=
like image 63
Dogbert Avatar answered Mar 27 '23 03:03

Dogbert