Classe de chiffrement de donnés avec mcrypt

Contenu du snippet

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 / Exemple :


<?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 ^^

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.