Espace membres

Bonjour Anonyme

Inscription

Email :
Mot de passe :

Mot de passe oublié ?

Nos scripts

MySpeach

MySpeach est un chat php sans base de donnée, rapide, léger et facile à prendre en main. DEMO

MyPHPUpload

MyPHPUpload est un script d'upload sécurisé écrit en PHP. DEMO

GrapAgenda

Agenda PHP et MySQL avec comptes utilisateurs et administration. DEMO

Livre PHP

création de site

Encrypter et décrypter une chaine avec MCRYPT en PHP

Portion de code ajouté par sky le 12-08-2010

Encrypter et décrypter en PHP des chaines de caractères avec TRIPLE DES et MCRYP utilisant un cipher CBC.

<?php
/*
 * CRYPT_CKEY et CRYPT_CIV sont à changer pour votre projet
 */


define('CRYPT_CKEY', '98qW5L4DnS11qYj98P5kL1P6');
define('CRYPT_CIV', 'HBq6Jl4q');
define('CRYPT_CBIT_CHECK', 32);


function encrypt($text)
{
    $text_num = str_split($text, CRYPT_CBIT_CHECK);
    $text_num = CRYPT_CBIT_CHECK - strlen($text_num[count($text_num)-1]);

    for ($i=0;$i<$text_num; $i++)
        $text = $text . chr($text_num);

    $cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
    mcrypt_generic_init($cipher, CRYPT_CKEY, CRYPT_CIV);
   
    $decrypted = mcrypt_generic($cipher, $text);
    mcrypt_generic_deinit($cipher);

    return base64_encode($decrypted);
}


function decrypt($encrypted_text)
{
    $cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
    mcrypt_generic_init($cipher, CRYPT_CKEY, CRYPT_CIV);
   
    $decrypted = mdecrypt_generic($cipher, base64_decode($encrypted_text));
    mcrypt_generic_deinit($cipher);
   
    $last_char = substr($decrypted,-1);

    for($i=0; $i<(CRYPT_CBIT_CHECK-1); $i++)
    {
        if(chr($i) == $last_char)
        {
            $decrypted = substr($decrypted, 0, strlen($decrypted)-$i);
            break;
        }
    }

    return $decrypted;
}
?>


Utilisation des fonctions :
<?php
// Encrypter une chaine
$chaine_crypte = encrypt('Une chaine à encrypter');
echo '<p>'.$chaine_crypte.'</p>';

// Décrypter la chaine
$chaine_decrypte = decrypt($chaine_crypte);
echo '<p>'.$chaine_decrypte.'</p>';
?>

Commentaires

Aucun commentaire. Soyez le premier !

Pseudo
Email
Commentaire

Merci d'écrire le code ici :