1. C语言 简单对字母进行加密
1、在我们的编辑页面输入以下代码。
2. C语言题编程实现对键盘输入的大写英文字母进行加密。字母
#include<stdio.h>
#include<ctype.h>
intmain()
{inti;
chars[200];
gets(s);
for(i=0;s[i];i++)
if(isalpha(s[i]))
{s[i]+=3;
if(s[i]%0x20>26)s[i]-=26;
}
puts(s);
return0;
}
3. C语言设计一个用简单的加密程序,即用字母替换的方式加密,程序运行中发现问题,求解释。
原因就是char是1个字节的,你不能超过127(hi,楼上的,不是128哦,是-128~127不要误人子弟),你到后面的vwxyz已经溢出,所以是乱码。
我的解决方法就很简单,就是换成unsigned char 数组,这样取值范围增大到(0~255)就可以了,既简单又不破坏原有的结构
还有
else if(str[i]<'a')
{
str[i]+=26;
}
这句话是废话,可以删掉
我修改过的版本
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void EncodeString(unsigned char *str,int key)
{
int length,i;//length为传入字符串长度,i用作循环计数器
length=strlen(str);
for(i=0;i<length;i++)//对字符串中的每个字符依次进行加密
{
if(isupper(str[i]))//对大写字母加密
{
str[i]+=key%26;
if(str[i]>'Z')
{
str[i]-=26;
}
}
else if(islower(str[i]))//对小写字母加密
{
str[i]+=key%26;
if(str[i]>'z')
{
str[i]-=26;
}
}
}
}
void main()
{
unsigned char arr[50],buffer;//arr[50]用来接收字符串信息,buffer用来接收缓冲区中的回车
int key;//key为加密秘钥
printf("This program encodes messages using a cyclic cipher.\n");
printf("To stop, enter 0 as the key.\n");
while(1)//程序一直运行,直到输入密钥0为止
{
printf("Enter the key: ");
scanf("%d",&key);
scanf("%c",&buffer);
if(0==key)
{
break;//输入密钥为0,则退出程序
}
printf("Enter a message: ");
scanf("%s",arr);
scanf("%c",&buffer);
EncodeString(arr,key);
printf("Encoded message: %s\n",arr);
}
}
4. 用循环语句输出26个大写字母加序数5循环加密
下面输出 26个大写字母 加序数5循环加密
每行输出: 原字母,加密后的字母,加密后的一个byte里存放的十六进制。
#include <stdio.h>
int main()
{
int i;
for (i=0;i<26;i++)
printf("%c %c %#x\n",'A'+i,'A'+(i+5)%26,'A'+(i+5)%26);
return 0;
}
A F 0x46
B G 0x47
C H 0x48
D I 0x49
E J 0x4a
F K 0x4b
....
U Z 0x5a
V A 0x41
W B 0x42
X C 0x43
Y D 0x44
Z E 0x45
5. C语言对字符进行加密
if(e>='A'&&e<='W')//
e+=3;
elseif(e>='X'&&e<='Z')
e-=23;
else
{
...//donotencryptordosomethingelse
}
6. C++ 编写一个程序,将一个包含大小写字母的纯字母明文串转换为纯大写字母的加密串输出。
#include <iostream>
using namespace std;
int i;
void main(void)
{
void process(char s[],char s1[]);
void show(char s[],char s1[]);
char s[20];
char s1[20];
process(s,s1);
show(s,s1);
}
void process(char s[],char s1[])
{
i=0;
while ((s[i]=getchar())!='\n'&&i<20)
{
if (s[i]>='A' && s[i]<='Z')
{
s1[i]=s[i]+3;
if (s1[i]>'Z' && s1[i]<='Z'+3)
s1[i]=s1[i]-26;
}
else
{
s1[i]=s[i]-29;
if (s1[i]>'Z'&& s1[i]<='Z'+3)
s1[i]=s1[i]-26;
}
i++;
}
}
void show(char s[],char s1[])
{
int j;
for(j=0; j<=i; j++)
cout<<s[j];
cout<<endl;
for(j=0; j<=i; j++)
cout<<s1[j];
cout<<endl;
}
7. c语言对大写英文字母加密
#include <stdio.h>
#include <string.h>
int main()
{
char passwd[100],encrypted[100];
int i,j,k,t,move;
while(1)
{
printf("Enter message to be encrypted:");
gets(passwd);
move=3;
for(i=0; i<strlen(passwd); i++)
{
if(passwd[i] >= 'A' && passwd[i] <= 'Z')
{
passwd[i] = ((passwd[i]-'A')+move)%26+'A';
} else if(passwd[i] >= 'a' && passwd[i] <= 'z')
{
passwd[i] = ((passwd[i]-'a')+move)%26+'a';
}
}
printf("%s",passwd);
printf("\n");
}
return 0;
}
这道题实际上就是C语言版的凯撒加密(字母往后面移动1-25之间的任意一位数)