请扮演一个资深程序员,编写 基于C语言的Vigenere 密码加解密,在指定的目录下建立明文文件,输入任意选取的密钥, 加密后得到密文(包含大写字母和小写字母)文件。在已知密钥的情况下将密文(包含大写字母和小写字母)文件解密得到明文(包含大写字母和小写字母)文件
时间: 2023-05-31 12:06:24 浏览: 89
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_SIZE 1024
void encrypt(char* plaintext, char* key, char* ciphertext);
void decrypt(char* ciphertext, char* key, char* plaintext);
int main() {
char plaintext[MAX_SIZE];
char ciphertext[MAX_SIZE];
char key[MAX_SIZE];
char filename[MAX_SIZE];
FILE *fp;
int choice;
printf("请选择操作:\n1.加密\n2.解密\n");
scanf("%d", &choice);
printf("请输入明文文件名:");
scanf("%s", filename);
fp = fopen(filename, "r");
if (fp == NULL) {
printf("打开文件失败!\n");
exit(1);
}
fgets(plaintext, MAX_SIZE, fp);
fclose(fp);
printf("请输入密钥:");
scanf("%s", key);
switch (choice) {
case 1:
encrypt(plaintext, key, ciphertext);
printf("加密后的密文为:\n%s\n", ciphertext);
printf("请输入密文文件名:");
scanf("%s", filename);
fp = fopen(filename, "w");
if (fp == NULL) {
printf("打开文件失败!\n");
exit(1);
}
fputs(ciphertext, fp);
fclose(fp);
break;
case 2:
decrypt(plaintext, key, ciphertext);
printf("解密后的明文为:\n%s\n", plaintext);
printf("请输入明文文件名:");
scanf("%s", filename);
fp = fopen(filename, "w");
if (fp == NULL) {
printf("打开文件失败!\n");
exit(1);
}
fputs(plaintext, fp);
fclose(fp);
break;
default:
printf("无效操作!\n");
break;
}
return 0;
}
void encrypt(char* plaintext, char* key, char* ciphertext) {
int len_p = strlen(plaintext);
int len_k = strlen(key);
for (int i = 0; i < len_p; i++) {
if (plaintext[i] >= 'a' && plaintext[i] <= 'z') {
ciphertext[i] = (plaintext[i] - 'a' + key[i % len_k] - 'a') % 26 + 'a';
}
else if (plaintext[i] >= 'A' && plaintext[i] <= 'Z') {
ciphertext[i] = (plaintext[i] - 'A' + key[i % len_k] - 'a') % 26 + 'A';
}
else {
ciphertext[i] = plaintext[i];
}
}
ciphertext[len_p] = '\0';
}
void decrypt(char* ciphertext, char* key, char* plaintext) {
int len_c = strlen(ciphertext);
int len_k = strlen(key);
for (int i = 0; i < len_c; i++) {
if (ciphertext[i] >= 'a' && ciphertext[i] <= 'z') {
plaintext[i] = (ciphertext[i] - 'a' - key[i % len_k] + 'a' + 26) % 26 + 'a';
}
else if (ciphertext[i] >= 'A' && ciphertext[i] <= 'Z') {
plaintext[i] = (ciphertext[i] - 'A' - key[i % len_k] + 'a' + 26) % 26 + 'A';
}
else {
plaintext[i] = ciphertext[i];
}
}
plaintext[len_c] = '\0';
}
阅读全文