Skip to content

Instantly share code, notes, and snippets.

@MASA-P
Created November 19, 2010 12:17
Show Gist options
  • Save MASA-P/706444 to your computer and use it in GitHub Desktop.
Save MASA-P/706444 to your computer and use it in GitHub Desktop.
Secure serialize / unserialize Library
<?php
/**
* PHP versions 4 and 5
*
* Secure serialize / unserialize Library
* Copyright 2010, Masaharu Takishita(ECWorks)
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010, ECWorks.
* @link http://blog.ecworks.jp/ ECWorks blog.
* @version 1.0.0
* @lastmodified $Date: 2010-11-19 21:00:00 +0900 (Fri, 19 Nov 2010) $
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* Generates HMAC hash string
*
* @param string $algo The name of algoritum for generating the hash code of HMAC. Choose "sha1" or "md5".
* @param mixed $data The data for generating the hash code of HMAC.
* @param string $key The secret key of HMAC.
* @param string $raw_output If you need raw hash code, this is true.
* @return string HMAC hash code from $data and $key.
*/
if (!function_exists('hash_hmac')) {
function hash_hmac($algo, $data, $key, $raw_output = false) {
$algo_list = array('sha1', 'md5');
$algo = strtolower($algo);
if (!in_array($algo, $algo_list)) return false;
if (!is_string($key)) $key = strval($key);
$key1 = $key2 = array();
for ($i = 0; $i < 64;$i++) {
$key1[] = chr(ord($key{$i}) ^ 0x36);
$key2[] = chr(ord($key{$i}) ^ 0x5c);
}
$key1[] = $data;
$key = implode('', $key1);
$hmac = call_user_func($algo, $key, true);
$key2[] = $hmac;
$key = implode('', $key2);
$hmac = call_user_func($algo, $key, $raw_output);
return $hmac;
}
}
/**
* Secure serialize / unserialize class.
*
*/
class Serializer {
/**
* Secure serializing.
*
* @param mixed $data The data for serializing.
* @param string $key The secret key of HMAC.
* @param string $algo The name of algoritum for generatingg the hash code of HMAC.
* @return string Serialized string with HMAC hash code, or false if hash_hmac() is failture.
*/
function serialize($data, $key, $algo = 'sha1'){
$str = serialize($data);
$hash = hash_hmac($algo, $str, $key);
return $hash !== false ? $hash.'|'.$str : false;
}
/**
* Secure unserializing.
*
* @param mixed $str Secure serialized data from Serializer::serialize().
* @param string $key The secret key of HMAC.
* @param string $algo The name of algoritum for generatingg the hash code of HMAC.
* @return mixed Unserialized data, or false if the generated hash and the including hash are different.
*/
function unserialize($str, $key, $algo = 'sha1'){
list($hash, $str) = explode('|', $str, 2);
$hash_confirm = hash_hmac($algo, $str, $key);
return $hash === $hash_confirm ? unserialize($str) : false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment