60 lines
2.4 KiB
PHP
60 lines
2.4 KiB
PHP
<?php # NCC # Encryption toolkit
|
|
|
|
final class NCC extends Protector {
|
|
const CRYPT_METHOD_CIPHER = 'aes-256-ctr';
|
|
const CRYPT_METHOD_DIGEST = 'md5';
|
|
const CRYPT_RAW_DATA = null;#OPENSSL_RAW_DATA;
|
|
const CRYPT_SEED = ',343K^bEqxFYL!%uEMK-№hf+}m4444y3';
|
|
|
|
static function encrypt($m,$k=null,$iv=null){
|
|
if($iv===null) $iv = static::num(16);
|
|
if($k===null) $k = static::CRYPT_SEED;
|
|
return openssl_encrypt($m,static::CRYPT_METHOD_CIPHER,openssl_digest($k,static::CRYPT_METHOD_DIGEST,true),static::CRYPT_RAW_DATA,$iv);
|
|
}
|
|
static function decrypt($m,$k=null,$iv=null){
|
|
if($iv===null) return false;
|
|
if($k===null) $k = static::CRYPT_SEED;
|
|
return openssl_decrypt($m,static::CRYPT_METHOD_CIPHER,openssl_digest($k,static::CRYPT_METHOD_DIGEST,true),static::CRYPT_RAW_DATA,$iv);
|
|
}
|
|
static function match($p,$h){ return (crypt($p,$h)==$h); }
|
|
static function num($x){
|
|
if(function_exists('mcrypt_create_iv')) return mcrypt_create_iv($x,MCRYPT_DEV_URANDOM);
|
|
return openssl_random_pseudo_bytes($x);
|
|
}
|
|
static function hash($p,$f=9){
|
|
$salt=substr(strtr(base64_encode(static::num(17)),'+','/'),0,22);
|
|
$param='$'.implode('$',array("2y",str_pad($f,2,"0",STR_PAD_LEFT),$salt));
|
|
$final=crypt($p,$param);
|
|
if(mb_strlen($final)>13) return $final;
|
|
return false;
|
|
}
|
|
static function hmac_sign($m,$k){ return hash_hmac('sha256',$m,$k).$m; }
|
|
static function hmac_verify($b,$k){ return hash_equals(hash_hmac('sha256',mb_substr($b,64,null,'8bit'),$k),mb_substr($b,0,64,'8bit')); }
|
|
static function token_patch(){ return bin2hex(static::num(32)); }
|
|
static function token_match($s,$p){ return hash_equals($s,$p); }
|
|
static function token($secret,$verify=false){
|
|
if(empty(X::$sign)) return false;
|
|
$real = crypt($secret, X::$sign);
|
|
if($verify) return hash_equals($real,$verify);
|
|
return $real;
|
|
}
|
|
static function noise_add($data,$key){
|
|
$key = static::hash($key); $str = '';
|
|
for($i=0,$j=0,$ld=strlen($data),$lk=strlen($key); $i<$ld; ++$i,++$j){
|
|
if ($j>=$lk) $j=0;
|
|
$str.=chr((ord($data[$i])+ord($key[$j]))%256);
|
|
}
|
|
return $str;
|
|
}
|
|
static function noise_rem($data,$key){
|
|
$key = static::hash($key); $str = '';
|
|
for($i=0,$j=0,$ld=strlen($data),$lk=strlen($key); $i<$ld; ++$i,++$j){
|
|
if($j>=$lk) $j=0;
|
|
$temp=ord($data[$i])-ord($key[$j]);
|
|
if($temp<0) $temp+=256;
|
|
$str.=chr($temp);
|
|
}
|
|
return $str;
|
|
}
|
|
static function rstr($len){ return bin2hex(random_bytes(abs(intval($len)))); }
|
|
} |