D
D
Dark192015-06-02 18:39:35
PHP
Dark19, 2015-06-02 18:39:35

How to decrypt text with AES in CBC mode?

Good afternoon, there is such a task: you need to implement a cryptosystem that uses AES in CBC mode. The 16-byte initial IV is chosen at random and prepended to the front of the ciphertext. For CBC mode, use the PKCS5 scheme to pad the message so that its length becomes a multiple of the block length. Below are the key and the encrypted message in hexadecimal. The task is to decrypt the message.
Actually the data:
1) key - 140b41b22a29beb4061bda66b6747e14
2) ciphertext - 4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee \
2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81
I don’t rummage in this at all, but the lab needs to be done. Having searched the Internet for solutions, I found something in PHP and brought it to the desired form for this task, but I don’t know what to do next to decrypt the text?
Here is the code:

<?php
$Pass = "140b41b22a29beb4061bda66b6747e14";
$Clear = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee\2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81";
$newClear = fnDecrypt($Clear, $Pass);
echo "Decrypted: ".$newClear."";
function fnDecrypt($sValue, $sSecretKey)
{
return rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_CBC, mcrypt_create_iv( mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC ), MCRYPT_RAND) );
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
krypt3r, 2015-06-03
@Dark19

Something like this you need:

<?php
function pkcs5_pad ($text)
{
    $size = mcrypt_get_block_size (MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $pad = $size - (strlen($text) % $size);
    return $text . str_repeat(chr($pad), $pad);
}

function pkcs5_unpad ($text)
{
    $pad = ord ($text{strlen ($text) - 1});
    if ($pad > strlen ($text))
        return false;
    if (strspn($text, $text{strlen($text) - 1}, strlen($text) - $pad) != $pad) {
        return false;
    }
    return substr($text, 0, -1 * $pad);
}

$key = '140b41b22a29beb4061bda66b6747e14';
$enc = '4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81';
$iv = substr ($enc, 0, 32);
$enc = substr ($enc, 32);
$iv = hex2bin ($iv);
$enc = hex2bin ($enc);
$key = hex2bin ($key);

$dec = mcrypt_decrypt (MCRYPT_RIJNDAEL_128, $key, $enc, MCRYPT_MODE_CBC, $iv);
$dec = pkcs5_unpad ($dec);
echo "$dec\n"; /* Basic CBC mode encryption needs padding. */

M
m0rd, 2015-06-02
@m0rd

You did not write the code correctly, it is written in the task

The 16-byte initial IV is randomly chosen and prepended to the front of the ciphertext

It must be taken from the beginning, and you generate it. Well, base64_decode is probably superfluous.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question