希尔密码C语言源代码,希尔密码加密解密(示例代码)
时间: 2023-09-05 10:15:11 浏览: 39
以下是希尔密码的C语言加密解密示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100
void encrypt(char message[], int key) {
int i, j, k = 0;
char cipher[MAX_LEN];
for(i = 0; message[i] != '\0'; i++) {
if(message[i] >= 'a' && message[i] <= 'z') {
cipher[k++] = ((message[i] - 'a') * key) % 26 + 'a';
}
else if(message[i] >= 'A' && message[i] <= 'Z') {
cipher[k++] = ((message[i] - 'A') * key) % 26 + 'A';
}
}
cipher[k] = '\0';
printf("Encrypted Message: %s\n", cipher);
}
void decrypt(char cipher[], int key) {
int i, j, k = 0, inverse_key = 0;
char message[MAX_LEN];
for(i = 0; i < 26; i++) {
if((key * i) % 26 == 1) {
inverse_key = i;
}
}
for(i = 0; cipher[i] != '\0'; i++) {
if(cipher[i] >= 'a' && cipher[i] <= 'z') {
message[k++] = ((cipher[i] - 'a') * inverse_key) % 26 + 'a';
}
else if(cipher[i] >= 'A' && cipher[i] <= 'Z') {
message[k++] = ((cipher[i] - 'A') * inverse_key) % 26 + 'A';
}
}
message[k] = '\0';
printf("Decrypted Message: %s\n", message);
}
int main() {
char message[MAX_LEN], cipher[MAX_LEN];
int key;
printf("Enter the message to encrypt: ");
fgets(message, MAX_LEN, stdin);
printf("Enter the key: ");
scanf("%d", &key);
encrypt(message, key);
printf("Enter the cipher to decrypt: ");
getchar();
fgets(cipher, MAX_LEN, stdin);
printf("Enter the key: ");
scanf("%d", &key);
decrypt(cipher, key);
return 0;
}
```
在这个示例代码中,我们使用了一个简单的希尔密码算法来加密和解密消息。该算法基于一个密钥,通过乘以消息中每个字母的位置来加密消息。我们还使用了模运算来确保加密后的字母仍然是字母,并且在解密时使用了密钥的逆元来还原原始消息。
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)