note 102427 deleted from function.mcrypt-encrypt by danbrown
| From: | danbrown@php.net | Date: | Mon, 14 Feb 2011 13:32:31 +0000 |
| Subject: | note 102427 deleted from function.mcrypt-encrypt by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176984@lists.php.net to get a copy of this message | ||
Note Submitter: das700 at gmail dot com
----
For anyone that wants PKCS7 compatibility (since PHP default is to use Zeros padding) I've
found this to work rather well (and seems binary compatible)
<?php
header("Content-type: text/plain");
function addpadding($string, $blocksize = 32){
$len = strlen($string);
$pad = $blocksize - ($len % $blocksize);
$string .= str_repeat(chr($pad), $pad);
return $string;
}
function strippadding($string){
$slast = ord(substr($string, -1));
$slastc = chr($slast);
$pcheck = substr($string, -$slast);
if(preg_match("/$slastc{".$slast."}/", $string)){
$string = substr($string, 0, strlen($string)-$slast);
return $string;
} else {
return false;
}
}
function keytest($keyfile = "key.key"){
$keyfile = file($keyfile);
$key = base64_decode($keyfile[0]);
$iv = base64_decode($keyfile[1]);
$enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, addpadding("Hello World"),
MCRYPT_MODE_CBC, $iv);
$dec = strippadding(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $enc, MCRYPT_MODE_CBC, $iv));
echo "Encrypted:".base64_encode($enc)."\n";
echo "Decrypted:$dec";
}
keytest();
?>
The key.key file basically just looks like this
jZjneNba78tqCuB8l8eQrXo4nCs6LmlRMflfjEdnnLg=
Uty9weAigmbjIwwng3532FJbeXxGJzhl4Ymw9ry6Slc=
And from this it is entirely compatible with C#'s PaddingMode.PKCS7 which I needed for an
application I wrote, I hope this helps!