begin process at 2012 05 27 22:13:20
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Sécurité & Cryptage

 > CLASSE DE CHIFFREMENT DE DONNÉS AVEC MCRYPT

CLASSE DE CHIFFREMENT DE DONNÉS AVEC MCRYPT


 Information sur la source

Note :
7 / 10 - par 1 personne
7,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10
Catégorie :Sécurité & Cryptage Classé sous :mcrypt, chiffrement, rijndael Niveau :Initié Date de création :04/07/2010 Date de mise à jour :02/12/2010 13:36:19 Vu :2 370

Auteur : TychoBrahe

Ecrire un message privé
Commentaire sur cette source (2)
Ajouter un commentaire et/ou une note

 Description

Une classe simple permettant une utilisation simple de l'extension mcrypt. Lors de l'instantiation on passe la clé au constructeur, il ne reste alors qu'à utiliser les méthodes crypt() et decrypt() pour respectivement chiffrer et déchiffrer les données. Afin d'améliorer la lisibilité et une utilisation plus pratique, les donnés chiffrées sont encodées en base 64.

Un exemple simple :
$key = 'su63jala][w !juTU42';
$Plop = new MyCrypt($key); // Attention, il est obligatoire de passer une variable (argument passé par référence) ! Cette clé sera détruite automatiquement.
$data = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit';
$cr = $Plop->crypt($data); // idem
var_dump($cr);
var_dump($Plop->decrypt($cr));

Pour ceux qui connaissent l'autre classe sur ce sujet déjà existante, je poste la mienne pour les raisons suivantes :
- Utilisation de PHP 5 au lieux de PHP 4 dans l'autre.
- Utilisation des exception au lieux de trigger_error, permettant ainsi de mieux s'intégrer dans un environnement objet.
- Utilisation d'un destructeur au lieux d'une méthode à appeler soi même.
- Utilisation base 64 au lieux de donnés binaires.
- Destruction de la clé de chiffrement et des données afin d'éviter qu'un dump de la mémoire en puisse la révéler (attaque par dl() et compagnie).

Source

  • <?php
  • // Copyright (c) 2010 Rodolphe Breard
  • //
  • // Permission to use, copy, modify, and/or distribute this software for any
  • // purpose with or without fee is hereby granted, provided that the above
  • // copyright notice and this permission notice appear in all copies.
  • //
  • // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  • // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  • // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  • // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  • // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  • // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  • // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  • //
  • class MyCrypt
  • {
  • protected $td;
  • protected $iv;
  • protected $key;
  • public function __construct(&$key)
  • {
  • $this->td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_ECB, '');
  • if ($this->td === false)
  • throw new Exception('MyCrypt::__construct: unable to open module');
  • $this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), MCRYPT_RAND);
  • if ($this->iv === false)
  • throw new Exception('MyCrypt::__construct: unable to create the initialization vector');
  • $this->key = substr(hash('sha512', $key, true), 0, mcrypt_enc_get_key_size($this->td));
  • $end = strlen($key);
  • for ($i = 0; $i < $end; $i++)
  • $key[$i] = "\0";
  • }
  • public function __destruct()
  • {
  • $this->bzero($this->key);
  • if (mcrypt_module_close($this->td) === false)
  • throw new Exception('MyCrypt::__destruct: unable to close module');
  • }
  • public function crypt(&$data)
  • {
  • return base64_encode($this->mcryptGeneric($data, 'mcrypt_generic'));
  • }
  • public function decrypt(&$data)
  • {
  • $tmp = base64_decode($data);
  • $this->bzero($data);
  • return $this->mcryptGeneric($tmp, 'mdecrypt_generic');
  • }
  • public function bzero(&$str)
  • {
  • $end = strlen($str);
  • for ($i = 0; $i < $end; $i++)
  • $str[$i] = "\0";
  • }
  • protected function mcryptGeneric(&$data, $func)
  • {
  • $ret = '';
  • try
  • {
  • $funcLst = array('mcrypt_generic', 'mdecrypt_generic');
  • if (!in_array($func, $funcLst))
  • throw new Exception("MyCrypt::mcryptGeneric: $func: unknown function");
  • $in = mcrypt_generic_init($this->td, $this->key, $this->iv);
  • if ($in === false)
  • throw new Exception('MyCrypt::mcryptGeneric: init: incorrect parameters');
  • elseif ($in == -3)
  • throw new Exception('MyCrypt::mcryptGeneric: init: incorrect key length');
  • elseif ($in == -4)
  • throw new Exception('MyCrypt::mcryptGeneric: init: memory allocation problem');
  • elseif ($in < 0)
  • throw new Exception('MyCrypt::mcryptGeneric: init: unknown error');
  • $ret = $func($this->td, $data);
  • if (mcrypt_generic_deinit($this->td) === false)
  • throw new Exception('MyCrypt::mcryptGeneric: unable to deinit');
  • }
  • catch (Exception $e)
  • {
  • $this->bzero($data);
  • throw $e;
  • }
  • $this->bzero($data);
  • return $ret;
  • }
  • }
  • ?>
