凯撒加密(后偏移)

题目描述

为了防止信息被别人轻易窃取,需要把电码明文通过加密方式变换成为密文。输入一个以回车符为结束标志的字符串(少于80个字符),再输入一个正整数offset,用凯撒密码将其加密后输出。恺撒密码是一种简单的替换加密技术,将明文中的所有字母都在字母表上向后偏移offset位后被替换成密文。 例如,当偏移量offset是2时,表示所有的字母被向后移动 2 位后的字母替换,即所有的字母 A 将被替换成C,字母 B 将变为 D,…,字母 X 变成 Z,字母 Y 则变为 A,字母 Z 变为 B。

输入格式:

输入第一行给出一个以回车结束的非空字符串(少于80个字符);第二行输入一个正整数offset。

输出格式:

输出加密后的结果字符串。 如果输入的offset不在有效范围内,则在一行中输出"Invalid."。

输入样例1:

在这里给出一组输入。例如:

Hello Hangzhou
2

结尾无空行

输出样例1:

在这里给出相应的输出。例如:

Jgnnq Jcpibjqw

结尾无空行

输入样例2:

在这里给出一组输入。例如:

z=x+y
-1

结尾无空行

输出样例2:

Invalid.

结尾无空行

代码

#include<stdio.h>
#include<string.h>

char str[1000];
int offset;

int main()
{
	gets(str);
	scanf("%d",&offset);
	
	if(offset<=0)
	{
		printf("Invalid.");
		return 0;
	}
	
	for(int i=0;i<strlen(str);i++)
	{
		if(str[i]>='a'&&str[i]<='z') printf("%c",(str[i]-'a'+offset)%26+'a');
		else if(str[i]>='A'&&str[i]<='Z') printf("%c",(str[i]-'A'+offset)%26+'A');
		else printf("%c",str[i]);
	}
		
	
	return 0;
}

c语言编写,欢迎扔板砖 //移位算法 #include #include #define SIZE 50 int main() { //i 用于计数输入个数,j 为临时变量, plain 存放明文, cipher 存放密文,decryption存放解密后文本,fpp 为明文文件指针,fpc 为密文文件指针 int i,j; char plain[SIZE],cipher[SIZE],decryption[SIZE],ciphertext[SIZE]; FILE * fpp,* fpc,* fpd; //加密 //建立新的明文TXT文件 printf("Caesar algorithm\n"); if((fpp=fopen("plain.txt","w+"))==NULL) { printf("creat new plain file error!\n"); exit(0); } //输入明文 printf("input plain alphabet:\n"); i=0; scanf("%c",&plain[i]); while(plain[i]!='\n'&&i<SIZE) { i++; scanf("%c",&plain[i]); } printf("success input %d characters\n",i); //将明文转存到文件中 for(j=0;j<i;j++) { if(fwrite(&plain[j],sizeof(char),1,fpp)!=1) { printf("saving plain file error!\n"); exit(0); } } printf("success saving plain text!\n"); //加密 for(j=0;j<i;j++) { cipher[j]=plain[j]+3; if(cipher[j]99) { printf("cipher %d = %c\n",j,cipher[j]); } else if(cipher[j]>122) { cipher[j]=cipher[j]%122+96; printf("cipher %d = %c\n",j,cipher[j]); } else if(cipher[j]>90) { cipher[j]=cipher[j]%90+64; printf("cipher %d = %c\n",j,cipher[j]); } else { printf("cipher %d = %c\n",j,cipher[j]); } } //建立密文文件 if((fpc=fopen("cipher.txt","w+"))==NULL) { printf("create new cipher file error!"); exit(0); } for(j=0;j<i;j++) { if(fwrite(&cipher[j],sizeof(char),1,fpc)!=1) { printf("saving cipher file error!"); exit(0); } } printf("success saving cipher file!"); printf("\n"); //解密 printf("input ciphertext alphabet:\n"); i=0; scanf("%c",&ciphertext[i]); while(ciphertext[i]!='\n'&&i<SIZE) { i++; scanf("%c",&ciphertext[i]); } for(j=0;j<i;j++) { decryption[j]=ciphertext[j]-3; if(decryption[j]90&&decryption[j]<97) { decryption[j]=123-(97-decryption[j]); printf("character %d = %c\n",j,decryption[j]); } else {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MRWHH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值