维吉尼亚加密算法

维吉尼亚加密算法

这个算法思想就是:当我们随机输入的要加密的一串明文,随机生成一个key,然后将对应的明文移动key位。最后得到加密后的密文。例如“HELLO”,随机生成KEY架设是‘2’,‘3’,‘4’,‘-1’,‘0’。那么得到的密文就是“JHPKO”。这里的KEY可正可负。本程序通过srand()和time()函数来生成伪随机数模拟KEY。代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define ERROR 0
#define OK 1
typedef char Elemtype;
typedef int Status;
int length = 0;
Status i = 0;
Elemtype ch=0;
typedef struct node
{
	Elemtype data;
	struct node *next;
	struct node *pre;
}Node;//定义一个双链表
Status InitialDList(Node *head,int length)//初始化循环双链表
{
	Node *p = head;
	Node *q = NULL;
	int i = 0;
	for (i=0;i< length;i++)
	{
		q = (Node *)malloc(sizeof(Node));
		if (q==NULL)
		{
			return ERROR;
		}
		q->data = 'A' + i;//此链表包含26个大写英文字母
		q->next = p->next;
		q->pre = p;
		p->next = q;
		p = q;
	}
	p->next = head->next;
	head->next->pre = p;
	return OK;
}
Elemtype Paixu(Node **head,int i, Elemtype ch)
{
	i = i % 26;
	//Node *curent;
	*head = (*head)->next;
	while ((*head)->data!=ch)//在此链表中找到对应的要进行加密的明文
	{
		*head = (*head)->next;
	}
	if (i>0)//如果是正向移位
	{
		while(i > 0){
			*head = (*head)->next;
			i--;
		} 
	}
	else {//反之反向移位
		while(i < 0){
			*head = (*head)->pre;
			i++;
		}
	}
	return (*head)->data;//返回加密后的数据
}
void Print(Node *head,int length)//一个打印函数
{
	for(int i=0;i< length;i++)
	{
		printf("%c\n",head->data);
		head = head->next;
	}
}
void Vigenere(char *str1,int i,char *str2,int *key,Node *head)//对于str1进行维吉尼亚加密
{
	srand((unsigned)time(NULL));
	int j = 0;
	for (j=0;j<i;j++)
	{
		*(str2+j)= Paixu(&head, rand(),*(str1 + j));//生成KEY,将str1数组中的数进行KEY位移位
		*(key+j) = rand();//把KEY保存起来
		printf("%d\n", *(key + j));
	}
}
int main(void)
{
	char str1[100] = {"HLLOWORD"};//明文
	char str2[100] = { 0 };
	int key[100] = {0};
	Node *head = (Node *)malloc(sizeof(Node));
	length = 26;
	i=InitialDList(head,length);//初始化26个字母的循环双链表
	if (i== ERROR)
	{
		printf("ERROR\n");
	}
	else {
		printf("OK\n");
	}
	Vigenere(str1,strlen(str1),str2,key,head);//维吉尼亚加密
	printf("%s\n",str2);
	//Print(head,length);
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值