仿射密码
import java.util.Scanner;
public class Affine {
public static final int n = 26;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入密钥k1:");
int k1 = input.nextInt();
System.out.println("请输入密钥k2:");
int k2 = input.nextInt();
System.out.println("[1 加密][2 解密],请选择一个");
Scanner c = new Scanner(System.in);
String s1 = c.nextLine();
if (s1.equalsIgnoreCase("1")) {
System.out.println("请输入明文:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(Encryption(k1, k2, s));
}
else if (s1.equalsIgnoreCase("2")) {
System.out.println("请输入密文:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(Decrypt(k1, k2, s));
}
}
public static String Encryption(int k1, int k2, String express){
String express2 = express.toLowerCase().replaceAll(" ", "");
char[] expressChar = express2.toCharArray();
int[] jiamiChar = new int[express2.length()];
for (int i=0;i<express2.length();i++){
jiamiChar[i] = ((expressChar[i] - 97) * k1 + k2) % n;
}
StringBuffer miwen = new StringBuffer();
for(int j=0;j<jiamiChar.length;j++){
miwen = miwen.append((char)(jiamiChar[j] + 65));
}
return miwen.toString();
}
public static String Decrypt(int k1, int k2, String ciphertext){
int k3 = 0;
for (int i = 2;;i++){
if((i*k1) % n == 1){
k3 = i;
break;
}
}
StringBuffer mingwen = new StringBuffer();
for (int j=0;j<ciphertext.length();j++){
int c = ((k3 * (ciphertext.charAt(j) - 65 - k2))) % 26;
if (c < 0){
c = c + 26;
}
mingwen.append((char)( c + 65));
}
return mingwen.toString();
}
}