note 102427 added to function.mcrypt-encrypt

[email protected] Sun, 13 Feb 2011 19:58:08 -0800
Newsgroups php.notes
Message-ID <[email protected]>
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!
----
Server IP: 208.69.120.55
Probable Submitter: 76.110.50.60
----
Manual Page -- http://www.php.net/manual/en/function.mcrypt-encrypt.php
Edit        -- https://master.php.net/note/edit/102427
Del: integrated  -- https://master.php.net/note/delete/102427/integrated
Del: useless     -- https://master.php.net/note/delete/102427/useless
Del: bad code    -- https://master.php.net/note/delete/102427/bad+code
Del: spam        -- https://master.php.net/note/delete/102427/spam
Del: non-english -- https://master.php.net/note/delete/102427/non-english
Del: in docs     -- https://master.php.net/note/delete/102427/in+docs
Del: other reasons-- https://master.php.net/note/delete/102427
Reject      -- https://master.php.net/note/reject/102427
Search      -- https://master.php.net/manage/user-notes.php