note 96635 added to function.mcrypt-encrypt

From: Date: Tue, 09 Mar 2010 13:58:13 +0000
Subject: note 96635 added to function.mcrypt-encrypt
Groups: php.notes 
Request: Send a blank email to php-notes+get-166825@lists.php.net to get a copy of this message
Contrary to what is implied in the mcrypt_encrypt() manual page, as well as the info given regarding the CBC vs CFB modes, mcrypt_encrypt() works just fine for encrypting binary data as well. A simple example verifies that the decrypted output is binary identical once cut to its original length: <?php // 448-bit key (56 bytes) - the only size that mcrypt/php uses for the Blowfish cipher // (using a smaller key works just fine, as mcrypt appends \0 to reach proper key-size) $key = 'SADFo92jzVnzSj39IUYGvi6eL8v6RvJH8Cytuiouh547vCytdyUFl76R'; // Blowfish/CBC uses an 8-byte IV $iv = substr( md5(mt_rand(),true), 0, 8 ); // do 50 encrypt/decrypt operations on some random data, and verify integrity with md5() for( $i = 0; $i < 50; $i++ ) { // create a random, binary string of random length $size = mt_rand( 25000, 500000 ); $c = 0; $data = null; while( $c++ * 16 < $size ) $data .= md5( mt_rand(), true ); $data = substr( $data, 0, $size ); $cksum = md5( $data ); // encrypt using Blowfish/CBC $enc = mcrypt_encrypt( MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv ); echo $size . ' -> ' . strlen( $enc ) . ' -> '; // decrypt (using same IV - a must for the CBC mode) $dec = mcrypt_decrypt( MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_CBC, $iv ); // cut the output with substr(), NOT by using rtrim() as is suggested in some of // the mcrypt manual pages - this is binary data, not plaintext echo ( md5(substr($dec, 0, $size)) == $cksum ? 'ok' : 'bad' ) . PHP_EOL; } ?> ---- Server IP: 80.67.10.226 Probable Submitter: 83.227.160.33 ---- Manual Page -- http://www.php.net/manual/en/function.mcrypt-encrypt.php Edit -- https://master.php.net/note/edit/96635 Del: integrated -- https://master.php.net/note/delete/96635/integrated Del: useless -- https://master.php.net/note/delete/96635/useless Del: bad code -- https://master.php.net/note/delete/96635/bad+code Del: spam -- https://master.php.net/note/delete/96635/spam Del: non-english -- https://master.php.net/note/delete/96635/non-english Del: in docs -- https://master.php.net/note/delete/96635/in+docs Del: other reasons-- https://master.php.net/note/delete/96635 Reject -- https://master.php.net/note/reject/96635 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#166825) next »