本篇文章,我要通过java代码实现Hill加密解密。
在上一篇,我们通过java代码实现了逆矩阵,这个是实现Hill密码的前提
首先我们实现加密,然后再通过加密的密文来进行解密过程。
1、Hill加密
我们将明文"paymoremoney"通过加密密钥K进行Hill加密
|17 17 5 |
K=|21 18 21|
|2 2 19|
每三个字母进行转换,依次转换结束。
private static String getEncrypttext(String plainttext) {
// TODO Auto-generated method stub
int temp1 = 0, temp2, temp3;
StringBuilder cipertext = new StringBuilder();
for(int i=0; i<plainttext.length(); i+=3) {
temp1 = key[0][0]*(plainttext.charAt(i) - 'A')
+ key[0][1]*(plainttext.charAt(i+1) - 'A')
+ key[0][2]*(plainttext.charAt(i+2) - 'A');
temp2 = key[1][0]*(plainttext.charAt(i) - 'A')
+ key[1][1]*(plainttext.charAt(i+1) - 'A')
+ key[1][2]*(plainttext.charAt(i+2) - 'A');
temp3 = key[2][0]*(plainttext.charAt(i) - 'A')
+ key[2][1]*(plainttext.charAt(i+1) - 'A')
+ key[2][2]*(plainttext.charAt(i+2) - 'A');
cipertext.append((char)('A'+temp1%26));
cipertext.append((char)('A'+temp2%26));
cipertext.append((char)('A'+temp3%26));
}
return cipertext.toString();
}
2、Hill解密
首先我们必须求出逆矩阵,由于里面的数字必须为0-25之间
所以上一节求逆矩阵不能用,我们使用穷举法。
/*
这里使用满足逆矩阵与原矩阵相乘必为单位矩阵
*/
private int[][] getReverseMartrix(int[][] key2) {
// TODO Auto-generated method stub
int[][] key = new int[key2.length][key2[0].length];
for(int num=0; num<3; num++)
for(int i=0; i<26; i++)
for(int j=0; j<26; j++)
for(int k=0; k<26; k++) {
if((i*17+j*21+k*2)%26 == temp[num%3]
&& ((i*17+j*18+k*2)%26 == temp[(num+2)%3])
&& ((i*5+j*21+k*19)%26 == temp[(num+1)%3])) {
key[num][0] = i;
key[num][1] = j;
key[num][2] = k;
}
}
return key;
}
下面是解密代码
private String getDncrypttext(String ciphertext) {
// TODO Auto-generated method stub
int[][] key2 = new int[key.length][key[0].length];
key2 = getReverseMartrix(key);
System.out.println("加密密钥逆矩阵为:");
showMartrix(key2);
return getDecrypttext(key2, ciphertext);
}
private String getDecrypttext(int[][] key2, String ciphertext) {
// TODO Auto-generated method stub
int temp1, temp2, temp3;
StringBuilder plainttext = new StringBuilder();
for(int i=0; i<ciphertext.length(); i+=3) {
temp1 = key2[0][0]*(ciphertext.charAt(i) - 'A')
+ key2[0][1]*(ciphertext.charAt(i+1) - 'A')
+ key2[0][2]*(ciphertext.charAt(i+2) - 'A');
temp2 = key2[1][0]*(ciphertext.charAt(i) - 'A')
+ key2[1][1]*(ciphertext.charAt(i+1) - 'A')
+ key2[1][2]*(ciphertext.charAt(i+2) - 'A');
temp3 = key2[2][0]*(ciphertext.charAt(i) - 'A')
+ key2[2][1]*(ciphertext.charAt(i+1) - 'A')
+ key2[2][2]*(ciphertext.charAt(i+2) - 'A');
plainttext.append((char)('A'+temp1%26));
plainttext.append((char)('A'+temp2%26));
plainttext.append((char)('A'+temp3%26));
}
return plainttext.toString();
}
最后,需要源代码的,请去云盘下载吧
Hill密码源代码 链接: http://pan.baidu.com/s/1i3J8BlV 密码: dyeq