note 74459 added to function.md5
| From: | orenivr at gmail dot com | Date: | Thu, 12 Apr 2007 12:19:38 +0000 |
| Subject: | note 74459 added to function.md5 | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125329@lists.php.net to get a copy of this message | ||
Below is MD5-based block Encrypt & Decrypt functions.
Originate whiten by "Alexander Valyalkin".
Now it works with php4 and php5 (without "+" and " " space problem)
very useful to encrypt secret data before transfer it over the network.
Best regards,
Oren Wisman
<?php
function get_rnd_iv($iv_len)
{
$iv = '';
while ($iv_len-- > 0) {
$iv .= chr(mt_rand() & 0xff);
}
return $iv;
}
function md5_encrypt($plain_text, $password, $iv_len = 16)
{
$plain_text .= "\x13";
$n = strlen($plain_text);
if ($n % 16) $plain_text .= str_repeat("\0", 16 - ($n % 16));
$i = 0;
$enc_text = get_rnd_iv($iv_len);
$iv = substr($password ^ $enc_text, 0, 512);
while ($i < $n)
{
$block = substr($plain_text, $i, 16) ^ pack('H*', md5($iv));
$enc_text .= $block;
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
$data = base64_encode($enc_text);
$data =
str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
function md5_decrypt($enc_text, $password, $iv_len = 16)
{
$data =
str_replace(array('-','_'),array('+','/'),$enc_text);
$mod4 = strlen($data) % 4;
if ($mod4) $data .= substr('====', $mod4);
$enc_text= base64_decode($data);
$n = strlen($enc_text);
$i = $iv_len;
$plain_text = '';
$iv = substr($password ^ substr($enc_text, 0, $iv_len), 0, 512);
while ($i < $n)
{
$block = substr($enc_text, $i, 16);
$plain_text .= $block ^ pack('H*', md5($iv));
$iv = substr($block . $iv, 0, 512) ^ $password;
$i += 16;
}
return preg_replace('/\\x13\\x00*$/', '', $plain_text);
}
/********************************************/
$plain_text = 'very secret string';
$password = 'very secret password';
$enc_text = md5_encrypt($plain_text, $password);
echo "encrypted text is: [${enc_text}]<br />\n";
$plain_text2 = md5_decrypt($enc_text, $password);
echo "decrypted text is: [${plain_text2}]<br />\n";
?>
----
Server IP: 212.199.163.191
Probable Submitter: 213.8.172.3
----
Manual Page -- http://www.php.net/manual/en/function.md5.php
Edit -- https://master.php.net/note/edit/74459
Del: integrated -- https://master.php.net/note/delete/74459/integrated
Del: useless -- https://master.php.net/note/delete/74459/useless
Del: bad code -- https://master.php.net/note/delete/74459/bad+code
Del: spam -- https://master.php.net/note/delete/74459/spam
Del: non-english -- https://master.php.net/note/delete/74459/non-english
Del: in docs -- https://master.php.net/note/delete/74459/in+docs
Del: other reasons-- https://master.php.net/note/delete/74459
Reject -- https://master.php.net/note/reject/74459
Search -- https://master.php.net/manage/user-notes.php