質問

Rubyには、少しのデータを復号化する次の関数があります:

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でまったく同じことをしようとしていますが、何が間違っているのかわかりません。ここに私が持っているものがあります:

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;
}

出力は、探している文字列ではなく、ゴミになるだけです。アイデア?

そして、開始する前に MCRYPT_RIJNDAEL_256 に切り替えることは役に立たないようで、ivがブロックサイズほど長くないことについて不平を言うだけです。 このサイトは128/256がキーサイズではなくブロックサイズの表示。

役に立ちましたか?

解決 2

問題なく動作していたことがわかりました。テストデータが不正だっただけです。私が行った2つの変更は、 pack()を使用して(cafの提案で)、末尾からパディング文字を削除することでした。

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"
    );
}

他のヒント

個人的には、自家製の hex_to_str 関数について少し疑っています。なぜ pack( 'H *'、$ key)を使用しないのですか?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top