Playfair密码C语言源代码
//PLAYFAIR.H头文件
#ifndef _PLAY_FAIR_H_
#define _PLAY_FAIR_H_
void cst_playfair_table (char *in_key);
void prnt_playfair_table ();
int playfair_encrypt (char *plain_txt, char *cipher_txt);
int playfair_decrypt (char *cipher_txt, char *plain_txt);
#endif
//PLAYFAIR.C源文件
#include "playfair.h"
#include
#include
#include
char playfair_table[5][5];
void get_x_y (char c, int *x, int *y)
{
int i, j;
for (i = 0; i < 5; ++i)
{
for (j = 0; j < 5; ++j)
{
if (playfair_table[i][j] == c)
{
*x = i; *y = j;
return;
}
}
}
}
char get_char_x_y (int x, int y)
{
if (x < 0)
x += 5;
if (y < 0)
y += 5;
return playfair_table[x % 5][y % 5];
}
void cst_playfair_table (char *in_key)
{
int i = 0, j, k;
int char_count = 0, left_ch_index = 0;
char ch, left_chs[26] = {0}, key[26] = {0};
int key_len;
strcpy (key, in_key);
key_len = strlen (key);
while (1)
{
if (key[i] == ' ')
{
for (j = i; j < key_len - 1; ++j)
key[j] = key[j + 1];
key_len--;
}
if (i == key_len)
break;
i++;
}
for (i = 0; i < 26; ++i)
{
ch = 'a' + i;
j = 0;
char_count = 0;
while (1)
{
if (key[j] == ch)
{
char_count++;
if (char_count > 1)
{
for (k = j; k < key_len -1; ++k)
key[k] = key[k + 1];
key_len--;
}
else
j++;
}
else
j++;
if (j == key_len)
break;
}
if (char_count == 0)
left_chs[left_ch_index++] = ch;
}
for (i = 0; i < left_ch_index; ++i)
key[key_len++] = left_chs[i];
for (i = 0; i < 26; ++i)
{
if (key[i] == 'z')
{
for (j = i; j < 25; ++j)
key[j] = key[j + 1];
}
}
for (i = 0; i < 5; ++i)
{
for (j = 0; j < 5; ++j)
playfair_table[i][j] = key[5 * i + j];
}
}
void prnt_playfair_table ()
{
int i, j;
printf ("Playfair Table:\n");
for (i = 0; i < 5; ++i)
{
printf ("\t");
for (j = 0; j < 5; ++j)
{
printf ("%c ", playfair_table[i][j]);
}
puts("\n");
}
}
int playfair_encrypt (char *plain_txt, char *cipher_txt)
{
in