Автор Тема: libmcrypt-помгите новичку плиз :(  (Прочитано 4002 раз)

0 Пользователей и 1 Гость просматривают эту тему.

Оффлайн reLax[0x00]

  • Завсегдатай
  • Пользователь
  • **
  • Сообщений: 68
  • +0/-0
  • 0
    • Просмотр профиля
    • http://www.microcat.ru
libmcrypt-помгите новичку плиз :(
« : 14 Апреля 2006, 21:35:37 »
Была когда то задача  обеспечить безопасную транзакцию между тремя SQL серверами без использования https..выход один нашел - заюзать libmcrypt. В принципе то все равботает, но криво на самом деле. Во первых урезание NULL-бит символов в конце-го это еще не проблма. Проблма что я что то не поняимаю-в функцию my_encrypt() я не могу всунуть константу  случайного выбора :( часть кода своровал с php.net для избежания лишних комментариев-скажу сразу. Может вы знаете. Это так, оболочка чтобы алгоритмы потестить.


<?
require_once 
$_SERVER[\'DOCUMENT_ROOT\']."/functions.php";

$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();


$_GET[\'uid\'] = ($_GET[\'uid\'] > count ($algorithms))?max(array_keys($algorithms)):$_GET[\'uid\'];
$poststring = htmlspecialchars (stripslashes ($_POST[\'string\']));

$random = array (
                "MCRYPT_DEV_RANDOM",
                "MCRYPT_DEV_URANDOM",
                "MCRYPT_RAND",
                );

if (!empty($_GET[\'uid\'])) 
    {
$disable_select = "disabled";
     foreach ($modes as $mod) 
	
    {
if (@mcrypt_test_module_mode ($algorithms[$_GET[\'uid\']], $mod))
$option_modes .= "<option value=\\"".$mod."\\" ".(($_POST[\'mode\']==$mod)?"selected":"").">MCRYPT_MODE_".strtoupper ($mod)."</option>";
         }

         foreach ($random as $mtrand) 
	
	
     {
         $option_random .= "<option value=\\"".$mtrand."\\"".((isset($_POST[\'rand\'])&&$_POST[\'rand\']==$mtrand)?"selected":"").">".$mtrand."</option>";
              }

$value_text = (!isset($_POST[\'cikey\']))? sha1 (uniqid(rand(), true)):$_POST[\'cikey\'];

} else {
$disable_form = "disabled";
$option_modes = "<option>[******************]</option>";
$option_random = "<option>[******************]</option>";
$value_text = "[************************************************]";
    }

function mcrypt_check_sanity() {
global $modes, $algorithms;
$html = "<div align=\\"center\\" class=\\"white\\">Таблица констант алгоритмов и их значений библиотеки LIBMCRYPT</div>";
$html.= "<table border=\\"0\\" align=\\"center\\" cellpadding=\\"1\\" cellspacing=\\"2\\">";
$html.= "<tr><td align=center class=\\"greytable\\">Алгоритм</td><td align=center class=\\"greytable\\">Статус</td><td class=\\"greytable\\" align=\\"center\\">Размер ключа</td><td class=\\"greytable\\" align=\\"center\\">Размер блока</td>";

foreach ($modes as $mode) 
$html.= "<td class=\\"greytable\\" align=\\"center\\">".strtoupper($mode)."</td>";
$html.= "</tr>";
 foreach ($algorithms as $cipher) 
    {
     $html.= "<tr><td class=\\"greytable\\" align=\\"left\\">".strtoupper($cipher)."</td>";

       if(mcrypt_module_self_test($cipher)) 
	
       {
     $html.= "<td align=center class=\\"greentable\\">Активен</td>";
               } else {
     $html.= "<td class=\\"redtable\\" align=\\"center\\">Не активен</td>";
           }

$html.= "<td class=\\"greylight\\" align=\\"center\\">";   
$ksizes = mcrypt_module_get_supported_key_sizes($cipher);
          if($ksizes==NULL)
	
         {
          $html.= "1-".mcrypt_module_get_algo_key_size($cipher)."</td>";
              } else {
	
            foreach ($ksizes as $size)
	
	
       
	
                  {
               $html.= $size." ";
                      }
	
	
	
   }
$html.= "</td>";

if (mcrypt_module_get_algo_block_size($cipher) == 1) 
           {
$html.= "<td class=\\"yellowtable\\" align=\\"center\\">Поток</td>";
        } else {
$html.="<td class=\\"greylight\\" align=\\"center\\">".mcrypt_module_get_algo_block_size($cipher)."</td>"; 
           }

   foreach ($modes as $mode) 
       {
       if($mode == \'\') 
	
       {
           $result = "<td align=center class=\\"redtable\\">Нет</td>";
       } else if(mcrypt_test_module_mode($cipher,$mode)) 
	
       {
             $result = "<td class=\\"greentable\\" align=\\"center\\">Да</td>";
       } else {
             $result = "<td class=\\"redtable\\" align=\\"center\\">Нет</td>";
       }
       $html.= $result;
   }
      $html.= "</tr>";
 }
$html.= "</table>";
      return $html;
}

function checksum () {
global $algorithms, $poststring;

$comments = array (
                 "3des"=>"Тройной DES, стандарт шифрования данных США (U.S. Data Encryption Standart)",
                 "tripledes"=>"Тройной DES, стандарт шифрования данных США (U.S. Data Encryption Standart)",
	
	
	
	
 "3way"=>"3way (Joan Daemen)",
	
	
	
	
 "threeway"=>"3way (Joan Daemen)",
	
	
	
	
 "blowfish"=>"Blowfish (Bruce Schneier)",
	
	
	
	
 "blowfish-compat"=>"Blowfish, совместимый с другими реализациями (Bruce Schneier)",
	
	
	
	
 "blowfish_128"=>"Blowfish (Bruce Schneier)",
	
	
	
	
 "blowfish_192"=>"Blowfish (Bruce Schneier)",
	
	
	
	
 "blowfish_256"=>"Blowfish (Bruce Schneier)",
	
	
	
	
 "blowfish_448"=>"Blowfish (Bruce Schneier)",
                 "cast_128"=>"CAST (Carlisle Adams & Stafford Tavares)",
	
	
	
	
 "cast_256"=>"CAST (Carlisle Adams & Stafford Tavares)",
	
	
	
	
 "crypt"=>"Однопроходный алгоритм шифрования Unix",
	
	
	
	
 "enigma"=>"Однопроходный алгоритм шифрования Unix",
	
	
	
	
 "des"=>"DES, стандарт шифрования данных США (U.S. Data Encryption Standart)",
	
	
	
	
 "gost"=>"Государственный стандарт СССР",
	
	
	
	
 "idea"=>"Международный стандарт шифрования данных (International Data Encryption Algorithm)",
	
	
	
	
 "loki97"=>"LOKI97 (Lawrie Brown & Josef Pieprzyk)",
	
	
	
	
 "mars"=>"MARS (IBM)",
                 "panama"=>"PANAMA (Joan Daemen & Craig Clapp)",
	
	
	
	
 "rc2"=>"Rivest Cipher 2",
	
	
	
	
 "rc2_1024"=>"Rivest Cipher 2",
	
	
	
	
 "rc2_128"=>"Rivest Cipher 2",
	
	
	
	
 "rc2_256"=>"Rivest Cipher 2",
	
	
	
	
 "rc4"=>"Rivest Cipher 4",
	
	
	
	
 "arcfour"=>"Не имеющий торговой марки, RC4-совместимый",
	
	
	
	
 "arcfour_iv"=>"Не имеющий торговой марки, RC4-совместимый с вектором инициализации",
	
	
	
	
 "rc6"=>"Rivest Cipher 6",
                 "rc6_128"=>"Rivest Cipher 6",
	
	
	
	
 "rc6_192"=>"Rivest Cipher 6",
	
	
	
	
 "rc6_256"=>"Rivest Cipher 6",
	
	
	
	
 "rijndael-128"=>"Rijndael (Joan Daemen & Vincent Rijmen)",
	
	
	
	
 "rijndael-192"=>"Rijndael (Joan Daemen & Vincent Rijmen)",
	
	
	
	
 "rijndael-256"=>"Rijndael (Joan Daemen & Vincent Rijmen)",
	
	
	
	
 "saferplus"=>"SAFER+, основанный на SAFER - безопасной и быстрой процедуре шифрования с улучшенным набором усиленных ключей (Secure And Fast Encryption Routine With Strengthened Key Schedule)",
	
	
	
	
 "safer_128"=>"Безопасная и быстрая процедура шифрования с улучшенным набором усиленных ключей (Secure And Fast Encryption Routine With Strengthened Key Schedule)",
	
	
	
	
 "safer_64"=>"Безопасная и быстрая процедура шифрования с усиленным ключом (Secure And Fast Encryption Routine With Strengthened Key)",
                 "serpent"=>"Serpent (Ross Anderson, Eli Biham & Lars Knudsen)",
	
	
	
	
 "serpent_128"=>"Serpent (Ross Anderson, Eli Biham & Lars Knudsen)",
	
	
	
	
 "serpent_192"=>"Serpent (Ross Anderson, Eli Biham & Lars Knudsen)",
	
	
	
	
 "serpent_256"=>"Serpent (Ross Anderson, Eli Biham & Lars Knudsen)",
	
	
	
	
 "skipjack"=>" Стандарт шифрования Управления Национальной Безопасности США (U.S. NSA Clipper Escrowed Encryption Standart)",
	
	
	
	
 "twofish"=>"Twofish (Counterpane Systems)",
	
	
	
	
 "twofish_128"=>"Twofish (Counterpane Systems)",
	
	
	
	
 "twofish_192"=>"Twofish (Counterpane Systems)",
	
	
	
	
 "twofish_256"=>"Twofish (Counterpane Systems)",
                 "wake"=>"Шифрование строк с авто-ключом (Word Auto Key Encryption, David Wheeler)",
	
	
	
	
 "xtea"=>"Расширенный малый алгоритм шифрования (Extended Tiny Encryption Algorithm, David Wheeler, Roger Needham",
	
	
	
	
 "ecb"=>"Режим электронной кодовой книги (Electronic Code Book - ECB)",
	
	
	
	
 "cbc"=>"Режим цепочки кодовых блоков (Cipher Block Chaining - CBC)",
	
	
	
	
 "cfb"=>"Режим обратной кодовой связи (Cipher Feedback - CFB)",
	
	
	
	
 "ofb"=>"Режим выходной обратной связи с 8-и битной обратной связью (Output Feedback - OFB)",
	
	
	
	
 "nofb"=>"Режим выходной обратной связи (OFB) с n-битной обратной связью, где n - это размер блока, используемый алгоритмом",
                 "ncfb"=>"Режим обратной кодовой связи (CFB) с n-битной обратной связью, где n - это размер блока, используемый алгоритмом",
	
	
	
	
 "stream"=>"Режим потокового кода (Stream Cipher)",
	
	
	
	
 "MCRYPT_DEV_RANDOM"=>"Устройство случайности /dev/random",
                 "MCRYPT_DEV_URANDOM"=>"Устройство случайности /dev/urandom",
	
	
	
	
 "MCRYPT_RAND"=>"Встроенный генератор случайных чисел"
	
	
	
	
                   );

Оффлайн reLax[0x00]

  • Завсегдатай
  • Пользователь
  • **
  • Сообщений: 68
  • +0/-0
  • 0
    • Просмотр профиля
    • http://www.microcat.ru
libmcrypt-помгите новичку плиз :(
« Ответ #1 : 14 Апреля 2006, 21:37:19 »
продолжение


if (isset($_POST[\'submit\'])) {

$check_plain_text = md5(rtrim ($poststring));
$check_decoded_text = md5(rtrim(my_decrypt (my_encrypt($poststring, $_POST[\'cikey\'], $algorithms[$_GET[\'uid\']],$_POST[\'mode\'], $_POST[\'rand\']), $_POST[\'cikey\'],$algorithms[$_GET[\'uid\']],$_POST[\'mode\'])));
(bool) $checksum = ($check_plain_text == $check_decoded_text)?1:0;
$html.= "<div align=\\"center\\" class=\\"white\\">Контрольная сумма и общие данные</div>";
$html.= "<table align=\\"left\\" cellpadding=\\"1\\" cellspacing=\\"2\\" border=\\"0\\" width=\\"540\\"><tr>";
$html.= "<td colspan=\\"2\\" class=\\"greytable\\" align=\\"center\\"><b>Контрольная сумма</b></td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Контрольная сумма MD5 исходных данных </td><td class=\\"greylight\\" align=\\"center\\">".$check_plain_text."</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Контрольная сумма MD5 после дешифрации </td><td class=\\"greylight\\" align=\\"center\\">".$check_decoded_text."</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Результат сверки контрольных сумм</td>".(($checksum)?"<td class=\\"greentable\\" align=\\"center\\">Возвращенные данные после дешифрации идентичны оригинальным":"<td class=\\"redtable\\" align=\\"center\\">Исходные данные после дешифрации не совпадают с оригинальными")."</td></tr><tr>";
$html.= "<td colspan=\\"2\\" class=\\"greytable\\" align=\\"center\\"><b>Общие сведения об использованном методе шифрования данных</b></td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Используемый алгоритм библиотеки LIBMCRYPT</td><td class=\\"greylight\\" align=\\"center\\"><b>MCRYPT_".strtoupper ($algorithms[$_GET[\'uid\']])."</b>
".$comments[$algorithms[$_GET[\'uid\']]]."</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Используемый режим шифрования</td><td class=\\"greylight\\" align=\\"center\\"><b>MCRYPT_MODE_".strtoupper ($_POST[\'mode\'])."</b>
".$comments[$_POST[\'mode\']]."</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Псевдоустройство случайности</td><td class=\\"greylight\\" align=\\"center\\"><b>".$_POST[\'rand\']."</b>
".$comments[$_POST[\'rand\']]."</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Автоматически сгенерированный 40-разрядный SHA1-хэш ключа</td><td class=\\"greylight\\" align=\\"center\\">".wordwrap ($_POST[\'cikey\'], 40, \'
\',1)."</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Размер ключа (берется максимальный)</td><td class=\\"greylight\\" align=\\"center\\">".mcrypt_get_key_size($algorithms[$_GET[\'uid\']], $_POST[\'mode\'])." Bytes</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Размер блока</td>".((mcrypt_module_is_block_algorithm ($algorithms[$_GET[\'uid\']]))?"<td class=\\"greylight\\" align=\\"center\\">".mcrypt_module_get_algo_block_size($algorithms[$_GET[\'uid\']])." Bytes":"<td class=\\"redtable\\" align=\\"center\\">Является потоковым алгоритмом, блоки не использует")."</td></tr><tr>";
$html.= "<td class=\\"greytable\\" width=\\"300\\">Размер вектора инициализации</td>".((mcrypt_get_iv_size ($algorithms[$_GET[\'uid\']], $_POST[\'mode\'])!=0)?"<td class=\\"greylight\\" align=\\"center\\">".mcrypt_get_iv_size($algorithms[$_GET[\'uid\']], $_POST[\'mode\'])." Bytes":"<td class=\\"redtable\\" align=\\"center\\">В данном режиме вектор инициализации не используется")."</td></tr>";
$html.= "</table>";
}
return $html;
}

function alg () {
global $algorithms, $disable_select, $poststring;
$html.= "<form action=\\"{$_SERVER[\'REQUEST_URI\']}\\" method=\\"POST\\">
<fieldset class=\\"fieldcrypt\\"><legend align=\\"left\\">Алгоритм</legend>
<select value=\\"treat\\" style=\\"width:150px;\\" name=\\"algorithm\\" size=\\"".count ($algorithms)."\\" onchange=\\"javascript: window.location.href=this.options[this.selectedIndex].value\\" ".$disable_select.">";
foreach ($algorithms as $algo_key=>$algo_name) {
$html.= "<option value=\\"/?sid=3&uid=".$algo_key."\\" ".(($algo_key == $_GET[\'uid\'])?\'selected\':NULL).">".strtoupper ($algo_name); }
$html.= "</select></fieldset>";
return $html;
}

function alkey () {
global $value_text, $poststring;
$html = "<fieldset class=\\"fieldcrypt\\"><legend align=\\"left\\">Генерация произвольного 40-разрядного SHA1-хэша ключа</legend>
<input type=\\"text\\" name=\\"cikey\\" style=\\"width: 355px;\\" value=\\"".$value_text."\\" readonly></fieldset>";
return $html;
}

function mod () {
global $option_modes, $disable_form, $poststring;
$html = "
<fieldset class=\\"fieldcrypt\\"><legend align=\\"left\\">Режим шифрования</legend>
<select name=\\"mode\\" ".$disable_form." style=\\"width:170px;\\">".$option_modes."</select></fieldset>";
return $html;

}

function ran () {
global $option_random, $disable_form, $poststring;
$html = "
<fieldset class=\\"fieldcrypt\\"><legend align=\\"left\\">Источник случайности</legend>
<select name=\\"rand\\" ".$disable_form." style=\\"width:165px;\\">".$option_random."</select></fieldset>";
return $html;
}

function text () {
global $disable_form, $poststring;
$html = "
<fieldset class=\\"fieldcrypt\\"><legend align=\\"left\\">Исходные данные</legend>
<textarea rows=\\"6\\" style=\\"width:355px;\\" name=\\"string\\" ".$disable_form.">".((!empty($poststring))?$poststring:"")."</textarea></fieldset>";
return $html;
}

function enc () {
global $algorithms, $poststring;
$html = "
<fieldset class=\\"fieldcrypt\\"><legend align=\\"left\\">Зашифрованные данные</legend>
<textarea rows=\\"6\\" style=\\"width:355px;\\" name=\\"encode\\" readonly>";
if (isset($_POST[\'submit\'])) {
$html.= my_encrypt($poststring, $_POST[\'cikey\'], $algorithms[$_GET[\'uid\']],$_POST[\'mode\'], $_POST[\'rand\']);
}
$html .= "</textarea></fieldset>";
return $html;
}

function sub () {
global $disable_form, $poststring;
$html = "
<input type=\\"submit\\" class=\\"baton\\" name=\\"submit\\" value=\\"Зашифровать данные\\"".$disable_form.">";
return $html;
}

function red () {
global $disable_form, $poststring;
$html = "
<input type=\\"button\\" class=\\"baton\\" value=\\"Выбор нового алгоритма\\" onclick=\\"javascript: window.location.href = \'/?sid=3\'\\"".$disable_form.">";
return $html;
}


function show () {
$html = "<div align=\\"center\\" class=\\"white\\">Здесь можно что-нибудь зашифровать</div>";
$html.= "
<table cellspacing=\\"0\\" cellpadding=\\"2\\" border=\\"0\\" width=\\"500\\" align=\\"center\\">
<tr>
    <td rowspan=\\"4\\" valign=\\"top\\">".alg()."</td>
    <td colspan=\\"2\\">".alkey()."</td>
</tr>
<tr>
    <td>".mod()."</td>
    <td>".ran()."</td>
</tr>
<tr>
    <td colspan=\\"2\\">".text()."</td>
</tr>
<tr>
    <td colspan=\\"2\\">".enc()."</td>
</tr>
<tr>
    <td colspan=\\"3\\" align=\\"center\\">

".sub()."          ".red()."</td>
   
</tr>
</table>";

return $html;
}


Оффлайн reLax[0x00]

  • Завсегдатай
  • Пользователь
  • **
  • Сообщений: 68
  • +0/-0
  • 0
    • Просмотр профиля
    • http://www.microcat.ru
libmcrypt-помгите новичку плиз :(
« Ответ #2 : 14 Апреля 2006, 21:38:57 »
продолжение



function mcrypt_test_module_mode($module,$mode) {
 global 
$algorithms$modes;
 
$key = \'this is a very long key, even too long for the cipher\';
 $plain_text = \'very important data\';
 $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_DEV_URANDOM); 
if (mcrypt_generic_init($td, $key, $iv) != -1) 
    { 
 $c_t = mcrypt_generic($td, $plain_text);
 mcrypt_generic_deinit($td);
 mcrypt_module_close($td);
 $td = mcrypt_module_open($module, \'\', $mode, \'\');
 $key = substr($key, 0, mcrypt_enc_get_key_size($td));
 mcrypt_generic_init($td, $key, $iv);
 $p_t = trim(mdecrypt_generic($td, $c_t)); 
 mcrypt_generic_end($td);
 mcrypt_module_close($td);
 }
 
 if (strncmp($p_t, $plain_text, strlen($plain_text)) == 0) 
     {
   return true;
 } else {
   return false;
     }
 }

function my_encrypt($string,$key,$algo,$mode,$rand) {
  srand((double) microtime() * 1000000); 
  
  $td = mcrypt_module_open($algo, \'\',$mode, \'\');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
 if ($iv_size!=0) 
    {
  $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM); 
    }
     if (mcrypt_generic_init($td, $key, $iv) != -1) 
	
  {
     $c_t = mcrypt_generic($td, $string);
     mcrypt_generic_deinit($td);
     mcrypt_module_close($td);
       $c_t = $iv.$c_t;
       return $c_t;
   } 
}

function my_decrypt($string,$key,$algo,$mode) {
 
  $td = mcrypt_module_open($algo, \'\',$mode, \'\');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
    if ($iv_size!=0):
  $iv = substr($string,0,$iv_size);
    endif;

  $string = substr($string,$iv_size);
    if (mcrypt_generic_init($td, $key, $iv) != -1): 
  $c_t = mdecrypt_generic($td, $string);
  mcrypt_generic_deinit($td);
  mcrypt_module_close($td);
       return $c_t;
    endif; 
}

echo table (@mcrypt_check_sanity().spacer().show().spacer().checksum());


Оффлайн CGVictor

  • теперь местный
  • Глобальный модератор
  • Ветеран
  • *****
  • Сообщений: 2511
  • +0/-0
  • 2
    • Просмотр профиля
    • http://cg.net.ru
libmcrypt-помгите новичку плиз :(
« Ответ #3 : 15 Апреля 2006, 12:21:21 »
[moderatorial]
Разбираешь код на алгоритм, убираешь из него всё лишнее (html в первую очередь), оставляешь объем примерно страницы и создаешь новую тему. Описываешь, что на входе, что должно получиться и что должно происходить. Словами.
Тема закрыта.
LJ: Backslashed life (rss)

 

Sitemap 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28