php 使用异或(XOR)加密/解密文件

来源:互联网 发布:archlinux 解压软件 编辑:程序博客网 时间:2024/05/12 20:47

php 使用异或(XOR)加密/解密文件

原理:将文件每一个字节与key作位异或运算(XOR),解密则再执行一次异或运算。


代码如下:

<?php$source = 'test.jpg';$encrypt_file = 'test_enc.jpg';$decrypt_file = 'test_dec.jpg';$key = 'D89475D32EA8BBE933DBD299599EEA3E';echo '<p>source:</p>';echo '<img src="'.$source.'" width="200">';echo '<hr>';file_encrypt($source, $encrypt_file, $key); // encryptecho '<p>encrypt file:</p>';echo '<img src="'.$encrypt_file.'" width="200">';echo '<hr>';file_encrypt($encrypt_file, $decrypt_file, $key); // decryptecho '<p>decrypt file:</p>';echo '<img src="'.$decrypt_file.'" width="200">';/** 文件加密,使用key与原文异或生成密文,解密则再执行一次异或即可* @param String $source 要加密或解密的文件* @param String $dest   加密或解密后的文件* @param String $key    密钥*/function file_encrypt($source, $dest, $key){if(file_exists($source)){$content = '';          // 处理后的字符串$keylen = strlen($key); // 密钥长度$index = 0;$fp = fopen($source, 'rb');while(!feof($fp)){$tmp = fread($fp, 1);$content .= $tmp ^ substr($key,$index%$keylen,1);$index++;}fclose($fp);return file_put_contents($dest, $content, true);}else{return false;}}?>

相关文章:《C 使用异或(xor)加密/解密文件》



原创粉丝点击