#include<iostream>
using namespace std
#define MINCHAR 32
#define CHARSUM 94
char table[CHARSUM][CHARSUM]
bool Init()
bool Encode(char* key, char* source, char* dest)
bool Dncode(char* key, char* source, char* dest)
int main()
{
if(!Init())
{
cout <<"初始化错误!" <<endl
return 1
}
char key[256]
char str1[256]
char str2[256]
int operation
while(1)
{
do
{
cout <<"请选择一个 *** 作:1. 加密; 2. 解密; -1. 退出\n"
cin >>operation
}while(operation != -1 &&operation != 1 &&operation != 2)
if(operation == -1)
return 0
else if(operation == 1)//加密
{
cin >>key
cout <<"请输入待加密字符串:"
cin >>str1
Encode(key, str1, str2)
cout <<"加密后的字符串:" <<str2 <<endl
}
else if(operation == 2)//解密
{
cout <<"请输入密钥:"
cin >>key
cout <<"请输入待解密字符串:"
cin >>str1
Dncode(key, str1, str2)
cout <<"解陆段密后的字符串:" <<str2 <<endl
}
cout <<endl
}
return 0
}
// 初始化维吉尼亚方阵
bool Init()
{
int i, j
for(i = 0i <CHARSUMi++)
{
for(j = 0j <CHARSUMj++)
{
table[i][j] = MINCHAR + (i + j) % CHARSUM
}
}
return true
}
// 加密
// key:密钥
// source:待加密的字符串
// dest:经过加密后的字符串
bool Encode(char* key, char* source, char* dest)
{
char* tempSource = source
char* tempKey = key
char* tempDest = dest
do
{
*tempDest = table[(*tempKey) - MINCHAR][(*tempSource) - MINCHAR]
tempDest++
if(!(*(++tempKey)))
tempKey = key
}while(*tempSource++)
dest[strlen(source)] = 0
return true
}
// 解密
// key:密钥
// source:待解密的字符串
// dest:经过解密后的字符串
bool Dncode(char* key, char* source, char* dest)
{
char* tempSource = source
char* tempKey = key
char* tempDest = dest
char offset
do
{
offset = (*tempSource) - (*tempKey)
offset = offset >= 0 ? offset : offset + CHARSUM
*tempDest = MINCHAR + offset
tempDest++
if(!(*(++tempKey)))
tempKey = key
}while(*++tempSource)
dest[strlen(source)] = 0
return true
}
#include <stdlib.h>#include <stdio.h>
#include <string.h>
#define N 10000
void function(char message[],char key[],int mode) //加解密函数
int main()
{
int choose
char m[N],key[N]
printf("维吉尼亚加密,请输入1;解密,请输入2:\n")
scanf("%d",&choose)
getchar()
if (choose == 1 || choose == 2)
{
if (choose == 1)
printf("输入明文:\n")
if (choose == 2)
printf("输入密文:\n")
gets(m)
printf("输亮闷入密钥:\n")
gets(key)
function(m,key,choose)
}
else
printf("输入错误!\n")
return 0
}
void function(char message[],char key[],int mode) //加解密函数
{
int i, j = 0 //j控制key的轮回
int len_k = strlen(key) //密钥长度
char s[N]
for(i=0message[i]!='\0'i++)
{
if(message[i] == 32)//判断空格
s[i]=' '
else
{
if (mode == 1)
s[i]=(int(message[i]-'a')+int(key[j%len_k]-'a'))%26+97
if (mode == 2)
s[i]=(int(message[i]-'a')-int(key[j%len_k]-'a')+26)%26+97
j++
}
printf("%c",s[i])
}
printf("\n")
}
gets(l)//不加这句M就输入不了为什么?
是因为没有这句的话,喊键谈按的回车键就输成m了。
连用两个输入语句时,需要考虑回郑碰车键,就像我代码里的getchar()。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)