当前位置:文档之家› java凯撒密码实现----完美版

java凯撒密码实现----完美版

代码:
package ning.hao;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Cryptology {
char ciphertext[];//密文
int key;
char plaintext[];//明文
StringBuffer plaintextStr;
StringBuffer ciphertextStr;
final int max=500;
Cryptology(){
key=0;
plaintextStr=new StringBuffer("");
ciphertextStr=new StringBuffer("");
}
int setKey(){
System.out.println("请输入一个Caesar密钥");
Scanner sc=new Scanner(System.in);
try{
key=sc.nextInt()%26;
}
catch(Exception e){
System.out.println("需要输入整数!");
}
return key;
}
void getPlaintext(){//获得明文
plaintext=new char[max];
for(int j=0;j<max;j++){
plaintext[j]='@';
}
int i=0;
char ch=' ';
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入明文");
try {
ch=(char) bf.read();//获得字符
while(ch!='\r'&&ch!='\n'){
if(ch>='a'&&ch<='z'||ch>='A'&&ch<='Z'||ch==' '||ch==','||ch=='.'||ch=='!'){
plaintext[i]=ch;
i++;
}
else{
System.out.println("输入不支持!!");
break;
}
try{
ch=(char) bf.read();
}
catch(IOException e1){
}
}
}
catch(IOException e){}
}
void encryption(){//加密
int temp=0;
ciphertext=new char[max];
for(int j=0;j<max;j++){
ciphertext[j]='@';
}
for(int i=0;i<plaintext.length;i++){
if(plaintext[i]!='@'){
temp=plaintext[i]+key;
if(plaintext[i]==' '||plaintext[i]==','||plaintext[i]=='.'||plaintext[i]=='!'){
ciphertext[i]=(char) (plaintext[i]);
}
if(plaintext[i]>='a'&&plaintext[i]<='z'){
if(temp>122)
ciphertext[i]=(char) (97+temp-123);
else{
ciphertext[i]=(char)temp;
}
}
if(plaintext[i]>='A'&&plaintext[i]<='Z'){
if((plaintext[i]+key)>90)
ciphertext[i]=(char)(65+temp-91);
else{
ciphertext[i]=(char)temp;
}
}
ciphertextStr.append(ciphertext[i]);
}
else{
break;
}
}
}
void deciphering(){//解密
char c=' ';
int temp=0;
for(int i=0;i<ciphertext.length;i++){
temp=ciphertext[i]-key;
if(ciphertext[i]!='@'){
if(plaintext[i]==' '||plaintext[i]==','||plaintext[i]=='.'||plaintext[i]=='!'){ c=(char)(ciphertext[i]);
}
if(ciphertext[i]>=97&&ciphertext[i]<=122){
c=(char)(temp);
if(temp<97){
c=(char)(26+temp);
}
}
if(ciphertext[i]>=65&&ciphertext[i]<=90){
c=(char)(temp);
if(temp<65){
c=(char)(26+temp);
}
}
plaintextStr.append(c);
}
else{
break;
}
}
}
void display(){
System.out.println("密文明文对比");
System.out.println("密文:"+ciphertextStr);
System.out.println("明文:"+plaintextStr);
}
}
主函数部分:
package ning.hao;
public class Complication {
public static void main(String args[]){ Cryptology cry=new Cryptology();
cry.setKey();
cry.getPlaintext();
cry.encryption();
cry.deciphering();
cry.display();
}
}
结果1:
结果2:。

相关主题