add new class SeedDMS_CSRF for creating time base tokens (currently not used)

This commit is contained in:
Uwe Steinmann 2019-07-12 16:40:38 +02:00
parent c5e6131c14
commit e79e9de1cf

View File

@ -480,21 +480,35 @@ function checkQuota($user) { /* {{{ */
return ($quota - $user->getUsedDiskSpace());
} /* }}} */
function encryptData($key, $value){
/**
* Encrypt any data with a key
*
* @param string $key
* @param string $value plain text data
* @return string encrypted data
*/
function encryptData($key, $value) { /* {{{ */
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
return $crypttext;
}
} /* }}} */
function decryptData($key, $value){
/**
* Decrypt data previously encrypted by encrypt
*
* @param string $key
* @param string $value encrypted data
* @return string plain text data
*/
function decryptData($key, $value) { /* {{{ */
$crypttext = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
} /* }}} */
/**
* Return file extension for a give mimetype
@ -574,4 +588,56 @@ function sendFile($filename) { /* {{{ */
readfile($filename);
}
} /* }}} */
class SeedDMS_CSRF {
protected $secret;
public function __construct($secret) {
$this->secret = $secret;
}
public function create_api_key() {
return base64_encode($this->encrypt(time().'|'.$_SERVER['REMOTE_ADDR'])); // !change if you dont want IP check
}
public function check_api_key($key, $timeout = 5) {
if (empty($key)) exit('Invalid Key');
$keys = explode('|', $this->decrypt(base64_decode($key)));
return (
isset($key, $keys[0], $keys[1]) &&
$keys[0] >= (time() - $timeout) &&
$keys[1] == $_SERVER['REMOTE_ADDR'] // !change if you dont want IP check
);
}
public function encrypt($string, $key = 'PrivateKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $this->secret), 0, 16);
// encrypt
$output = openssl_encrypt($string, $method, $key, 0, $iv);
// encode
return base64_encode($output);
}
public function decrypt($string, $key = 'PrivateKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $this->secret), 0, 16);
// decode
$string = base64_decode($string);
// decrypt
return openssl_decrypt($string, $method, $key, 0, $iv);
}
}
//$CSRF = new SeedDMS_CSRF($settings->_encryptionKey);
//$kkk = $CSRF->create_api_key();
//echo $kkk;
//echo $CSRF->check_api_key($kkk) ? 'valid' : 'invalid';
?>