C语言实验 文件加密与解密

简单的加密与解密方法有:异或实现,ASCII码移位,ASCII码与二进制、十进制等转换。

当然还有其他更复杂的包括军事加密机制,不作论述。

本次实验我采用ASCII码与十进制转换,把每个字符强制转化为3位ASCII数字,进行加密和解密。

#include 
#include 

int main() {
    FILE *f1, *f2, *f3;

    int a, i,tmp,tmp1,tmp2;
    char c,ct;
    while(scanf("%d", &a)) {
        if(a == 1) {
            f1 = fopen("file1.txt", "r");
            f2 = fopen("file2.txt", "w");
            if( f1 == NULL || f2 == NULL) {
                printf("Open file1 failed!\n");
                exit(0);
            }
            while((c = fgetc(f1)) != EOF) {
                tmp=(int)c;
                if(tmp<100){fprintf(f2,"0%d",tmp);}
                else{fprintf(f2,"%d",tmp);}
            }
            fclose(f2);
            fclose(f1);
            printf("\nFile1 is encrypted!\n");
        } else if(a == 2) {
            f2 = fopen("file2.txt", "r");
            f3 = fopen("file3.txt", "w");
            if( f2 == NULL || f3 == NULL) {
                printf("Open file2 failed!\n");
                exit(0);
            }
            while(fscanf(f2,"%3d",&tmp)!=EOF) {
                ct=(char)tmp;
                fprintf(f3,"%c",ct);
            }
            fclose(f3);
            fclose(f2);
            printf("\nFile2 is decrypted!\n");
        } else if(a == 0) {
            printf("Ended\n");
            break;
        }
    }

    return 0;
}

实现结果:

 

你可能感兴趣的:(C)