1 import java.util.*; 2 public class FangSheMiMa{ 3 public static void main (String args[]){ 4 System.out.println("请依次输入k1,k2,字母数值"); 5 Scanner scan=new Scanner (System .in); 6 int k1=scan.nextInt(); 7 int k2=scan.nextInt(); 8 int letter=scan.nextInt(); 9 10 if (gcd(k1,26)!=1){ 11 System.out.println("输入的密匙不符合要求!"); 12 } 13 else{ 14 System .out.println("请选择操作"); 15 System .out.println("1:加密 "); 16 System .out.println("2:解密 "); 17 int t=scan.nextInt(); 18 switch (t ){ 19 case 1: 20 System .out.println("明文:"+ letter+" "+jiaMi(letter,k1,k2)); 21 System .out.println(" "); 22 break; 23 case 2: 24 System .out.println("密文:"+letter+" "+jieMi(letter,k1,k2)); 25 System .out.println(" "); 26 break; 27 28 } 29 } 30 } 31 /* }*/ 32 33 34 private static int gcd(int k1, int n) {// gcd(k1,n)=1为仿射密码具有可逆性的条件 35 // TODO Auto-generated method stub 36 int k=0;// 37 do{ 38 k=k1%n; 39 k1=n; 40 n=k; 41 }while(k!=0); 42 return k1; 43 } 44 //辗转消除求最大公约数 45 private static int ni(int k1,int n){ 46 int i=1; 47 while(k1*i%n!=1){ 48 i++; 49 } 50 return i; 51 } 52 53 //加密算法 54 private static String jiaMi(int plainText, int k1, int k2) { 55 // TODO Auto-generated method stub 56 //String PlainText=""; 57 int encryperText=0; 58 encryperText=(k1*plainText+k2)%26; 59 String result ="密匙:<"+k1+","+k2+"> "+" 密文:"+encryperText; 60 return result; 61 } 62 63 64 65 //解密算法 66 private static String jieMi(int encrypherText, int k1, int k2) { 67 // TODO Auto-generated method stub 68 int PlainText=0; 69 String result=""; 70 71 // k3(m-t)%26=c 72 PlainText=(ni(k1,26)*(encrypherText-k2))%26; 73 result ="密匙:<"+k1+","+k2+"> "+" 明文:"+PlainText; 74 return result; 75 76 } 77 }