PHP script for DES/CBC/ with PKCS5Padding encrypti

2020-03-30 03:46发布

问题:

I would like to know in the following code if PKCS#5 padding is added ? If not how to add ?

$message = "insert plaintext message here";

$iv  = pack('H*', 'insert hex iv here');
$key = pack('H*', 'insert hex key here');

$enc = mcrypt_encrypt(MCRYPT_DES, $key, $message, MCRYPT_MODE_CBC, $iv);

echo bin2hex($enc);

I also want to create a PHP code to decrypt a string created with DES/CBC/PKCS5Padding. I think the above mentioned code can be modified to get a decryption.

The important thing for me is to get the PKCS#5 Padding and Unpadding script.

回答1:

No, it is not added. Unfortunately PHP / mcrypt uses zero padding until the message is N times the block size.

To add PKCS#5 padding, use the formula:

p = b - l % b

Where l is the message length, b is the block size and % is the remainder operation. Then add p bytes with the value p to the end before performing the encryption.



回答2:

I have found some scripts and modified them below , check if now the PKCS#5 Padding is done .

<?php 
function printStringToHex($text)
{
    $size = strlen($text);
    for($i = 0; $i < $size; $i++)
    {
        echo dechex(ord($text[$i])) . " ";
    }
}

function encrypt($input) 
{ 
    echo "<PRE>*** Encrypt *** </PRE>";
    echo "<PRE>Raw input: " . $input . "</PRE>";
    $size = mcrypt_get_block_size('des', 'cbc'); 
    echo "<PRE>Block: " . $size . "</PRE>";
    $input = pkcs5_pad($input, $size); 
    echo "<PRE>PKCS#5 padding: ";
    echo printStringToHex($input);
    echo "</PRE>";

    $td = mcrypt_module_open('des', '', 'cbc', ''); 
    $iv = pack('H*','insert hex iv here');
    $key = pack('H*','insert hex key here');
    mcrypt_generic_init($td, $key, $iv); 
    $data = mcrypt_generic($td, $input); 
    echo "<PRE>Raw output: " . $data . "</PRE>";
    echo "<PRE>Hex output: ";
    echo printStringToHex($data);
    echo "</PRE>";
    mcrypt_generic_deinit($td); 
    mcrypt_module_close($td); 
    $data = base64_encode($data); 
    echo "<PRE>B64 output: " . $data . "</PRE>";
    echo "<PRE>B64 output len: ";
    echo strlen($data) . "</PRE>";
    return $data; 
} 

function pkcs5_pad ($text, $blocksize) 
{ 
    $pad = $blocksize - (strlen($text) % $blocksize); 
    return $text . str_repeat(chr($pad), $pad); 
} 

$enc = encrypt("insert plaintext message here");