c代码实现密码学仿射变换的加解密
时间: 2024-02-27 14:29:31 浏览: 91
加密:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char plain_text[100], cipher_text[100];
int key_a, key_b, i;
printf("Enter the plaintext: ");
gets(plain_text);
printf("Enter key a: ");
scanf("%d", &key_a);
printf("Enter key b: ");
scanf("%d", &key_b);
for (i = 0; plain_text[i] != '\0'; i++) {
if (isalpha(plain_text[i])) {
if (isupper(plain_text[i])) {
cipher_text[i] = ((key_a * (plain_text[i] - 'A') + key_b) % 26) + 'A';
} else {
cipher_text[i] = ((key_a * (plain_text[i] - 'a') + key_b) % 26) + 'a';
}
} else {
cipher_text[i] = plain_text[i];
}
}
cipher_text[i] = '\0';
printf("Cipher text: %s\n", cipher_text);
return 0;
}
```
解密:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char plain_text[100], cipher_text[100];
int key_a, key_b, i, multiplicative_inverse;
printf("Enter the ciphertext: ");
gets(cipher_text);
printf("Enter key a: ");
scanf("%d", &key_a);
printf("Enter key b: ");
scanf("%d", &key_b);
for (i = 0; cipher_text[i] != '\0'; i++) {
if (isalpha(cipher_text[i])) {
if (isupper(cipher_text[i])) {
multiplicative_inverse = 1;
while ((key_a * multiplicative_inverse) % 26 != 1) {
multiplicative_inverse++;
}
plain_text[i] = ((multiplicative_inverse * (cipher_text[i] - 'A' - key_b + 26)) % 26) + 'A';
} else {
multiplicative_inverse = 1;
while ((key_a * multiplicative_inverse) % 26 != 1) {
multiplicative_inverse++;
}
plain_text[i] = ((multiplicative_inverse * (cipher_text[i] - 'a' - key_b + 26)) % 26) + 'a';
}
} else {
plain_text[i] = cipher_text[i];
}
}
plain_text[i] = '\0';
printf("Plain text: %s\n", plain_text);
return 0;
}
```
阅读全文