现在的位置: 首页 > 综合 > 正文

C基础/PlayFair加密

2018年05月26日 ⁄ 综合 ⁄ 共 1761字 ⁄ 字号 评论关闭

http://wenku.baidu.com/view/9a28a8070740be1e650e9a2a.html  第12题

//	playfair 加密
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
#define x 50
char MiYao[x],PassWord[x],AddPass[x],Table[5][5],Map[25]; 
bool Visit[27]={false};
char English[27]="abcdefghijklmnopqrstuvwxyz";
void Input()
{
	printf("请输入密钥:\t");	scanf("%s",MiYao);
	printf("请输入待加密密码:\t");	scanf("%s",PassWord);
}
void Fun_5x5()
{
	int count = 0,V =0;
	/*标记密钥内字符为: true*/
	for(int i=0;MiYao[i]!='\0';i++)
		if(strchr(English,MiYao[i])!=NULL)
			Visit[strchr(English,MiYao[i])-English] = true;	
	/*执行密钥矩阵操作 并标记已使用字符:true*/					
	for(int i=0;i<5;i++)
		for(int j=0;j<5;j++)
		{
			if(count<strlen(MiYao))
				Table[i][j] = MiYao[count++];
			else
			{
				while(Visit[V] != false)	V++;
				Table[i][j] = English[V];	
				Visit[V++] = true;
			}
		}
		puts("∞∞∞密钥矩阵为∞∞∞");
		for(int i=0;i<5;i++)
		{	for(int j=0;j<5;j++)
				printf("%3c",Table[i][j]);
			puts("");
		}
		puts("∞∞∞∞∞∞∞∞∞∞∞"); 
			
}
int IsVisited(char ch)
{
	return Visit[strchr(English,ch)-English];	//false 未出现过 
}
void TabletoMap()
{	int count=0;
	for(int i=0;i<5;i++)
	for(int j=0;j<5;j++)
		Map[count++]=Table[i][j];
	Map[count]='\0';
}
void Judge()
{
	int len = strlen(PassWord),i,j,k;
	memset(AddPass,0,sizeof(char)); 
	/*一对对去字母,剩下单个字母,则不变化,直接放入加密串中.*/
	if(len%2){	
		AddPass[len-1] = PassWord[len-1];
		len -=1;
	}
	/*一对中 密钥矩阵中 存在矩阵 eg.ab 先输出a同行顶点在输出b同行顶点*/
	int row1,low1,row2,low2,a1,a2;
	for(i=0;i<len;i+=2)
	{
		char c1,c2;
		c1 = PassWord[i];
		c2 = PassWord[i+1];
		/*一对中 两字母相同 无变化*/
		/*一对中 有字母不在密钥矩阵中 无变化*/
		if(c1 == c2 || ( !IsVisited(c1)||!IsVisited(c2)))
		{	AddPass[i] = c1;
			AddPass[i+1]=c2;
		}else{
			a1 = strchr(Map,c1)-Map;
			row1 = a1/5;	low1 = a1%5;
			a2 = strchr(Map,c2)-Map;
			row2 = a2/5;	low2 = a2%5;
			/*一对中 字符出现在同行或同列 简单swap字符*/
			if(row1 == row2 || low1 == low2)
			{
				AddPass[i] = c2;
				AddPass[i+1] = c1;
			}else{
				AddPass[i] = Table[row1][low2];
				AddPass[i+1] = Table[row2][low1];	
			}	
		}
	}AddPass[len+1]='\0';
	puts("加密后字符串:"); 
	puts(AddPass);
	puts("原串是:");
	puts(PassWord); 
} 
int main()
{
	Input();
	Fun_5x5();
	TabletoMap();	
	Judge();
	return 0;
} 

抱歉!评论已关闭.