Форум АНТИЧАТ

Форум АНТИЧАТ (https://forum.antichat.xyz/index.php)
-   PHP, PERL, MySQL, JavaScript (https://forum.antichat.xyz/forumdisplay.php?f=37)
-   -   Нужен скрипт PHP на тему криптографии. (https://forum.antichat.xyz/showthread.php?t=103305)

Хелпер 27.01.2009 16:58

Нужен скрипт PHP на тему криптографии.
 
Мне вместо экзаменов можно сделать на эту тему скрипт, и я спасен от ЕГЭ. Буду плюсики кидать по КД или $$$. Договоримся.
Если за + то постим тут.
Если за $$$, то icq: 2425208

Kaimi 27.01.2009 17:08

Криптография однако:

print md5('preved');
print sha1('medved');

))

Хелпер 27.01.2009 17:22

Не серьезно относитесь(((

Chaak 27.01.2009 17:37

Погугли на тему библиотеки mcrypt - полезно

Kaimi 27.01.2009 17:42

Хочешь серьезный ответ - скажи какого плана скрипт ищешь

Root-access 27.01.2009 17:58

Можешь взять готовый скрипт какого-нибудь алгоритма шифрования (хоть того же md5) и подредактировать =))
Можно даже попросту прогу шифра Цезаря написать.. Или прогу для примитивного морфологического криптоанализа.

Хелпер 27.01.2009 20:02

Цитата:

Можешь взять готовый скрипт какого-нибудь алгоритма шифрования (хоть того же md5) и подредактировать =))
Можно даже попросту прогу шифра Цезаря написать.. Или прогу для примитивного морфологического криптоанализа.
Верно выразил мою мысль

Chaak 27.01.2009 20:22

Sha-1 на php
PHP код:

class CI_SHA {

    function 
CI_SHA()
    {
        
log_message('debug'"SHA1 Class Initialized");
    }

    
/**
     * Generate the Hash
     *
     * @access    public
     * @param    string
     * @return    string
     */    
    
function generate($str)
    {
        
$n = ((strlen($str) + 8) >> 6) + 1;

        for (
$i 0$i $n 16$i++)
        {
            
$x[$i] = 0;
        }

        for (
$i 0$i strlen($str); $i++)
        {
            
$x[$i >> 2] |= ord(substr($str$i1)) << (24 - ($i 4) * 8);
        }

        
$x[$i >> 2] |= 0x80 << (24 - ($i 4) * 8);

        
$x[$n 16 1] = strlen($str) * 8;

        
$a =  1732584193;
        
$b = -271733879;
        
$c = -1732584194;
        
$d =  271733878;
        
$e = -1009589776;

        for (
$i 0$i sizeof($x); $i += 16)
        {
            
$olda $a;
            
$oldb $b;
            
$oldc $c;
            
$oldd $d;
            
$olde $e;

            for(
$j 0$j 80$j++)
            {
                if (
$j 16)
                {
                    
$w[$j] = $x[$i $j];
                }
                else
                {
                    
$w[$j] = $this->_rol($w[$j 3] ^ $w[$j 8] ^ $w[$j 14] ^ $w[$j 16], 1);
                }

                
$t $this->_safe_add($this->_safe_add($this->_rol($a5), $this->_ft($j$b$c$d)), $this->_safe_add($this->_safe_add($e$w[$j]), $this->_kt($j)));

                
$e $d;
                
$d $c;
                
$c $this->_rol($b30);
                
$b $a;
                
$a $t;
            }

            
$a $this->_safe_add($a$olda);
            
$b $this->_safe_add($b$oldb);
            
$c $this->_safe_add($c$oldc);
            
$d $this->_safe_add($d$oldd);
            
$e $this->_safe_add($e$olde);
        }

        return 
$this->_hex($a).$this->_hex($b).$this->_hex($c).$this->_hex($d).$this->_hex($e);
    }
      
    
// --------------------------------------------------------------------

    /**
     * Convert a decimal to hex
     *
     * @access    private
     * @param    string
     * @return    string
     */    
    
function _hex($str)
    {
        
$str dechex($str);

        if (
strlen($str) == 7)
        {
            
$str '0'.$str;
        }

        return 
$str;
    }
      
    
// --------------------------------------------------------------------

    /**
     *  Return result based on iteration
     *
     * @access    private
     * @return    string
     */    
    
function _ft($t$b$c$d)
    {
        if (
$t 20)
            return (
$b $c) | ((~$b) & $d);
        if (
$t 40)
            return 
$b $c $d;
        if (
$t 60)
            return (
$b $c) | ($b $d) | ($c $d);

        return 
$b $c $d;
    }

    
// --------------------------------------------------------------------

