首页 > 编程语言 >【网安】第一次写的简单加密程序

【网安】第一次写的简单加密程序

时间:2022-11-05 08:22:20浏览次数:64  
标签:fp 加密 int 程序 filename char printf 网安

教学链接:https://www.bilibili.com/video/BV1UG411L74y?p=33&vd_source=01e5c1103fb910315f88a7bdc747b3d5

c语言实现的简单加密程序

核心加密原理:

将文件逐字符读取和密码进行逐位异或运算进行加解密。
异或运算具有自反性:a ^ b ^ a = b
所以a可以用来加密b,再次计算会解密

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


char ch = '0';
char filename[256]="";
FILE *fp=NULL; 
FILE *fptemp=NULL;
char password[12]="123456";
int pwdlen=0;
const char tempfile[256]="temp.temp";
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/liang/av.txt*********************\n");
    gets(filename);
    if( NULL == (fp=fopen(filename,"rb")))
    {
        printf("你输入的文件不存在!\n");
        exit(1);
    }
    printf("文件存在,请输入密码。如:888888888\n");
    inputpass(password);
    pwdlen=(int)strlen(password);
    if( 0 == pwdlen)
    {
        printf("密码不能为空!\n");
        exit(2);
    }
    fptemp = fopen("temp.temp","wb");
    while(1)
    {
        
        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");

}

int main(int argc,char const *argv[])
{
    menu();
    return 0;
}

标签:fp,加密,int,程序,filename,char,printf,网安
From: https://www.cnblogs.com/blanset/p/16859616.html

相关文章