一、实验目的及要求
通过编程实现替代密码算法——仿射密码算法,加深对古典密码体制的了解,为深入学习密码学奠定基础
二、实验设备及要求
编译软件:idea
其他软件:captfencoder
三、实验内容与步骤
仿射密码的基本思想:加法密码和乘法密码结合就构成仿射密码,仿射密码的加密和解密算法是:
C=Ek(m)=(k1m+k2)mod nC=Ek(m)=(k1m+k2)mod n
M=Dk(c)=k1(c-k2)mod nM=Dk(c)=k1(c-k2)mod n o仿射密码具有可逆性的条件是gcd(k,n)=1。当k1=1时,仿射密码变为加法密码,
当k2=0时,仿射密码变为乘法密码。o仿射密码中的**空间的大小为np(n),当n为26字母,p(n)=12,因此仿射密码的**空间为12×26=312。
附源码:
import java.util.Scanner;
public class EncryAndDecry {
public static void main(String[]
args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要加密的明文:");
String s = scanner.next();
String encryption = EncryAndDecry.encryption(s);
System.out.println("加密后的密文为:" +
encryption);
String decrypt = EncryAndDecry.decrypt(encryption);
System.out.println("解密后的明文为:" +
decrypt);
System.out.println("a:" + EncryAndDecry.getA() + " b:" + EncryAndDecry.getB() + "
a逆:" + EncryAndDecry.reciprocal());
}
private static int a;
private static int b;
static {
do {
a = (int) (Math.random() * 26);
b = (int) (Math.random() * 26);
} while
(a == 0 || b == 0 || gcd(26, a) != 1 || gcd(26, b) != 1);
}
public static int gcd(int a,
int b) {
if (b
> a) {
int c;
c = a;
a = b;
b = c;
}
return a %
b == 0 ? b : gcd(b, a %
b);
}
public static int reciprocal() {
int q = 1;
for (int i = 3; i < 26; i = i + 2) {
if ((a * i) % 26 == 1) {
q = i;
break;
}
}
return q;
}
public static String encryption(String mingWen) {
String s = "";
char[] chars = mingWen.toCharArray();
for (char
aChar : chars) {
int i =
aChar;
if (i >= 65 && i < 65 + 26) {
String i1 = (char) ((a * (i - 65) + b) % 26 + 65) + "";
s = s + i1;
} else
if (i >= 97 &&
i < 97 + 26) {
String i1 = (char) ((a * (i - 97) + b) % 26 + 97) + "";
s = s + i1;
} else
{
continue;
}
}
return s;
}
public static String decrypt(String miWen) {
int reciprocal
= reciprocal();
String s = "";
char[] chars = miWen.toCharArray();
for (char
aChar : chars) {
int i =
aChar;
if (i >= 65 && i < 65 + 26) {
int temp
= (i - 65) - b;
if (temp < 0) {
temp = temp + 26;
}
String i1 = (char) ((reciprocal * temp) % 26 + 65) + "";
s = s + i1;
} else
if (i >= 97 &&
i < 97 + 26) {
int temp
= (i - 97) - b;
if (temp < 0) {
temp = temp + 26;
}
String i1 = (char) ((reciprocal * temp) % 26 + 97) + "";
s = s + i1;
} else
{
continue;
}
}
return s;
}
public static int getA() {
return a;
}
public static int getB() {
return b;
}
}
四、实验结果与数据处理
五、实验分析与总结
在本次实验中我深刻的理解到仿射密码的加密解密过程,也对现代密码学有了初步的认识,在仿射密码中主要的的问题就是找到一个参数的逆元,密码和数字字母是分不开的,在以后的学习中我会抓住基础的练习,不断提高自己的能力。
标签:26,加密,String,int,解密,密码,static,仿射 From: https://www.cnblogs.com/ai5277/p/17835025.html