Java版 凯撒密码 加密、解密、暴力破解
用Java实现凯撒密码的 ‘加密’ 和 ‘解密’ 工作
代码实现如下:
代码片
package com.hellow.demo;
import java.util.Scanner;
// 凯撒密码
public class Caesar {
public static void main(String[] args) {
int tpm;
System.out.println("1.加密 2.解密 3.暴力破解\n 请选择模式:");
Scanner sc = new Scanner(System.in);
tpm = sc.nextInt();
if (tpm == 1) {
System.out.println("请输入明文:");
Scanner sc1 = new Scanner(System.in);
String s = sc1.nextLine();
System.out.println("请输入密钥:");
Scanner sc2 = new Scanner(System.in);
int key = sc2.nextInt();
//调用加密函数
Encryption(s, key);
} else if (tpm == 2) {
System.out.println("请输入密文:");
Scanner sc1 = new Scanner(System.in);
String pwd = sc1.nextLine();
System.out.println("请输入密钥:");
Scanner sc2 = new Scanner(System.in);
int key = sc2.nextInt();
//调用解密函数
Decrypt(pwd, key);
} else if (tpm == 3) {
System.out.println("请输入密文:");
Scanner sc1 = new Scanner(System.in);
String pwd = sc1.nextLine();
//调用解密函数
for (int i = 1; i <= 26; i++) {
int key = i;
Decrypt_attack(pwd, key);
System.out.println("(密钥: " + key + ")\n");
}
} else {
System.out.println("模式选择错误");
}
System.out.println("end");
}
//加密函数 Encryption
public static void Encryption(String str, int n) {
String string = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
c += n % 26;
if (c < 'a') {
c += 26;
}
if (c > 'z') {
c -= 26;
}
} else if (c >= 'A' && c <= 'Z') {
c += n % 26;
if (c < 'A') {
c += 26;
}
if (c > 'Z') {
c -= 26;
}
}
string += c;
}
System.out.println(string);
}
//解密函数 Decrypt
public static void Decrypt(String str, int n) {
// int k=Integer.parseInt("-"+n);
String string = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
c -= n % 26;
if (c < 'a') {
c += 26;
}
if (c > 'z') {
c -= 26;
}
} else if (c >= 'A' && c <= 'Z') {
c -= n % 26;
if (c < 'A') {
c += 26;
}
if (c > 'Z') {
c -= 26;
}
}
string += c;
}
System.out.println(string);
}
//暴力破解函数 Decrypt_attack
public static void Decrypt_attack(String str, int n) {
// int k=Integer.parseInt("-"+n);
String string = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 'a' && c <= 'z') {
c -= n % 26;
if (c < 'a') {
c += 26;
}
if (c > 'z') {
c -= 26;
}
} else if (c >= 'A' && c <= 'Z') {
c -= n % 26;
if (c < 'A') {
c += 26;
}
if (c > 'Z') {
c -= 26;
}
}
string += c;
}
System.out.println(string);
// hellow
// khoorz
// 3
// see you tomorrow
// vhh brx wrpruurz
// 3
// 密文: PELCGBTENCUL
// 真实密钥:13
// 明文: CRYPTOGRAPHY (n.密码学)
}
}