请扮演一个资深程序员,编写 基于C++的Vigenere 密码加解密,在指定的目录下建立明文文件,输入任意选取的密钥, 加密后得到密文文件,在已知密钥的情况下将密文文件解密得到明文文件,注意改程序需要区分大小写字母和符号
时间: 2023-06-01 18:04:27 浏览: 113
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_FILENAME_LEN 256
#define MAX_KEY_LEN 256
#define BUFFER_SIZE 1024
void encrypt_file(char *filename, char *key);
void decrypt_file(char *filename, char *key);
void vigenere_cipher(char *input, char *output, char *key, int encrypt);
int main() {
char filename[MAX_FILENAME_LEN];
char key[MAX_KEY_LEN];
int choice;
printf("请选择要进行的操作:\n");
printf("1. 加密文件\n");
printf("2. 解密文件\n");
printf("请选择:");
scanf("%d", &choice);
printf("请输入文件名:");
scanf("%s", filename);
printf("请输入密钥:");
scanf("%s", key);
switch (choice) {
case 1:
encrypt_file(filename, key);
break;
case 2:
decrypt_file(filename, key);
break;
default:
printf("无效的选择\n");
break;
}
return 0;
}
void encrypt_file(char *filename, char *key) {
FILE *fp_in, *fp_out;
char output_filename[MAX_FILENAME_LEN];
// 打开输入文件
fp_in = fopen(filename, "rb");
if (fp_in == NULL) {
printf("打开输入文件失败\n");
return;
}
// 构造输出文件名
sprintf(output_filename, "%s.enc", filename);
// 打开输出文件
fp_out = fopen(output_filename, "wb");
if (fp_out == NULL) {
printf("打开输出文件失败\n");
fclose(fp_in);
return;
}
// 逐个读取并加密字符
char buffer[BUFFER_SIZE];
char output_buffer[BUFFER_SIZE];
int key_len = strlen(key);
int i = 0;
int j = 0;
int bytes_read;
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, fp_in)) > 0) {
vigenere_cipher(buffer, output_buffer, key, 1);
fwrite(output_buffer, 1, bytes_read, fp_out);
}
// 关闭文件
fclose(fp_in);
fclose(fp_out);
printf("加密成功,加密后文件为 %s\n", output_filename);
}
void decrypt_file(char *filename, char *key) {
FILE *fp_in, *fp_out;
char output_filename[MAX_FILENAME_LEN];
// 打开输入文件
fp_in = fopen(filename, "rb");
if (fp_in == NULL) {
printf("打开输入文件失败\n");
return;
}
// 构造输出文件名
int len = strlen(filename);
if (len > 4 && strcmp(filename + len - 4, ".enc") == 0) {
strncpy(output_filename, filename, len - 4);
output_filename[len - 4] = '\0';
} else {
sprintf(output_filename, "%s.dec", filename);
}
// 打开输出文件
fp_out = fopen(output_filename, "wb");
if (fp_out == NULL) {
printf("打开输出文件失败\n");
fclose(fp_in);
return;
}
// 逐个读取并解密字符
char buffer[BUFFER_SIZE];
char output_buffer[BUFFER_SIZE];
int key_len = strlen(key);
int i = 0;
int j = 0;
int bytes_read;
while ((bytes_read = fread(buffer, 1, BUFFER_SIZE, fp_in)) > 0) {
vigenere_cipher(buffer, output_buffer, key, 0);
fwrite(output_buffer, 1, bytes_read, fp_out);
}
// 关闭文件
fclose(fp_in);
fclose(fp_out);
printf("解密成功,解密后文件为 %s\n", output_filename);
}
void vigenere_cipher(char *input, char *output, char *key, int encrypt) {
int input_len = strlen(input);
int key_len = strlen(key);
int i, j, k;
for (i = 0, j = 0; i < input_len; i++) {
if (isalpha(input[i])) {
k = toupper(key[j % key_len]) - 'A';
if (encrypt) {
output[i] = (input[i] + k) % 256;
} else {
output[i] = (input[i] - k + 256) % 256;
}
j++;
} else {
output[i] = input[i];
}
}
}
阅读全文