Java实现仿射变换的加密、解密、破译
package com.qul.java1;
import java.util.Scanner;
/**
* @author Dxkstart
* @create 2021-05-25 15:21
*/
public class AffineTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("1.*****加密*****");
System.out.println("2.*****解密*****");
System.out.println("3.*****破译*****");
System.out.println("4.*****退出*****");
boolean b = true;
while (b) {
System.out.println("请选择功能:");
int num = scanner.nextInt();
switch (num) {
case 1:
new Encryption().encryption();
break;
case 2:
new Decryption().decryption();
break;
case 3:
new Decode().decode();
break;
case 4:
b = false;
}
}
}
}
//加密算法
class Encryption {
String cleartext;//明文
int k1;//k1与26互为质数
int k2;
public void encryption() {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
System.out.println("请输入k1、k2:");
k1 = scanner.nextInt();
k2 = scanner.nextInt();
System.out.println("请输入明文(小写字符):");
cleartext = scanner.next();
System.out.println("密文为:");
char[] chars = cleartext.toCharArray();//String转char数组
for (int i = 0; i < chars.length; i++) {
int q = (int) chars[i];//转ACSll码 97-122
if (q != 32) {
int m = (k1 * (q - 97) + k2 % 26) % 26;
char c = (char) (m + 65);//转大写字符
System.out.print(c);
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
//解密算法
class Decryption {
String ciphertext;//密文
int k1;//k1与26互为质数
int k2;
public void decryption() {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");//可识别空格字符
System.out.println("请输入k1、k2:");
k1 = scanner.nextInt();
k2 = scanner.nextInt();
System.out.println("请输入密文(大写字符):");
ciphertext = scanner.next();
System.out.println("明文为:");
//求k1的乘法逆元素
int M;
for (M = 0; M < 26; M++) {
if ((k1 * M) % 26 == 1) {
break;
}
}
char[] chars = ciphertext.toCharArray();
for (int i = 0; i < chars.length; i++) {
int q = (int) chars[i];//转ACSll码 65-90
if (q != 32) {
int m = (M * ((q - 65 + 26) - k2)) % 26;
char c = (char) (m + 97);//转小写字符
System.out.print(c);
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
//破译算法
class Decode {
String ciphertext;//密文
int k1;//k1与26互为质数
int k2;
public void decode() {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\n");
System.out.println("请输入密文(大写字符):");
ciphertext = scanner.next();
System.out.println("明文为:");
//求k1、k2
for (k1 = 1; k1 <= 26; k1 += 2) {
if (k1 % 13 != 0) {
for (k2 = 1; k2 < 26; k2++) {
//求k1的乘法逆元素
int M;
for (M = 0; M < 26; M++) {
if ((k1 * M) % 26 == 1) {
break;
}
}
char[] chars = ciphertext.toCharArray();
for (int i = 0; i < chars.length; i++) {
int q = (int) chars[i];//转ACSll码 65-90
if (q != 32) {
int m = (M * ((q - 65 + 26) - k2)) % 26;
char c = (char) (m + 97);//转小写字符
System.out.print(c);
} else {
System.out.print(" ");
}
}
System.out.print(" ***** k1 = " + k1 + " k2= " + k2);
System.out.println();
}
}
}
}
}