信息安全基础实验报告——凯撒密码(java)
一、 设计流程图
二、 源代码
import java.util.*;
publicclass Test {
publicstaticvoid main(String[] args) {
char[] s1 = newchar[1000];
int i,n,a;
for(i=65;i<91;i++)
{
s1[i]=(char)i;
}
Scanner scanner = new Scanner(System.in);
System.out.printf("输入明文:");
String s = scanner.next();
a=s.length();
System.out.printf("请设置偏移量:");
n=scanner.nextInt();
char[] m=newchar[a];
for(i=0;i<a;i++){
m[i]=s.charAt(i);
int q=n%26;
int p=m[i];
if((p+q)<91){
m[i]=s1[p+q];}
else {
m[i]=s1[p-26+q];}
System.out.print(m[i]);
}
}
}
三、 运行截图
运行,准备输入明文(英文大写):
输入要设置的偏移量值:
设置偏移量为3:
设置偏移量为10:
设置偏移量为36:
第二篇:凯撒加密器 java源代码
凯撒加密器
1、功能要求
开发基于控制台的凯撒加密系统。具体要求如下:
(1)根据用户的选择从控制台待加密或解密的字符串。如图-2和图-3所示。
(2)根据凯撒加密法,对字符串进行加密或解密。
(3)加密或解密完成后,把结果输出到控制台。如图-4和图-5所示。
图-2 操作选择界面
图-3 输入字符串界面
图-4 加密后的界面
图-5 解密后的界面
2、类的设计
该系统中必须包括三个类。
输入台控制类(Swither)
Encryption(字符串加密类)
Decryption(字符串解密类)
3、具体要求及推荐实现步骤
1、创建控制台控制类Switcher,用于和操作者交互。
2、开发加密类Encryption,使用凯撒加密法对字符串加密,并把加密后的结果返回给Switcher。
3、开发解密类Dncryption,使用凯撒加密法对字符串解密,并把解密后的结果返回给Switcher。
凯撒加密法,就是将字母表中的每个字母向后移动3位,比如a被替换成d,b被替换成f,以此类推。字母表的最后三位xyz,会被替换为abc。比如hello,加密之后是khoor.对于拉丁字母之外的其他字符,一律不加密。
java源代码:
import java.util.Scanner;
public class Test {
void mj(){
Scanner in = new Scanner(System.in);
System.out.print("请选择操作(1.加密 2.解密):");
int n=in.nextInt();
if(n == 1){
System.out.print("请输入待加密的字符串:");
String str = in.next();
String jm="";
int key = 3;
for(int i = 0;i < str.length();i++){
char c = str.charAt(i);
if(c >= 'a'&&c <= 'z'){
if(c>='x'&&c<='z'){
c-=26;
c+=key;
}
else{
c+=key;
}
}
else if(c >= 'A'&&c <= 'Z'){
if(c>='X'&&c<='Z'){
c-=26;
c+=key;
}
else{
c+=key;
}
}
jm += c;
}
System.out.print("加密后的字符串是:"+jm);
System.out.print("\n输入任意建继续,0结束程序:");
n=in.nextInt();
if(n==0){
System.out.print(" 谢谢使用本程序,欢迎再次使用!");
}
else{
this.mj();
}
}
else if(n == 2){
System.out.print("请输入待解密的字符串:");
String str = in.next();
String jm="";
int key = -3;
for(int i = 0;i < str.length();i++){
char c = str.charAt(i);
if(c >= 'a'&&c <= 'z'){
if(c>='a'&&c<='c'){
c+=26;
c+=key;
}
else{
c+=key;
}
}
else if(c >= 'A'&&c <= 'Z'){
if(c>='A'&&c<='C'){
c+=26;
c+=key;
}
else{
c+=key;
}
}
jm += c;
}
System.out.println("解密后的字符串:"+jm);
System.out.print("\n输入任意建继续,0结束程序:");
n=in.nextInt();
if(n==0){
System.out.print(" 谢谢使用本程序,欢迎再次使用!");
}
else{
this.mj();
}
}
else{
System.out.print("请输入1或2,其他字符无效!\n输入任意建继续,0结束程序:");
n=in.nextInt();
if(n==0){
System.out.print(" 谢谢使用本程序,欢迎再次使用!");
}
else{
this.mj();
}
}
}
public static void main(String[] args) {
Test mj=new Test();
System.out.println("******欢迎使用凯撒加密器******");
mj.mj();
}
}