将Ruby AES256解密函数转换为PHP [英] Converting Ruby AES256 decrypt function to PHP

查看:97
本文介绍了将Ruby AES256解密函数转换为PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby中具有以下功能,可以解密一些数据:

I have the following function in Ruby that decrypts a bit of data:

def decrypt(key, iv, cipher_hex)
    cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')

    cipher.decrypt
    cipher.key = key.gsub(/(..)/){|h| h.hex.chr}
    cipher.iv = iv.gsub(/(..)/){|h| h.hex.chr}

    decrypted_data = cipher.update(cipher_hex.gsub(/(..)/){|h| h.hex.chr})
    decrypted_data << cipher.final

    return decrypted_data
end

我正在尝试在PHP中做完全相同的事情,但是我不确定自己做错了什么.这就是我所拥有的:

I'm trying to do the exact same thing in PHP, but I'm not sure what I'm doing wrong. Here's what I've got:

function decrypt_data($key, $iv, $cipher_hex) {
    return mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128, 
        hex_to_str($key), 
        hex_to_str($cipher_hex), 
        MCRYPT_MODE_CBC, 
        hex_to_str($iv)
    );
}

function hex_to_str($hex_str) {
    preg_match_all('/(..)/', $hex_str, $matches);

    $to_return = '';
    foreach ($matches[1] as $val)
        $to_return .= chr(hexdec($val));
    return $to_return;
}

输出最终只是垃圾,而不是我要查找的字符串.想法?

The output just ends up being garbage, not the string I'm looking for. Ideas?

在我们甚至开始之前,将其切换为MCRYPT_RIJNDAEL_256似乎并没有帮助,只会使它抱怨iv的长度不如块大小.我相信在这种情况下128是正确的,因为此网站表示128/256是指示块的大小,而不是密钥的大小.

And before we even start, switching it to MCRYPT_RIJNDAEL_256 doesn't seem help and just causes it to complain about the iv not being as long as the block size. I believe 128 is correct in this case since this site says that the 128/256 is an indication of the block size, not the key size.

推荐答案

事实证明它工作正常,只是我的测试数据不正确.我进行的两个更改是使用pack()(根据caf的建议),并从末尾删除了填充字符.

It turns out that it was working fine, it's just that my test data was bad. The two changes I made were using pack() (at caf's suggestion) and dropping the padding characters from the end.

function decrypt_data($key, $iv, $cipher_hex) {
    return rtrim(
        mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128, 
            pack('H*', $key), 
            pack('H*', $cipher_hex), 
            MCRYPT_MODE_CBC, 
            pack('H*', $iv)
        ), 
        "\x00..\x1F"
    );
}

这篇关于将Ruby AES256解密函数转换为PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