Welcome 微信登录

首页 / 网页编程 / PHP / php使用异或(XOR)加密和解密文件

php使用异或(XOR)加密和解密文件2014-08-20php 使用异或(XOR)加密/解密文件

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

代码如下:

01.<?php
02.
03.$source = "test.jpg";
04.$encrypt_file = "test_enc.jpg";
05.$decrypt_file = "test_dec.jpg";
06.$key = "D89475D32EA8BBE933DBD299599EEA3E";
07.
08.echo "<p>source:</p>";
09.echo "<img src="".$source."" width="200">";
10.echo "<hr>";
11.
12.file_encrypt($source, $encrypt_file, $key); // encrypt
13.
14.echo "<p>encrypt file:</p>";
15.echo "<img src="".$encrypt_file."" width="200">";
16.echo "<hr>";
17.
18.file_encrypt($encrypt_file, $decrypt_file, $key); // decrypt
19.
20.echo "<p>decrypt file:</p>";
21.echo "<img src="".$decrypt_file."" width="200">";
22.
23./** 文件加密,使用key与原文异或生成密文,解密则再执行一次异或即可
24.* @param String $source 要加密或解密的文件
25.* @param String $dest 加密或解密后的文件
26.* @param String $key密钥
27.*/
28.function file_encrypt($source, $dest, $key){
29.if(file_exists($source)){
30.
31.$content = "";// 处理后的字符串
32.$keylen = strlen($key); // 密钥长度
33.$index = 0;
34.
35.$fp = fopen($source, "rb");
36.
37.while(!feof($fp)){
38.$tmp = fread($fp, 1);
39.$content .= $tmp ^ substr($key,$index%$keylen,1);
40.$index++;
41.}
42.
43.fclose($fp);
44.
45.return file_put_contents($dest, $content, true);
46.
47.}else{
48.return false;
49.}
50.}
51.
52.?>