<?php
// Copyright (c) 2010 Rodolphe Breard
// 
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
// 
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

class			MyCrypt
{
  protected		$td;
  protected		$iv;
  protected		$key;

  public function	__construct(&$key)
  {
    $this->td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_ECB, '');
    if ($this->td === false)
      throw new Exception('MyCrypt::__construct: unable to open module');
    $this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), MCRYPT_RAND);
    if ($this->iv === false)
      throw new Exception('MyCrypt::__construct: unable to create the initialization vector');
    $this->key = substr(hash('sha512', $key, true), 0, mcrypt_enc_get_key_size($this->td));
    $end = strlen($key);
    for ($i = 0; $i < $end; $i++)
      $key[$i] = "\0";
  }

  public function	__destruct()
  {
    $this->bzero($this->key);
    if (mcrypt_module_close($this->td) === false)
      throw new Exception('MyCrypt::__destruct: unable to close module');
  }

  public function	crypt(&$data)
  {
    return base64_encode($this->mcryptGeneric($data, 'mcrypt_generic'));
  }

  public function	decrypt(&$data)
  {
    $tmp = base64_decode($data);
    $this->bzero($data);
    return $this->mcryptGeneric($tmp, 'mdecrypt_generic');
  }

  public function	bzero(&$str)
  {
    $end = strlen($str);
    for ($i = 0; $i < $end; $i++)
      $str[$i] = "\0";
  }

  protected function	mcryptGeneric(&$data, $func)
  {
    $ret = '';
    try
      {
	$funcLst = array('mcrypt_generic', 'mdecrypt_generic');
	if (!in_array($func, $funcLst))
	  throw new Exception("MyCrypt::mcryptGeneric: $func: unknown function");
	$in = mcrypt_generic_init($this->td, $this->key, $this->iv);
	if ($in === false)
	  throw new Exception('MyCrypt::mcryptGeneric: init: incorrect parameters');
	elseif ($in == -3)
	  throw new Exception('MyCrypt::mcryptGeneric: init: incorrect key length');
	elseif ($in == -4)
	  throw new Exception('MyCrypt::mcryptGeneric: init: memory allocation problem');
	elseif ($in < 0)
	  throw new Exception('MyCrypt::mcryptGeneric: init: unknown error');
	$ret = $func($this->td, $data);
	if (mcrypt_generic_deinit($this->td) === false)
	  throw new Exception('MyCrypt::mcryptGeneric: unable to deinit');
      } 
    catch (Exception $e)
      {
	$this->bzero($data);
	throw $e;
      }
    $this->bzero($data);
    return $ret;
  }
}

?>

 Conclusion

En espérant que ça serve ^^


 Historique

20 juillet 2010 11:54:06 :
Protection de la clé de chiffrement contre les attaques par dl() et assimilés (sur un serveur mutualisé ou du genre, dump de la mémoire pour récupérer la clé de chiffrement).
02 décembre 2010 13:27:11 :
Destruction des données en plus de la clé. Modification de la licence.
02 décembre 2010 13:36:19 :
petit oubli

 Sources du même auteur

CURRYFICATION DE FONCTIONS
DÉTECTEUR DE VULNERABILITY SCANNER
Source avec Zip GÉNÉRATEUR DE MAKEFILE

 Sources de la même categorie

Source avec Zip Source avec une capture CAPTCHA AJAX ANTI-BOT par darkvador59
Source avec Zip Source avec une capture ACCÈS, ESPACE MEMBRE AVEC INSCRIPTION ET DÉSINSCRIPTION PAR ... par stephelle
Source avec Zip CRYPTAGE REVERSIBLE par Mokost
Source avec Zip Source avec une capture CREATION DE COMPTE AVEC CRYPTAGE ET ESPACE DE CONNEXION SEC... par bm1982
PROTÉGEZ VOS LIENS DE TÉLÉCHARGEMENT PAR MOT DE PASSE ET/OU ... par unlien

 Sources en rapport avec celle ci

