维吉尼亚加密算法
这个算法思想就是:当我们随机输入的要加密的一串明文,随机生成一个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);
}