I\'m generating data to send from a Ruby stack to a PHP stack. I\'m using the OpenSSL::Cipher library on the Ruby side and the \'mcrypt\' library in PHP. When I encrypt us
Let me show you some code.
PHP code:
$privateKey = "1234567890123456"; # the size is 16.
$data = "hello";
$iv = "0123456789012345";
$result = mcrypt_encrypt(
MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv
)
$base64str = base64_encode($result);
$base64str = str_replace("+", "-", $base64str);
$base64str = str_replace("/","_", $base64str);
# => f-WffBXnf122NcVBUZ6Rlg==
Ruby code:
require 'base64'
require 'openssl'
private_key = "1234567890123456"
data = "hello"
iv = "0123456789012345"
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt
cipher.padding = 0 # we must disable padding in ruby.
cipher.key = private_key
cipher.iv = iv
block_size = cipher.block_size
# Add padding by yourself.
data = data + "\0" * (block_size - data.bytesize % block_size)
result = cipher.update(data) + cipher.final
Base64.urlsafe_encode64(result)
# ==> f-WffBXnf122NcVBUZ6Rlg==
As you can see I am using AES-128 in ruby because the size of private_key is 16.
So you have to use AES-256 if the size of your private_key is 32.
Formula: size_of_private_key * 8.