首页 > 代码库 > 给文件简单加密

给文件简单加密

#include <iostream>
#include <string>

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

#define BUFF_LEN 1024

using namespace std;

long file_len(string file_name);

void init(string file_name)
{
}

void release()
{
}

int get_random(int max_rand)
{
srand (time(NULL));
int r = rand() % max_rand + 1;
return r;
}

long file_len(string file_name)
{
FILE * pFile;
long size;

pFile = fopen (file_name.c_str(),"rb");
if (pFile==NULL) perror ("Error opening file");
else
{
fseek (pFile, 0, SEEK_END); // non-portable
size=ftell (pFile);
fclose (pFile);
printf ("Size of myfile.txt: %ld bytes.\n",size);
}
return size;
}

void buff_reverse(char *buff, size_t len, FILE *ou_f)
{
for (int i = len - 1; i >= 0; --i)
{
fputc(buff[i], ou_f);
}
}

void encry_file(string src_file, string tgt_file, int rand_seed)
{
FILE *in_f = fopen(src_file.c_str(), "rb");
FILE *ou_f = fopen(tgt_file.c_str(), "wb");
int r = get_random(rand_seed);
fwrite(&rand_seed, sizeof(int), 1, ou_f);
fwrite(&r, sizeof(int), 1, ou_f);
char buff[BUFF_LEN];
r = get_random(BUFF_LEN);

size_t len = fread(buff, sizeof(char), r, in_f);
while (!feof(in_f))
{
fwrite(&len, sizeof(int), 1, ou_f);
buff_reverse(buff, len, ou_f);
r = get_random(BUFF_LEN);
len = fread(buff, sizeof(char), r, in_f);
}
fwrite(&len, sizeof(int), 1, ou_f);
buff_reverse(buff, len, ou_f);
fclose(in_f);
fclose(ou_f);
}

int is_not_accu(int rand_seed, int c)
{
int g = get_random(rand_seed);
printf("rand_seed:%d, key:%d, guess:%d\n", rand_seed, c, g);
if (c == g) return 0;
else return 1;
}

int decry_file(string src_file, string tgt_file)
{
FILE *in_f = fopen(src_file.c_str(), "rb");

int rand_seed, c;
char buff[BUFF_LEN];
fread(&rand_seed, sizeof(int), 1, in_f);
fread(&c, sizeof(int), 1, in_f);
//verification part
if (is_not_accu(rand_seed, c)) {
printf("failed\n");
return 1;
}

FILE *ou_f = fopen(tgt_file.c_str(), "wb");
size_t len = fread(&c, sizeof(int), 1, in_f);
while (!feof(in_f))
{
size_t len_in = fread(buff, sizeof(char), c, in_f);
buff_reverse(buff, len_in, ou_f);
len = fread(&c, sizeof(int), 1, in_f);
}
size_t len_in = fread(buff, sizeof(char), c, in_f);
buff_reverse(buff, len_in, ou_f);
fclose(in_f);
fclose(ou_f);

printf("success\n");
return 0;
}

void args()
{
printf("encrypt src_file tgt_file rand_seed\n");
printf("decrypt src_file tgt_file\n");
}

int main(int argc, char **argv)
{
if (argc < 3)
{
args();
return 1;
}
string comm = string(argv[1]);
if (comm == "encrypt")
{
string src_file = string(argv[2]);
string tgt_file = string(argv[3]);
int rand_seed = atoi(argv[4]);
encry_file(src_file, tgt_file, rand_seed);
}
else if (comm == "decrypt")
{
string src_file = string(argv[2]);
string tgt_file = string(argv[3]);
decry_file(src_file, tgt_file);
}

}