Vigenere密碼是一種歷史長久的多碼加密法,它基於關鍵詞停止加密,存在很高的保險性。在本文中,我們將利用C言語來剖析Vigenere密碼的編碼與解碼技能,幫助讀者輕鬆控制這一加密方法。
Vigenere密碼簡介
Vigenere密碼是一種調換加密法,它利用一個關鍵詞(密鑰)來決定每個明文字母的調換方法。關鍵詞的長度決定了加密跟解密過程中的調換形式。Vigenere密碼的加密跟解密過程如下:
- 編碼過程:將明文字母與密鑰中的字母停止對應,根據密鑰字母在Vigenere表中查找對應的密文字母。
- 解碼過程:與編碼過程相反,根據密文字母跟密鑰字母在Vigenere表中查找對應的明文字母。
Vigenere密碼的C言語實現
以下是一個利用C言語實現的Vigenere密碼編碼跟解碼的示例代碼:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define ALPHABET_SIZE 26
// 函數申明
void VigenereEncrypt(char *plaintext, char *keyword, char *ciphertext);
void VigenereDecrypt(char *ciphertext, char *keyword, char *plaintext);
void GenerateVigenereTable(char *table);
int main() {
char plaintext[100], keyword[100], ciphertext[100];
// 生成Vigenere表
char vigenereTable[ALPHABET_SIZE][ALPHABET_SIZE];
GenerateVigenereTable(vigenereTable);
// 獲取用戶輸入
printf("Enter plaintext: ");
fgets(plaintext, sizeof(plaintext), stdin);
plaintext[strcspn(plaintext, "\n")] = 0; // 移除換行符
printf("Enter keyword: ");
fgets(keyword, sizeof(keyword), stdin);
keyword[strcspn(keyword, "\n")] = 0; // 移除換行符
// 編碼
VigenereEncrypt(plaintext, keyword, ciphertext);
printf("Ciphertext: %s\n", ciphertext);
// 解碼
VigenereDecrypt(ciphertext, keyword, plaintext);
printf("Decrypted plaintext: %s\n", plaintext);
return 0;
}
// 生成Vigenere表
void GenerateVigenereTable(char *table) {
for (int i = 0; i < ALPHABET_SIZE; i++) {
for (int j = 0; j < ALPHABET_SIZE; j++) {
table[i][j] = 'A' + (i + j) % ALPHABET_SIZE;
}
}
}
// Vigenere加密
void VigenereEncrypt(char *plaintext, char *keyword, char *ciphertext) {
int keywordIndex = 0;
for (int i = 0; plaintext[i] != '\0'; i++) {
if (isalpha(plaintext[i])) {
int key = tolower(keyword[keywordIndex % strlen(keyword)]) - 'a';
key = isupper(plaintext[i]) ? key + 'A' - 'a' : key;
ciphertext[i] = (toupper(plaintext[i]) - 'A' + key) % ALPHABET_SIZE + 'A';
keywordIndex++;
} else {
ciphertext[i] = plaintext[i];
}
}
ciphertext[strlen(plaintext)] = '\0'; // 增加字符串結束符
}
// Vigenere解碼
void VigenereDecrypt(char *ciphertext, char *keyword, char *plaintext) {
int keywordIndex = 0;
for (int i = 0; ciphertext[i] != '\0'; i++) {
if (isalpha(ciphertext[i])) {
int key = tolower(keyword[keywordIndex % strlen(keyword)]) - 'a';
key = isupper(ciphertext[i]) ? key + 'A' - 'a' : key;
plaintext[i] = (toupper(ciphertext[i]) - 'A' - key + ALPHABET_SIZE) % ALPHABET_SIZE + 'A';
keywordIndex++;
} else {
plaintext[i] = ciphertext[i];
}
}
plaintext[strlen(ciphertext)] = '\0'; // 增加字符串結束符
}
這段代碼起首定義了一個函數GenerateVigenereTable
來生成Vigenere表,然後定義了兩個函數VigenereEncrypt
跟VigenereDecrypt
來實現Vigenere密碼的編碼跟解碼過程。
總結
經由過程本文的講解,信賴讀者曾經控制了Vigenere密碼的編碼與解碼技能,並可能利用C言語來實現這一加密方法。在現實利用中,Vigenere密碼的保險性絕對較低,但對懂得加密道理跟進修編程來說,它仍然是一個很好的例子。