您的位置:首页 > 其它

文件加密

2016-04-21 18:56 323 查看
/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:test.cpp
*作    者:徐洪祥
*完成日期:2015年6月10日
*版 本 号:v1.0
*
* 问题描述:
一个文本串可用事先给定的字母映射表进行加密。例如,设字母映射表为:
abcdefghijklmnopqrstuvwxyz
ngzqtcobmuhelkpdawxfyivrsj
则字符串“abc”被加密为“ngz”。设计一个程序exp4-4.cpp将输入的文本串进行加密后输出,然后进行解密并输出。
* 输入描述:
abcdefghijklmnopqrstuvwxyz
* 程序输出:
原码
abcdefghijklmnopqrstuvwxyz
加密
ngzqtcobmuhelkpdawxfyivrsj
解密
abcdefghijklmnopqrstuvwxyz
*/
#include <iostream>
#include <stdio.h>
#include <cstring>
#define  MaxSize 100
using namespace std;
typedef struct
{
char data[MaxSize];
int length;
} SqString;
SqString A,B; //用于存储字符映射表
SqString EnCrypt(SqString p)
{
int i=0,j;
SqString q;
while (i<p.length)
{
for (j=0; p.data[i]!=A.data[j]&&j<A.length; j++);
if (j>=A.length)            //在A串中未找到p.data[i]字母
q.data[i]=p.data[i];
else                        //在A串中找到p.data[i]字母
q.data[i]=B.data[j];
i++;
}
q.length=p.length;
return q;
}
SqString UnEncrypt(SqString q)
{
int i=0,j;
SqString p;
while (i<q.length)
{
for (j=0; q.data[i]!=B.data[j]&&j<B.length; j++);
if (j>=B.length)            //在B串中未找到q.data[i]字母
p.data[i]=q.data[i];
else                    //在B串中找到q.data[i]字母
p.data[i]=A.data[j];
i++;
}
p.length=q.length;
return p;
}
void StrAssign(SqString &s,char cstr[])
{
int i;
for(i=0; cstr[i]!='\0'; i++)
s.data[i]=cstr[i];
s.length=i;
}
void DispStr(SqString s)
{
int i;
if(s.length>0)
{
for(i=0; i<s.length; i++)
printf("%c",s.data[i]);
printf("\n");
}
}
int main()
{
SqString p,q;
char str[MaxSize];
StrAssign(A,"abcdefghijklmnopqrstuvwxyz");	//建立A串
StrAssign(B,"ngzqtcobmuhelkpdawxfyivrsj");	//建立B串
printf("输入原文串:");
gets(str);                                  //获取用户输入的原文串
StrAssign(p,str);                           //建立p串
printf("  原文串:");
DispStr(p);
q=EnCrypt(p);                               //p串加密产生q串
printf("  加密串:");
DispStr(q);
p=UnEncrypt(q);                         //q串解密产生p串
printf("  解密串:");
DispStr(p);
printf("\n");
return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: