PHP script for DES/CBC/ with PKCS5Padding encryption and decryption

前端 未结 2 1954
轮回少年
轮回少年 2021-01-15 11:59

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*\'         


        
相关标签:
2条回答
  • 2021-01-15 12:42

    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.

    0 讨论(0)
  • 2021-01-15 12:42

    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");
    
    0 讨论(0)
提交回复
热议问题