PHP使用异或加密解密文件
- 原理:将文件的每一个字节与密钥的单位做异或处理
-
<?php /** * 文件加密解密方法 * @param string $input 源文件 * @param string $ouput 加密文件 * @param string $key 密钥 */ function file_crypt ( $input , $ouput , $key ) { if (!file_exists($input)) { throw new Exception("Input Source Error", 1); } if (!$ouput || !$key) { throw new Exception("Ouput Or Key Error", 1); } // 加密后的字符串 $content = ''; // 密钥长度 $keylen = strlen($key); // 索引 $sublen = $keylen - 1; // 索引 $index = 0; $fp = fopen($input, 'rb'); while (!feof($fp)) { // 读取一个字节 $tmp = fread($fp, 1); // 内容与密钥的字节做异或处理 $content .= $tmp ^ substr($key, $index % $keylen, 1); // 索引规律变化 (防止数量递增) if ($index < $sublen) { $index ++; } else { $index = 0; } } // 关闭资源 fclose($fp); return file_put_contents($ouput, $content, true); } file_crypt('./tupian.jpg', './jiami.jpg', 'abcdefg');
C语言写的版本
-
#define TRUE 1 #define FALSE 0 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <io.h> // 如果在/usr/include/找不到,可以在/usr/include/sys/复制过去 // 输出信息 void msg_log(char *str); // 判断文件是否存在 int file_exists(char *filename); // 主函数 int main(int argc, char *argv[]){ int keylen, index=0; char *source, *dest, *key, fBuffer[1], tBuffer[20], ckey; FILE *fSource, *fDest; source = argv[1]; // 原文件 dest = argv[2]; // 目的文件 key = argv[3]; // 加密字串 // 检查参数 if(source==NULL || dest==NULL || key==NULL){ msg_log("param error\nusage:xor_encrypt source dest key\ne.g ./xor_encrypt o.txt d.txt 123456"); exit(0); } // 判断原文件是否存在 if(file_exists(source)==FALSE){ sprintf(tBuffer,"%s not exists",source); msg_log(tBuffer); exit(0); } // 获取key长度 keylen = strlen(key); fSource = fopen(source, "rb"); fDest = fopen(dest, "wb"); while(!feof(fSource)){ fread(fBuffer, 1, 1, fSource); // 读取1字节 if(!feof(fSource)){ ckey = key[index%keylen]; // 循环获取key *fBuffer = *fBuffer ^ ckey; // xor encrypt fwrite(fBuffer, 1, 1, fDest); // 写入文件 index ++; } } fclose(fSource); fclose(fDest); msg_log("success"); exit(0); } //输出信息 void msg_log(char *str){ printf("%s\n", str); } // 判断文件是否存在 int file_exists(char *filename){ return (access(filename, 0)==0); }