XOR加密--PHP版

来源:互联网 发布:淘宝怎么更改支付宝 编辑:程序博客网 时间:2024/05/18 07:44

关于XOR加密的概念可以参考 阮一峰老师的博客:http://www.ruanyifeng.com/blog/2017/05/xor.html



下面给出代码实例


<?phpclass XorEncrypt{private static $key = 'XorEncryptKey';private static $randomStrLen = 3;public static function encrypt($message,$key = ''){$key =  $key == '' ? self::$key : $key;$messageLen = strlen($message);$cipherText = '';$keyLen = strlen($key);for($i=0;$i<=$messageLen;$i+=$keyLen){$cipherText .= substr($message,$i,$keyLen) ^ $key;}//加入随机字符$randomStr = self::generateRandomStr();return base64_encode($randomStr.$cipherText);}public static function decrypt($cipherText,$key= ''){$key = $key == '' ? self::$key : $key;$cipherText = substr(base64_decode($cipherText),self::$randomStrLen);$cipherTextLen = strlen($cipherText);$message = '';$keyLen = strlen($key);for($i=0;$i<=$cipherTextLen;$i+=$keyLen){$message .= substr($cipherText,$i,$keyLen) ^ $key;}return $message;}private static function generateRandomStr(){$randomStr = '';for($i=1;$i<=self::$randomStrLen;$i++){$randomStr .= chr(mt_rand(33, 126));}return $randomStr;}}$message = "加密字符串";$cipherText = XorEncrypt::encrypt($message);echo "加密后:".$cipherText.PHP_EOL;$message = XorEncrypt::decrypt($cipherText);echo "加密后:".$message.PHP_EOL;

需要注意的是 做XOR运算时,两个字符串需长度相等,否则会截断过长的部分。

即:key的长度大于等于message。


原创粉丝点击