C 使用异或(xor)加密/解密文件

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

之前写过一篇《php 使用异或(XOR)加密/解密文件》,但php执行的速度很慢,因此这次使用C重写,速度有很大的提高。


xor_encrypt.c

/** XOR 加密/解密文件 */

#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
usage:xor_encrypt source dest key
e.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
", str);
}

// 判断文件是否存在
int file_exists(char *filename){
    return (access(filename, 0)==0);
}

这张图如果使用php来处理需要 2秒 左右,但用C处理只需要 130毫秒

fdipzone@ubuntu:~/C$ gcc -o xor_encrypt xor_encrypt.c
fdipzone@ubuntu:~/C$ time ./xor_encrypt 1280.jpg 1280en.jpg '@#$%^&*()_DFGHJKadsklfjasdf'
success

real	0m0.139s
user	0m0.060s
sys	0m0.070s


原文地址:https://www.cnblogs.com/fdipzone/p/3715054.html