Encrypt with Ruby decrypt in PHP
2009年12月16日星期三
Ruby encrypt decrypt
http://coderay.rubychan.de/rays/show/6287
require 'openssl'
require 'base64'
def encipher(data_to_encode)
cipher = OpenSSL::Cipher::Cipher.new("des-ede3-cbc")
key = "secretkey"
cipher.encrypt(key)
encoded_data = cipher.update(data_to_encode)
encoded_data cipher.final
return Base64.encode64(encoded_data)
end
def decipher(encoded)
encoded = Base64.decode64(encoded)
cipher = OpenSSL::Cipher::Cipher.new("des-ede3-cbc")
key = "secretkey"
cipher.decrypt(key)
encoded_data = cipher.update(encoded)
encoded_data cipher.final
return encoded_data
end
PHP encrypt decrypt
http://coderay.rubychan.de/rays/show/6288
function getkeyiv($key_size, $iv_size, $key, $iv='') {
if ($iv == '') {
$iv = 'OpenSSL for Ruby rulez!';
}
$iv = substr($iv,0,$iv_size);
$gen = '';
do {
$gen = $gen.md5($gen.$key.$iv,true);
} while (strlen($gen)($iv_size+$key_size));
$o[0] = substr($gen,0,$key_size);
$o[1] = $iv; //this is not the generated IV,
//just the original "salt" cut to the required size
return $o;
}
function trimpadding($str) {
if (ord($str[strlen($str)-1]) 9) {
return rtrim($str,$str[strlen($str)-1]);
} else {
return $str;
}
}
function encipher($data_to_encode){
$key = 'secretkey';
$td = mcrypt_module_open(MCRYPT_TRIPLEDES, '', MCRYPT_MODE_CBC, '');
$iv_size = mcrypt_enc_get_iv_size($td);
$key_size = mcrypt_enc_get_key_size($td);
$genkey = getkeyiv($key_size, $iv_size,$key);
if (mcrypt_generic_init($td,$genkey[0],$genkey[1]) != -1) {
$encoded_data = mcrypt_generic($td, $data_to_encode);
}
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return base64_encode($encoded_data);
}
function decipher($encoded) {
$key = 'secretkey';
$decrypted='';
$enc = base64_decode($encoded);
$td = mcrypt_module_open(MCRYPT_TRIPLEDES, '', MCRYPT_MODE_CBC, '');
$iv_size = mcrypt_enc_get_iv_size($td);
$key_size = mcrypt_enc_get_key_size($td);
$genkey = getkeyiv($key_size, $iv_size,$key);
if (mcrypt_generic_init($td,$genkey[0],$genkey[1]) != -1) {
$decrypted = mdecrypt_generic($td, $enc);
}
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return trimpadding($decrypted);
}
?>
发表评论
订阅 博文评论 [Atom]
<< 主页