【密码学 Vigenere】Vigenere密码C语言实现

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);
}
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值