您当前的位置:首页 > 计算机 > 编程开发 > C语言

简单的文件加密C语言代码实现

时间:03-29来源:作者:点击数:

加密算法通过对原文的每个字符进行异或运算来进行加密;解密时同样进行异或处理即可恢复到原文。

代码实现如下

#include<stdlib.h>
#include <stdio.h>

int getfilesize(char *path)
{ 
    FILE *pf = fopen(path, "r");
    if (pf == NULL)
    { 
        return -1;
    }
    else
    { 
        fseek(pf, 0, SEEK_END);
        int length = ftell(pf);
        return length;
    }
}

void EncryptFile(char *oldpath, char *newpath)
{ 
    int i = 0;
    FILE *pfr, *pfw;
    pfr = fopen(oldpath, "rb");
    pfw = fopen(newpath, "wb");
    if (pfr == NULL || pfw == NULL)
    { 
        fclose(pfr);
        fclose(pfw);
        return;
    }
    else
    { 
        int length = getfilesize(oldpath);
        char *p = (char *)malloc(length*sizeof(char));
        fread(p, sizeof(char), length, pfr);
        for (i = 0; i < length; i++)
        { 
            p[i] ^= 'A';
        }
        fwrite(p, sizeof(char), length, pfw);
        fclose(pfr);
        fclose(pfw);
    }
}
void DecryptFile(char *oldpath, char *newpath)
{ 
    int i = 0;
    FILE *pfr, *pfw;
    pfr = fopen(oldpath, "rb");
    pfw = fopen(newpath, "wb");
    if (pfr == NULL || pfw == NULL)
    { 
        fclose(pfr);
        fclose(pfw);
        return;
    }
    else
    { 
        int length = getfilesize(oldpath);
        char *p = (char *)malloc(length*sizeof(char));
        fread(p, sizeof(char), length, pfr);
        for (i = 0; i < length; i++)
        { 
            p[i] ^= 'A';
        }
        fwrite(p, sizeof(char), length, pfw);
        fclose(pfr);
        fclose(pfw);
    }
}
#if 0
void main()
{           
    // 原始文件的路径
    char *oldpath = "log.txt";
    // 加密后的路径
    char *newpath = "log-EecryptFile.dat";
    // 解密后的路径
    char *newDecryptFilepath = "log-DecryptFile.txt";
    EncryptFile(oldpath, newpath);
    DecryptFile(newpath, newDecryptFilepath);
}
#endif
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门