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

三世轮回 提交于 2019-12-01 09:30:40

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.

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!