note 39904 added to ref.mcrypt
| From: | robert at peakepro dot com | Date: | Sun, 15 Feb 2004 02:17:06 +0000 |
| Subject: | note 39904 added to ref.mcrypt | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-65154@lists.php.net to get a copy of this message | ||
I found this nested loop very useful for checking the sanity of my libmcrypt install. It turned out
many of the modules weren't working in certain modes. Hopefully this will save someone some
frustration:
<?php
/* run a self-test through every listed cipher and mode
*/
function mcrypt_check_sanity() {
$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();
foreach ($algorithms as $cipher) {
if(mcrypt_module_self_test($cipher)) {
print $cipher." ok.<br />\n";
} else {
print $cipher." not ok.<br />\n";
}
foreach ($modes as $mode) {
if(mcrypt_test_module_mode($cipher,$mode)) {
$result = "ok";
} else {
$result = "not ok";
}
print $cipher." in mode ".$mode." ".$result."<br
/>\n";
mcrypt_module_close($td);
}
}
}
// a variant on the example posted in mdecrypt_generic
// that works on versions of libmcrypt
// without mcrypt_generic_deinit() defined
function mcrypt_test_module_mode($module,$mode) {
/* Data */
$key = 'this is a very long key, even too long for the cipher';
$plain_text = 'very important data';
/* Open module, and create IV */
$td = mcrypt_module_open($module, '',$mode, '');
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
$iv_size = mcrypt_enc_get_iv_size($td);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
/* Initialize encryption handle */
if (mcrypt_generic_init($td, $key, $iv) != -1) {
/* Encrypt data */
$c_t = mcrypt_generic($td, $plain_text);
mcrypt_generic_end($td);
mcrypt_module_close($td);
/* Reinitialize buffers for decryption */
/* Open module, and create IV */
$td = mcrypt_module_open($module, '', $mode, '');
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
$iv_size = mcrypt_enc_get_iv_size($td);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$p_t = mdecrypt_generic($td, $c_t);
/* Clean up */
mcrypt_generic_end($td);
mcrypt_module_close($td);
}
if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) {
return TRUE;
} else {
return FALSE;
}
}
// remember to call:
// mcrypt_check_sanity();
?>
----
Manual Page -- http://www.php.net/manual/en/ref.mcrypt.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+39904
Delete -- http://master.php.net/manage/user-notes.php?action=delete+39904&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+39904&report=yes
Search -- http://master.php.net/manage/user-notes.php