-
-
Save jfqd/e975dc393818d22c6bd99b820b686fc1 to your computer and use it in GitHub Desktop.
PHP <=> Ruby ( OpenSSL AES-256-CBC )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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