    /**
     * Determine the additive constant
     *
     * @access    private
     * @return    string
     */    
    
function _kt($t)
    {
        if (
$t 20)
        {
            return 
1518500249;
        }
        else if (
$t 40)
        {
            return 
1859775393;
        }
        else if (
$t 60)
        {
            return -
1894007588;
        }
        else
        {
            return -
899497514;
        }
    }
      
    
// --------------------------------------------------------------------

    /**
     * Add integers, wrapping at 2^32
     *
     * @access    private
     * @return    string
     */    
    
function _safe_add($x$y)
    {
        
$lsw = ($x 0xFFFF) + ($y 0xFFFF);
        
$msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);

        return (
$msw << 16) | ($lsw 0xFFFF);
    }
      
    
// --------------------------------------------------------------------

    /**
     * Bitwise rotate a 32-bit number
     *
     * @access    private
     * @return    integer
     */    
    
function _rol($num$cnt)
    {
        return (
$num << $cnt) | $this->_zero_fill($num32 $cnt);
    }

    
// --------------------------------------------------------------------

    /**
     * Pad string with zero
     *
     * @access    private
     * @return    string
     */    
    
function _zero_fill($a$b)
    {
        
$bin decbin($a);

        if (
strlen($bin) < $b)
        {
            
$bin 0;
        }
        else
        {
            
$bin substr($bin0strlen($bin) - $b);
        }

        for (
$i=0$i $b$i++)
        {
            
$bin "0".$bin;
        }

        return 
bindec($bin);
    }


Copyright (c) 2008, EllisLab, Inc.

Хелпер 27.01.2009 20:48

а откуда он текст берят для шифрования???

Chaak 27.01.2009 21:08

PHP код:

$sha1 = new CI_SHA();
echo 
$sha1->generate('ояебу!'); 


Хелпер 28.01.2009 19:42

Мля, долго изучал. С трудом понял меньше половины.
Надо ченить проще, а то я объяснить не смогу.
Скрипт №1 берет текст из файла in.txt кодирует по алгаритму - любому. И сохраняет в файл out.txt
Скрипт №2 берет текст из файла out.txt декодирует и сохраняет в файл in.txt

Вроде все.

Чуть не забыл. Заплатить больше 200 рублей пока не могу.

nerezus 28.01.2009 19:47

Код:

def check_correct(string, alphabet):
    """Check string in alphabet"""
    for c in string:
        if c not in alphabet:
            raise "Wrong data: found wrong characters"
 
def code(char, alphabet):
    """Return number of character in alphabet"""
    return alphabet.find(char)

def shift_char(char1, char2, alphabet):
    """Shift character with the other one"""
    c = code(char1, alphabet) + code(char2, alphabet)
    if c > len(alphabet):
        c -= len(alphabet)
    return alphabet[c]
 
def unshift_char(char1, char2, alphabet):
    """Unshift character with the other one"""
    c1 = code(char1, alphabet)
    c2 = code(char2, alphabet)
    if c1 < c2:
        c1 += len(alphabet)
    c = c1 - c2
    return alphabet[c]
 
def encrypt(phrase, autokey, alphabet):
    """Encrypt data with autokey"""
    check_correct(phrase, alphabet)
    check_correct(autokey, alphabet)
    key = autokey + phrase
    encrypted = ""
    for i in range(len(phrase)):
        encrypted += shift_char(phrase[i], key[i], alphabet)
    return encrypted

def decrypt(encrypted, autokey, alphabet):
    """Decrypt data with autokey"""
    check_correct(encrypted, alphabet)
    check_correct(autokey, alphabet)
    key = autokey
    for i in range(len(encrypted)):
        key += unshift_char(encrypted[i], key[i], alphabet)
    return key[len(autokey):]


Автоключ на питоне

mailbrush 28.01.2009 23:41

Цитата:

Скрипт №1 берет текст из файла in.txt кодирует по алгаритму - любому. И сохраняет в файл out.txt
Скрипт №2 берет текст из файла out.txt декодирует и сохраняет в файл in.txt
Шя...

mailbrush 29.01.2009 00:54

PHP код:

