Create a gist now

Instantly share code, notes, and snippets.

@kkosuge /sample.php
Last active Sep 19, 2016

PHP <=> Ruby ( OpenSSL AES-256-CBC )
<?php
const PASSWORD = '!!!!!sufficiently_long_password!!!!!';
const CIPHER_METHOD = 'AES-256-CBC';
function encrypt($str) {
$iv_length = openssl_cipher_iv_length(CIPHER_METHOD);
$iv = mcrypt_create_iv($iv_length, MCRYPT_RAND);
$str = $iv.$str;
$val = openssl_encrypt($str, CIPHER_METHOD, PASSWORD, 0, $iv);
return str_replace(array('+', '/', '='), array('_', '-', '.'), $val);
}
function decrypt($str) {
$val = str_replace(array('_','-', '.'), array('+', '/', '='), $str);
$data = base64_decode($val);
$iv_length = openssl_cipher_iv_length(CIPHER_METHOD);
$body_data = substr($data, $iv_length);
$iv = substr($data, 0, $iv_length);
$base64_body_data = base64_encode($body_data);
return openssl_decrypt($base64_body_data, CIPHER_METHOD, PASSWORD, 0, $iv);
}
$plain_data = 'secret text';
$encrypted = encrypt($plain_data);
$decrypted = decrypt($encrypted);
echo $encrypted."\n";
echo $decrypted."\n";
require 'openssl'
require 'base64'
require 'pry'
PASSWORD = '!!!!!sufficiently_long_password!!!!!';
CIPHER_METHOD = 'AES-256-CBC'
def encrypt(str)
cipher = OpenSSL::Cipher.new(CIPHER_METHOD)
cipher.encrypt
iv = OpenSSL::Random.random_bytes(cipher.iv_len)
cipher.iv = iv
cipher.key = PASSWORD
str = iv + str
data = cipher.update(str) + cipher.final
Base64.urlsafe_encode64(data)
end
def decrypt(str)
data = Base64.urlsafe_decode64(str)
cipher = OpenSSL::Cipher.new(CIPHER_METHOD)
cipher.decrypt
cipher.key = PASSWORD
cipher.iv = data[0..(cipher.iv_len-1)]
data_body = data[cipher.iv_len..-1]
cipher.update(data_body) + cipher.final
end
plain_data = 'secret text';
encrypted = encrypt(plain_data)
decrypted = decrypt(encrypted)
puts encrypted
puts decrypted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment