<?php
/**
* Generic Encryption Class
*
* @version 1.0
* @author Martijn Bogaard
* @copyright 2009 Perfect Networks
**/
class Encryption {
private static $_secretKey =
'Eg/ObjSwroO{fUIrkE1rIFit]RosbUCu1wIngiApT#iO~BedOpeO9agOLuPat#UobN>RifEioN3SlAxbUi#I';
//This is the secret key. Randomize it for every application you use this class. Use at least a 100 character key.
private static $_encryptPrefix =
'$:';
private static $_encryptSuffix =
'$';
private static $_saltLength =
3;
public static function isEncrypted
($str) {
if (substr($str,
0,
strlen(self::
$_encryptPrefix)) == self::
$_encryptPrefix &&
substr($str,
0,
strlen(self::
$_encryptSuffix)) == self::
$_encryptSuffix) {
$encryptedData =
substr($str,
strlen(self::
$_encryptPrefix),
0 -
strlen(self::
$_encryptSuffix));
list($data,
$checksum,
$salt) =
explode(':',
$encryptedData);
return true;
}
}
}
return false;
}
public static function encryptData
($data,
$publicKey) {
$salt = self::generateSalt();
$encryptionKey = self::getEncryptionKey($publicKey, $salt);
$encryptedData = self::
crypt($gzippedData,
$encryptionKey);
//encrypt
$hexData =
bin2hex($encryptedData);
//bin2hex
$checksum =
substr(sha1($hexData),
0,
8);
//checksum
return self::$_encryptPrefix . $hexData . ':' . $checksum . ':' . $salt . self::$_encryptSuffix;
}
public static function decryptData
($data,
$publicKey) {
if (self::isEncrypted($data)) {
$encryptionKey = self::getEncryptionKey($publicKey, $salt);
$encryptedData =
pack('H*',
$data);
//hex2bin
$gzippedData = self::
crypt($encryptedData,
$encryptionKey);
//decrypt
}
}
return false;
}
private static function getEncryptionKey
($publicKey,
$salt) {
$newKey = self::
crypt(self::
$_secretKey,
$publicKey);
//first we encode the private key with the public key
return self::
crypt($newKey,
$salt);
//and then we encode the key with the salt
}
private static function generateSalt
() {
for($i = 0, $salt = ''; $i < self::$_saltLength; $i++) {
}
return $salt;
}
$strPos = 0;
$tokenPos = 0;
while ($strPos <
strlen($data)) {
$data{$strPos} = $data{$strPos} ^ $key{$tokenPos};
$strPos++;
$tokenPos++;
if ($tokenPos >=
strlen($key))
$tokenPos = 0;
}
return $data;
}
}
Encryption::encryptData('test1ioewijoiojew', 'een key'),
Encryption::decryptData(Encryption::encryptData('test1ioewijoiojew', 'een key'), 'een key'),
Encryption::isEncrypted(Encryption::encryptData('test1ioewijoiojew', 'een key'))
);