<?
error_reporting
(0);
echo 
'<title>Encoder/Decoder</title>';
$do=$_GET['do'];
switch(
$do)
{
default:
echo 
'Выберите тип:';
echo 
'<form name="" action="" method="post">
<input name="type" type="radio" value="1" checked> Encode <br />
<input name="type" type="radio" value="2"> Decode   <br />
<input type="submit" value="Перейти">
</form>'
;
if (
$_POST['type']==1)
{
echo 
'<script>document.location="?do=encode"</script>';
}
if (
$_POST['type']==0)
{
echo 
'<script>document.location="?do=decode"</script>';
}
break;

case
"decode":
echo 
'<form action="" method="post">
Файл, который декодируем: <input name="in" type="" value=""> <br />
Файл, куда декодируем: <input name="out" type="" value="">   <br />
<input type="submit" value="Send">
</form>'
;
if (isset(
$_POST['in']))
{
    if (isset(
$_POST[out]))
{
$in=$_POST[in];
$out=$_POST[out];
$a=file_get_contents($in);
$r=base64_decode($a);
if (
file_put_contents($out$r))
echo 
'<b>Декодировано успешно!</b>';
}
}
break;

case
"encode":
echo 
'<form action="" method="post">
Файл, который кодируем: <input name="in" type="" value=""> <br />
Файл, куда кодируем: <input name="out" type="" value="">   <br />
<input type="submit" value="Send">
</form>'
;
if (isset(
$_POST['in']))
{
    if (isset(
$_POST[out]))
{
$in=$_POST[in];
$out=$_POST[out];
$a=file_get_contents($in);
$r=base64_encode($a);
if (
file_put_contents($out$r))
echo 
'<b>Закодировано успешно!</b>';
}
}
break;
}
?>

Просьба сильно не пинать, я в пхп новичек.

Хелпер 29.01.2009 11:30

СПС, но он не дает выбор Кодинг\декодинг. Он сам сразу выбирает декодинг.(
тобишь вот эта часть не работает.
PHP код:

echo 'Выберите тип:'
echo 
'<form name="" action="" method="post"> 
<input name="type" type="radio" value="1" checked> Encode <br /> 
<input name="type" type="radio" value="2"> Decode   <br /> 
<input type="submit" value="Перейти"> 
</form>'

if (
$_POST['type']==1

echo 
'<script>document.location="?do=encode"</script>'

if (
$_POST['type']==0

echo 
'<script>document.location="?do=decode"</script>'

break; 


eLWAux 29.01.2009 11:38

http://forum.xaknet.ru/thread8745.html

D1mka 29.01.2009 15:43

Реализация AES-128 на PHP с нуля

mailbrush 29.01.2009 16:55

Хелпер, сори, ошибся немного, вот:
PHP код:

<?
error_reporting
(0);
echo 
'<title>Encoder/Decoder</title>';
$do=$_GET['do'];
switch(
$do)
{
default:
echo 
'Выберите тип:';
echo 
'<form name="" action="" method="post">
<input name="type" type="radio" value="1" checked> Encode <br />
<input name="type" type="radio" value="2"> Decode   <br />
<input type="submit" value="Перейти">
</form>'
;
if (
$_POST['type']==1)
{
echo 
'<script>document.location="?do=encode"</script>';
}
if (
$_POST['type']==2)
{
echo 
'<script>document.location="?do=decode"</script>';
}
break;

case
"decode":
echo 
'<form action="" method="post">
Файл, который декодируем: <input name="in" type="" value=""> <br />
Файл, куда декодируем: <input name="out" type="" value="">   <br />
<input type="submit" value="Send">
</form>'
;
if (isset(
$_POST['in']))
{
    if (isset(
$_POST[out]))
{
$in=$_POST[in];
$out=$_POST[out];
$a=file_get_contents($in);
$r=base64_decode($a);
if (
file_put_contents($out$r))
echo 
'<b>Декодировано успешно!</b>';
}
}
break;

case
"encode":
echo 
'<form action="" method="post">
Файл, который кодируем: <input name="in" type="" value=""> <br />
Файл, куда кодируем: <input name="out" type="" value="">   <br />
<input type="submit" value="Send">
</form>'
;
if (isset(
$_POST['in']))
{
    if (isset(
$_POST[out]))
{
$in=$_POST[in];
$out=$_POST[out];
$a=file_get_contents($in);
$r=base64_encode($a);
if (
file_put_contents($out$r))
echo 
'<b>Закодировано успешно!</b>';
}
}
break;
}
?>


Хелпер 30.01.2009 20:45

Спасибо огромное

mailbrush 30.01.2009 23:29

Да незачто, сори за большую длину, в пхп тока начал кодить, кстати, если хочешь, к скрипту прилеплю чтобы енкодил/декодил текст который напишешь.

Хелпер 31.01.2009 10:10

Сам добавлю.

mailbrush 31.01.2009 10:45

ОК, я просто думал раз ты не знаешь как вывести содержимое файла, то и не знаешь как текстареу забацать, но, видать, ошибся...


Время: 19:27