note 102427 deleted from function.mcrypt-encrypt by danbrown
[email protected] Mon, 14 Feb 2011 05:32:31 -0800
| Newsgroups | php.notes |
|---|---|
| Message-ID | <[email protected]> |
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!