Vigenere密码C语言实现
#include <Stdio.h>
#include <Conio.h>
#include <string.h>
#include <malloc.h>
#define MAX 100
static int square[27][27];
char* vigenere( char key[], char word[] );
char* anti_vigenere( char key[], char * en_word );
int main( void )
{
char key[MAX], word[MAX], *en_word;
int i, j, k, m;
for ( i = 1; i < 27; i++ )
{
for ( j = 1; j < 27; j++ )
{
square[i][j] = 63 + i + j;
if ( square[i][j] > 90 )
square[i][j] = square[i][j] - 26;
}
}
for ( k = 1; k < 27; k++ )
{
for ( m = 1; m < 27; m++ )
{
printf( "%c ", square[k][m] );
}
printf( "\n" );
}
printf( "VigenereCipher \nPlease input plain text:" );
scanf( "%s", word );
printf( "inputthe key:" );
scanf( "%s", key );
en_word = vigenere( key, word );
printf( "\nTheresult is: %s\n", en_word );
printf( "\n\tDecryption:\n" );
printf( "Theplain text is:%s\n", anti_vigenere( key, en_word ) );
getch();
return(0);
}
/*加密算法*/
char* vigenere( char key[], char word[] )
{
char *text = (char *) malloc( MAX * sizeof(char) );
int key_length = strlen( key );
int word_length = strlen( word );
int i, j, c;
for ( i = 0; i < word_length; i++ )
{
if ( (word[i] >= 65 && word[i] <= 90) || (word[i] >= 97 && word[i] <= 122) )
{
if ( word[i] >= 97 && word[i] <= 122 )
{
c = word[i] - 96;
}else {
c = word[i] - 64;
}
j = i % key_length;
text[i] = square[key[j] - 96][c];
}else text[i] = word[i];
}
text[i] = '\0';
return(text);
}
/*解密算法*/
char* anti_vigenere( char key[], char * en_word )
{
char *word = (char *) malloc( MAX * sizeof(char) );
int key_length = strlen( key );
int word_length = strlen( en_word );
int i, j, c, k, d;
for ( i = 0; i < word_length; i++ )
{
if ( en_word[i] >= 65 && en_word[i] <= 90 )
{
c = i % key_length; /*所用密钥在所在*/
k = key[c] - 96;
d = en_word[i] - square[k][1];
if ( d >= 0 )
{
word[i] = 'a' + d;
}else{
word[i] = 'z' + d + 1;
}
}else{
word[i] = en_word[i];
}
}
word[i] = '\0';
return(word);
}