70,022
社区成员




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define FILE_NAME_LEN 32
#define MAX_KEY_NUM 26
enum {
ENCRYPT_DATA = 1,
DECRYPT_DATA,
FORCE_DECRYPT_DATA,
EXIT_PROCESS
};
/*加密函数,把字符向右循环移位n*/
char encrypt(char ch, int n)
{
while(ch >= 'A' && ch <= 'Z') {
return ('A'+(ch-'A'+n)%26);
}
while(ch >= 'a' && ch <= 'z') {
return ('a'+(ch-'a'+n)%26);
}
return ch;
}
/*菜单,1.加密,2.解密,3.暴力破解,密码只能是数字*/
static void menu(void)
{
printf("\n=========================================================");
printf("\n1.Encrypt the file");
printf("\n2.Decrypt the file");
printf("\n3.Force decrypt file");
printf("\n4.Quit\n");
printf("=========================================================\n");
return;
}
static int get_opt(void)
{
int option, ret;
printf("Please input your choice: ");
ret = scanf("%d", &option);
while (ret != 1) {
printf("Please input your choice: ");
ret = scanf("%d", &option);
}
return option;
}
/* Open a file, then return file decription. */
static FILE *open_file(const char *filename, const char *openmode)
{
FILE *fp = NULL;
fp = fopen(filename, openmode);
if(!fp) {
printf("Can not open the outfile: %s, %s!\n", filename, strerror(errno));
exit(0);
}
return fp;
}
/* Copy data from source file to destination file. */
int copy_data(FILE *src_fp, FILE *dst_fp, int key)
{
int data, cnt = 0;
while(!feof(src_fp)) { /* 加密 */
data = encrypt(fgetc(src_fp), key);
if (data != EOF) {
putchar(data);
fputc(data, dst_fp);
cnt++;
}
}
return cnt;
}
int main(int argc, const char *argv[])
{
char src_file[FILE_NAME_LEN];
char dst_file[FILE_NAME_LEN];
FILE *src_fp, *dst_fp;
int option, key, ret;
int total_num, i;
while (1) {
menu();
option = get_opt();
if (option == EXIT_PROCESS) {
printf("Goodbye!\n");
break;
}
printf("Please input src file: ");
scanf("%s", src_file);
src_fp = open_file(src_file, "r");
if (!src_fp)
return 1;
printf("Please input dst file: ");
scanf("%s", dst_file);
dst_fp = open_file(dst_file, "w");
if (!dst_fp) {
fclose(src_fp);
return 1;
}
if (option != FORCE_DECRYPT_DATA) {
printf("Please input the key: ");
ret = scanf("%d", &key);
while (ret != 1) {
printf("Please input the key: ");
ret = scanf("%d", &key);
}
}
switch (option) {
case ENCRYPT_DATA:
total_num = copy_data(src_fp, dst_fp, key);
printf("Encrypt %d character(s)\n", total_num);
fclose(src_fp);
fclose(dst_fp);
break;
case DECRYPT_DATA:
key = 26 - key;
total_num = copy_data(src_fp, dst_fp, key);
printf("Encrypt %d character(s)\n", total_num);
fclose(src_fp);
fclose(dst_fp);
break;
case FORCE_DECRYPT_DATA:
for (i = 1; i < MAX_KEY_NUM; i++) {
fseek(src_fp, 0l, SEEK_SET);
fseek(dst_fp, 0l, SEEK_SET);
total_num = copy_data(src_fp, dst_fp, 26-i);
printf("Current encrypt's key is %d\n", i);
printf("Encrypt %d character(s)\n", total_num);
printf("Press 'Q' to quit and other key to continue......\n");
option = getchar();
if (option == 'Q' || option == 'q') {
break;
}
}
fclose(src_fp);
fclose(dst_fp);
break;
}
printf("\nEncrypt is over!\n");
}
return 0;
}