【发布时间】:2014-06-24 09:44:42
【问题描述】:
我正在用 Ruby 替换旧的 PHP 系统。这里的开发人员为我编写了自己的加密代码(呃)。旧的 PHP 使用下面的代码来加密一些数据。我很难用 ruby 编写“解密”方法。
前言
我知道这个现有的 php 代码存在安全问题(三重奏、无盐等)。新的 Ruby 代码不存储任何敏感数据,但至少需要读取 PHP 创建的数据。
旧 PHP 代码
// old PHP code
class encrypter {
private $_crypt;
private $_key;
private $_algorithm;
private $_mode;
private $_init_vector;
public function __construct( $key = 'SomeRandomStringThisOneIsOK', $algorithm = 'tripledes', $mode = 'ecb', $init_vector = false ) {
$this->_key = $key;
$this->_algorithm = $algorithm;
$this->_mode = $mode;
$this->_init_vector = $init_vector;
$this->_crypt = mcrypt_module_open($algorithm, '', $mode, '') ;
$random_seed = MCRYPT_RAND;
//generate an initialization vector if none is given.
$init_vector = ($init_vector === false)
? mcrypt_create_iv(mcrypt_enc_get_iv_size($this->_crypt), $random_seed)
: substr($init_vector, 0, mcrypt_enc_get_iv_size($this->_crypt));
$expected_key_size = mcrypt_enc_get_key_size($this->_crypt);
// we dont need to know the real key, we just need to be able to confirm a hashed version
$key = substr(md5($key), 0, $expected_key_size);
mcrypt_generic_init($this->_crypt, $key, $init_vector);
}
public function encrypt($plain_string) {
return base64_encode(mcrypt_generic($this->_crypt, $plain_string));
}
public function decrypt($encrypted_string) {
return trim(mdecrypt_generic($this->_crypt, base64_decode($encrypted_string)));
}
public function __destruct() {
$this->_crypt = null;
}
public function __sleep() {
$this->_crypt = null;
return array_keys( get_object_vars( $this ) );
}
public function __wakeup () {
$this->__construct($this->_key, $this->_algorithm, $this->_mode, $this->_init_vector);
}
}
我不明白的地方
我不知道如何在 Ruby 中模拟这行 php。诚然,因为我不确定 100% php 在做什么。
mcrypt_create_iv(mcrypt_enc_get_iv_size($this->_crypt), $random_seed)
我目前拥有的 Ruby
我正计划使用 Encryptor Gem(它包装了 OpenSSL 方法)。我无法在 OS X 上安装 ruby-mcrypt,并且认为 OpenSSL 是内置的,所以为什么不使用它。同样,我只需要能够解密数据。
secret = "some_secret_key"
iv = "what goes here?"
Encryptor.default_options.merge!(:algorithm => 'des-ede-cbc', :key => secret)
decrypted_value = Encryptor.decrypt(:value => encrypted_value, :key => secret, :iv => iv)
【问题讨论】:
标签: php ruby encryption openssl mcrypt