|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 spy 于 2015-3-28 00:05 编辑
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/timeb.h>
struct Node
{
char data;
struct Node *next;
};
struct TableNode
{
char data;
struct TableNode *prior, *next;
};
void CreateTable(struct TableNode **);
void CreateText(struct Node **);
void Encrypt(struct Node *, struct TableNode *, struct Node **);
void ShowKey(struct Node *);
void ShowText(struct Node *);
void Decrypt(struct Node *, struct TableNode *, struct Node *);
void main()
{
struct Node *head=NULL, *key=NULL;
struct TableNode *table=NULL;
CreateTable(&table);
printf("请输入要加密的明文(字母格式),以0结束输入:\n");
CreateText(&head);
Encrypt(head, table, &key);
printf("密钥:\n");
ShowKey(key);
printf("加密后的密文: \n");
ShowText(head);
Decrypt(head, table, key);
printf("解密后的明文: \n");
ShowText(head);
}
void CreateTable(struct TableNode **table)
{
struct TableNode *p, *q;
char ch;
*table = (struct TableNode *)malloc(sizeof(struct TableNode));
p = *table;
for(ch='a'; ch<='z'; ch++)
{
q = (struct TableNode *)malloc(sizeof(struct TableNode));
q->data = ch;
p->next = q;
q->prior = p;
p = q;
}
p->next = (*table)->next;
(*table)->next->prior = p;
}
void CreateText(struct Node **head)
{
struct Node *p, *q;
char ch;
while((ch=getchar())==10);
*head = (struct Node *)malloc(sizeof(struct Node));
p = *head;
while(ch!='0')
{
q = (struct Node *)malloc(sizeof(struct Node));
q->data = ch;
p->next = q;
p = q;
fflush(stdin);
while((ch=getchar())==10);
}
putchar('\n');
p->next = NULL;
}
void Encrypt(struct Node *head, struct TableNode *table, struct Node **key)
{
struct Node *p=head->next, *r, *s;
struct TableNode *q;
struct timeb timebuffer;
int n;
q = table->next;
*key = (struct Node *)malloc(sizeof(struct Node));
r = *key;
ftime(&timebuffer);
srand( (unsigned int)timebuffer.millitm );
while(p!=NULL)
{
s = (struct Node *)malloc(sizeof(struct Node));
s->data = rand()%100;
n = (s->data)%26;
while(q->data!=p->data)
{
q = q->next;
}
while(n--)
{
q = q->next;
}
p->data = q->data;
r->next = s;
r = s;
p = p->next;
}
r->next = NULL;
}
void Decrypt(struct Node *head, struct TableNode *table, struct Node *key)
{
struct Node *p=head->next, *r=key->next;
struct TableNode *q=table->next;
int n;
while(p!=NULL)
{
while(q->data!=p->data)
{
q = q->next;
}
n = (r->data)%26;
while(n--)
{
q = q->prior;
}
p->data = q->data;
p = p->next;
r = r->next;
}
}
void ShowKey(struct Node *key)
{
struct Node *p = key->next;
while(p!=NULL)
{
printf("%2d ", p->data);
p = p->next;
}
printf("\n\n");
}
void ShowText(struct Node *head)
{
struct Node *p = head->next;
while(p!=NULL)
{
printf("%2c ", p->data);
p = p->next;
}
printf("\n\n");
}
|
|