vigenere密码算法c
时间: 2023-11-18 16:05:35 浏览: 100
下面是Vigenere密码算法的C代码实现,包括加密和解密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* encrypt(char* plaintext, char* key);
char* decrypt(char* ciphertext, char* key);
int main() {
char plaintext[] = "Vigenere cipher is a polyalphabetic cipher";
char key[] = "SECRET";
char* ciphertext = encrypt(plaintext, key);
printf("Ciphertext: %s\n", ciphertext);
char* decryptedtext = decrypt(ciphertext, key);
printf("Decrypted text: %s\n", decryptedtext);
free(ciphertext);
free(decryptedtext);
return 0;
}
char* encrypt(char* plaintext, char* key) {
int plaintext_len = strlen(plaintext);
int key_len = strlen(key);
char* ciphertext = (char*) malloc(sizeof(char) * (plaintext_len + 1));
for (int i = 0; i < plaintext_len; i++) {
ciphertext[i] = ((plaintext[i] + key[i % key_len]) % 26) + 'A';
}
ciphertext[plaintext_len] = '\0';
return ciphertext;
}
char* decrypt(char* ciphertext, char* key) {
int ciphertext_len = strlen(ciphertext);
int key_len = strlen(key);
char* decryptedtext = (char*) malloc(sizeof(char) * (ciphertext_len + 1));
for (int i = 0; i < ciphertext_len; i++) {
decryptedtext[i] = (((ciphertext[i] - key[i % key_len]) + 26) % 26) + 'A';
}
decryptedtext[ciphertext_len] = '\0';
return decryptedtext;
}
```
这个代码使用了纯文本作为明文和密钥,返回的密文和解密后的明文也是纯文本。在实际使用中,需要先将明文和密钥转换成数字或二进制形式,再进行加密和解密。
阅读全文