码迷,mamicode.com
首页 > 编程语言 > 详细

C语言实现简单文件加密

时间:2015-04-10 19:59:57      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

原理:异或运算

加密:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define KEY ‘@‘
int main(int argc, char * argv[]){
    FILE *fp;
    FILE *coded;
    char codedname[40];
    char ch;
    if(argc < 2){
        printf("param error!\n");
        exit(1);
    }
    if((fp = fopen(argv[1], "rb")) == NULL){
        printf("error when open file %s.\n", argv[1]);
        exit(1);
    }
    strcpy(codedname, argv[1]);
    strcat(codedname, ".coded");
    if((coded = fopen(codedname, "a+b")) == NULL){
        printf("error when open file %s.\n", codedname);
        exit(1);
    }
    while((ch = getc(fp)) != EOF){
        char temp = ch^KEY;
        putc(temp, coded);
    }

    if(fclose(fp) != 0){
        printf("error when close file %s.\n", argv[1]);
        exit(1);
    }
    if(fclose(coded) != 0){
        printf("error when close file %s.\n", codedname);
    }
    return 0;
}

解密:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char * argv[]){
    FILE *fp;
    FILE *decoded;
    char decodedname[40];
    char ch;
    char key;
    const char *dot = ".";
    if(argc < 3){
        printf("param error!\n");
        exit(1);
    }
    if((fp = fopen(argv[1], "rb")) == NULL){
        printf("error when open file %s.\n", argv[1]);
        exit(1);
    }
    strcpy(decodedname, strtok(argv[1], dot));
    strcat(decodedname, ".");
    strcat(decodedname, strtok(NULL, dot));
    key = argv[2][0];

    if((decoded = fopen(decodedname, "a+b")) == NULL){
        printf("error when open file %s.\n", decodedname);
        exit(1);
    }
    while((ch = getc(fp)) != EOF){
        char temp = ch^key;
        putc(temp, decoded);
    }

    if(fclose(fp) != 0){
        printf("error when close file %s.\n", argv[1]);
        exit(1);
    }
    if(fclose(decoded) != 0){
        printf("error when close file %s.\n", decodedname);
    }
    return 0;
}

 

C语言实现简单文件加密

标签:

原文地址:http://www.cnblogs.com/msing/p/4415211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!