c++实现维吉尼亚加解密
时间: 2023-05-21 16:02:35 浏览: 172
可以使用以下代码实现维吉尼亚加解密:
```c
#include <stdio.h>
#include <string.h>
void vigenere_encrypt(char *plaintext, char *key, char *ciphertext) {
int i, j, k;
int plaintext_len = strlen(plaintext);
int key_len = strlen(key);
for (i = 0, j = 0; i < plaintext_len; i++, j++) {
if (j == key_len) {
j = 0;
}
k = (plaintext[i] + key[j]) % 26;
ciphertext[i] = k + 'A';
}
ciphertext[i] = '\0';
}
void vigenere_decrypt(char *ciphertext, char *key, char *plaintext) {
int i, j, k;
int ciphertext_len = strlen(ciphertext);
int key_len = strlen(key);
for (i = 0, j = 0; i < ciphertext_len; i++, j++) {
if (j == key_len) {
j = 0;
}
k = (ciphertext[i] - key[j] + 26) % 26;
plaintext[i] = k + 'A';
}
plaintext[i] = '\0';
}
int main() {
char plaintext[] = "HELLO";
char key[] = "WORLD";
char ciphertext[strlen(plaintext)];
char decrypted_plaintext[strlen(plaintext)];
vigenere_encrypt(plaintext, key, ciphertext);
printf("Ciphertext: %s\n", ciphertext);
vigenere_decrypt(ciphertext, key, decrypted_plaintext);
printf("Decrypted plaintext: %s\n", decrypted_plaintext);
return 0;
}
```
这段代码实现了维吉尼亚加解密,其中 plaintext 是明文,key 是密钥,ciphertext 是密文,decrypted_plaintext 是解密后的明文。
阅读全文