帮我按这个用c++写一个playfair加密代码
时间: 2023-05-24 17:01:04 浏览: 94
当然可以,以下是你想要的代码:
```c
#include <stdio.h>
#include <string.h>
int find_pos(char c, char key[5][5])
{
int i, j;
for(i = 0; i < 5; i++)
{
for(j = 0; j < 5; j++)
{
if(key[i][j] == c)
{
return 5 * i + j;
}
}
}
return -1;
}
void playfair_encipher(char* plaintext, char* ciphertext, char key[5][5])
{
int i;
int len = strlen(plaintext);
for(i = 0; i < len; i += 2)
{
char c1 = plaintext[i];
char c2 = (i + 1 < len) ? plaintext[i+1] : 'x';
if(c1 == c2) c2 = 'x';
int pos1 = find_pos(c1, key);
int pos2 = find_pos(c2, key);
int row1 = pos1 / 5;
int col1 = pos1 % 5;
int row2 = pos2 / 5;
int col2 = pos2 % 5;
if(row1 == row2)
{
ciphertext[i] = key[row1][(col1+1)%5];
ciphertext[i+1] = key[row2][(col2+1)%5];
}
else if(col1 == col2)
{
ciphertext[i] = key[(row1+1)%5][col1];
ciphertext[i+1] = key[(row2+1)%5][col2];
}
else
{
ciphertext[i] = key[row1][col2];
ciphertext[i+1] = key[row2][col1];
}
}
ciphertext[i] = '\0';
}
int main()
{
char plaintext[] = "hello world";
char key[5][5] = {
{'p', 'l', 'a', 'y', 'f'},
{'i', 'r', 'e', 'x', 'm'},
{'b', 'c', 'd', 'g', 'h'},
{'k', 'n', 'o', 'q', 's'},
{'t', 'u', 'v', 'w', 'z'}
};
char ciphertext[100];
playfair_encipher(plaintext, ciphertext, key);
printf("plaintext: %s\n", plaintext);
printf("ciphertext: %s\n", ciphertext);
return 0;
}
```
阅读全文