实验目的
- 理解古典加密算法加解密原理;
- 理解流密码工作原理;
- 通过 RSA 理解非对称加密算法安全性。
实验原理
Java代码展示
package kaisa;
import java.util.Scanner;
public class Caesar {
//凯撒密码的加密解密原理
// C=(P+key)(mod 26);
// P=(C+ key_1)(mod 26);
// key_1=26-key%26
//1. 凯撒密码的加密过程
public static String encryption(String str,int offset) {
char c ;
String str1 = "" ;
for(int i = 0;i<str.length();i++) {
c = str.charAt(i);
if(c >= 'a'&& c<='z') {
c = (char)(((c-'a')+offset)%26+'a');
}else if(c >= 'A'&& c<='Z') {
c = (char)(((c-'A')+offset)%26+'A');
}else if(c >= '0'&& c<='9') {
c = (char)(((c-'0')+offset)%10+'0');
}else {
System.out.println("你输入的字符传不符合规!!!");
str1 = "";
break;
}
str1+=c;
}
return str1;
}
public static String decryption(String str,int offset) {
char c ;
String str1 = "" ;
for(int i = 0;i<str.length();i++) {
c = str.charAt(i);
if(c >= 'a'&& c<='z') {
c = (char)(((c-'a')-offset+26)%26+'a');
}else if(c >= 'A'&& c<='Z') {
c = (char)(((c-'A')-offset+26)%26+'A');
}else if(c >= '0'&& c<='9') {
c = (char)(((c-'0')-offset+10)%10+'0');
}else {
System.out.println("你输入的字符传不符合规!!!");
str1 = "";
break;
}
str1+=c;
}
return str1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Caesar caesar = new Caesar();
Scanner sc = new Scanner(System.in);
System.out.println("请选择你需要的操作:1.Caesar加密 2.Caesar解密");
int choice = sc.nextInt();
if(choice == 1) {
System.out.println("请输入要加密的内容:");
String str = sc.next();
System.out.println("请出入要偏移的量:");
int offset = sc.nextInt();
str = caesar.encryption(str, offset);
if(str != "") {
System.out.println("加密之后的结果为:"+str);
}
}
if(choice == 2) {
System.out.println("请输入要解密的内容:");
String str1 = sc.next();
System.out.println("请出入要偏移的量:");
int offset = sc.nextInt();
str1 = caesar.decryption(str1, offset);
if(str1 != "") {
System.out.println("解密之后的结果为:"+str1);
}
}
}
}
结果展示