CRYPTAGE/DECRYPTAGE MCRYPT par sephirothgeek
CHIFFRE DE CESAR par jean84
CHIFFRE DE VIGENÈRE par franco_se

Commentaires et avis

Commentaire de phpAnonyme le 16/12/2010 15:20:00

Slt,

Ca m'a l'air pas mal ! Dommage que tu limite l'utilisation à un seul mode de chiffrement et à un seul chiffrement.

Commentaire de hornetbzz le 08/11/2011 09:05:20 7/10

Slt,

Je n'ai pas testé mais en ts cas, beau code et oui, c'est utile.

J'attire juste l'attention des utilisateurs éventuels sur les risques de ralentissements éventuels de la réponse du serveur avec ce type de fonctions très consommatrices de ressources (utilisation de libmcrypt). Un petit benchmark aurait été intéressant.

Quasiment la même chose en 2 lignes, testé avec une réponse rapide du serveur, juste en utilisant la doc (donc moins élaborée que la classe proposée) :
class Cipher {

private $securekey, $iv;
public $_serialized;
protected $_ciphered = array();

/**
* Class constructor
* @param string type $textkey
*/
function __construct($textkey) {

// Create the cipher object
$this->securekey = hash('sha256', $textkey, TRUE);
$this->iv = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);

}
/**
* Encrypt
* @param string|object $input
* @return string
*/
public function encrypt($input) {
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->securekey, $input, MCRYPT_MODE_ECB, $this->iv));
}

/**
* Decrypt
* @param string|object $input
* @return string
*/
public function decrypt($input) {
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->securekey, base64_decode($input), MCRYPT_MODE_ECB, $this->iv));
}
} /* end of Cipher class */

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

cryptage et décryptage mcrypt [ par titinoos ] Bonjour,Je suis un peu nouveau dans ce qui est de la cryptographie et je voudrais crypter d&#233;crypter un fichier txtj'essai d&#233;ja avec une phra Compatibilité des algos de Cryptages [ par Manu94600 ] Salut à tous,Je débute dans ce domaine et j'ai fait une fonction qui crypte des données et une autre qui décrypte les données. J'utilise l'algo MCRYPT Nombre de combinaisons possibles avec l'algo MCRYPT_RIJNDAEL_256 [ par roymatthieu ] Bonjour... Question débile de fin d'après-midi... J'ai une fonction de chiffrement qui me permet de protéger certaines données sensibles... J'utili fonction mcrypt bug - Comment avoir un cryptage PHP réversible et sur? [ par zzzzzz ] Bonjour, J'ai trouvé 2 fonctions pour chiffrer du texte sur php.net (utilisant mcrypt) : function Crypter($str, $key) { # Add PKCS7 padding. mcrypt problème d'encodage [ par zzzzzz ] Bonjour à tous, J'utilise une fonction (trouvé sur le net) utilisant mcrypt : function Crypter($str, $key) { # Add PKCS7 padding. $block = mcrypt : Can not create an IV with a size of less then 1 or [ par zzzzzz ] Bonjour j'utilise 2 fonctions, une pour crypter, une pour decrypter. Pour être franc je n'y comprend pas grand chose... J'ai essayé dans un fichier fichier mcrypt [ par MAsterC ] Bonjour,J'essaie d'installer le module mcrypt à php mais quand je démarre mon apache, j'ai une erreur de php qui m'indique que le module "php_mcrypt.d cryptage et libmcrypt [ par metos ] Bonjour, j'aimerais utiliser du cryptage AES en php avec la fonction :  mcrypt_module_open. Lors du chargement de la page l'erreur suivante se produit tripleDES de php à java simplement [ par ymazal2 ] Hi, i need the equivalence of this code in java :function TripleDesDecryption($string, $key){$iv = false;// set mcrypt mode and cipher $td = mcrypt_mo compiler extension php sous mac OS et utiliser utiliser mcrypt [ par inaden ] Bonjour à tous,Je viens d'installer mysql et phpMyAdmin sur le sereur du mac (OS 10.5).Lorsque je me connecte sur phpMyAdmin j'ai le message d'erreur


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,671 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales