本文实例为大家分享了java实现仿射密码加密解密的具体代码,供大家参考,具体内容如下
加密:将明文转化为对应的数字,如 ‘a'-> 0, ‘b'->1,…,'1'->26,'2'->27,…然后将数字进行仿射运算,求取出来的数字再转化为字符。即 密文=(k1*明文+k2)mod36
解密:密文转化为对应数字,然后进行仿射的逆运算,得到对应数字,然后将其转化为字符明文。解密 k3是k1的乘法逆元
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
import java.util.scanner;
public class affine{
public static void main(string[] args) {
char [] form = { 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' , '0'
, '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' };
scanner sc = new scanner(system.in);
system.out.println( "请输入待加密的明文:" );
string mingwen = sc.nextline();
mingwen=mingwen.touppercase(); //将输入的明文全部大写
final int k1 = 103 ;
final int k2 = 103 ;
final int k3 = 31 ;
int [] ciphernum= new int [mingwen.length()]; //用来存储数字化的密文
encryption(mingwen,form,k1,k2,ciphernum);
decryption(form,mingwen,k2,k3,ciphernum);
}
public static void encryption(string mingwen, char [] form, int k1, int k2, int [] ciphernum){
//第一步:将明文存入数组
char [] pla= new char [mingwen.length()];
for ( int i = 0 ; i <mingwen.length() ; i++) {
pla[i]=mingwen.charat(i);
} //已将明文存入字符数组pla中
//第二步:通过脚标找到明文中每个字符对应的数,参与加密运算
int [] mingwennumber= new int [pla.length];
for ( int i = 0 ; i <pla.length ; i++) {
for ( int j = 0 ; j <form.length ; j++) {
if (form[j]==pla[i]) {
mingwennumber[i] = j;
}
}
}
//通过脚标将明文全部转化为数字
char [] cipher = new char [mingwen.length()]; //cipher密码数组 用来存储密文
for ( int i = 0 ; i <mingwen.length() ; i++) {
int a= math.floormod((k1*mingwennumber[i]+k2), 36 );
ciphernum[i]=a;
cipher[i]=form[a];
//计算密文并存入数组中
}
system.out.println( "加密结果是:" );
system.out.println(cipher);
}
public static void decryption( char [] form,string mingwen, int k2, int k3, int [] ciphernum){
char [] jiemi= new char [mingwen.length()];
for ( int i = 0 ;i<mingwen.length();i++){
jiemi[i]=form[math.floormod(k3*(ciphernum[i]-k2), 36 )];
}
system.out.println( "解密结果是:" );
system.out.println(jiemi);
}
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/rtx_2080/article/details/86523035