«

用C写一个简单的加解密程序

时间:2023-3-3 19:55     作者:wen     分类: 编程语言


// 引入头文件 标准的输入输出
#include <stdio.h>
// 字符串 提供了一些字符串所要用到的函数
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

// 声明一些变量
char ch = '0';
char filename[256] = ""; // 保存文件收入的路径
FILE* fp = NULL;
FILE* fptemp = NULL;
char password[12] = "123456";
const char tempfile[256] = "temp1234567890.temp";
int pwdlen = 0;
int i = 0;

// 封装一些函数
// 函数声明
void menu();
void inputpass(char* pass);

void inputpass(char* pass)
{
    scanf("%s", pass);
}

// 函数实现
void menu()
{
    printf("************************************************\n");
    printf("****************安全课程小程序*******************\n");
    printf("************************************************\n");
    printf("****************请输入要机密或解密的文件路径******\n");
    printf("****************例如:/user/wen/av.txt**********\n");
    // 1. 要打开一个文件或目录
    gets(filename);
    fp = fopen(filename, "rb");
    if (NULL == fp) {
        // 如果不为空 表示文件存在, 空的 表示文件不存在
        // 退出
        exit(0);
    }
    // 如果文件存在
    printf("文件存在,请输入密码。如:888888\n");
    inputpass(password);
    pwdlen = (int)strlen(password);
    if (0 == pwdlen) {
        printf("对不起密码长度不能为0。\n");
        exit(2);
    }
    // 2. 读出文件中的内容进行加密
    fptemp = fopen(tempfile, "wb");
    // 3. 把加密的信息写入到文件中覆盖原来的数据
    while (1)
    {
        /* code */
        ch = getc(fp);
        if (feof(fp))
        {
            // 判断文件读完没有
            break;
        }
        // 每取出一个字符就加密
        ch ^= password[i++];
        fputc(ch, fptemp);
        if (i == pwdlen)
        {
            i = 0;
        }
    }
    // 循环结束后 清理
    fclose(fp);
    fclose(fptemp);
    remove(filename);
    rename(tempfile, filename);
    printf("恭喜你!加密或解密成功!\n");

}

// 主函数 是C语言程序的入口地址
int main(int argc, char const* argv[])
{
    /* code */
    menu();
    return 0;
}

然后用gcc编译
gcc encrypt.c -o tools 生成一个tools的可执行文件,运行文件就行

标签: C/C++