题目描述
写一个程序实现2*2 Hill密码的加解密算法
遇到的问题
加密过程写的很顺利,因为是2*2矩阵,一些本应该用矩阵乘法计算的东西也直接被我简化成用算式表示了。
在写解密过程是遇到了问题,矩阵求逆的部分不太会做。跟着书上前面的例题看了一下。书上说对于2*2的矩阵,求其行列式。如果矩阵A有非零的行列式,则这个矩阵的逆如下计算:[A^(-1)]ij = (det A)^(-1) * (-1)^(i+j) * (Dij), 其中(Dij)是将矩阵去掉第j行和第i列后的子行列式的值,det(A)是A的行列式,而(det A)^(-1)是det(A) mod 26的逆。
然后举了个例子,矩阵A = 5 8 17 3; det A = (5 * 3) - (8 * 17) = -121 mod 26 = 9
因为9*3 = 27 mod 26 = 1,可得到9^(-1) mod 26 = 3
因此,A^(-1) mod 26 = 3 * (3, -8, -17, 5) = 3 * (3, 18, 9, 5) = (9, 54, 27, 15) = (9, 2, 1, 15)
啊对就这里。最开始我怎么都没看明白,后面去问别人人给我说就是对其中的每一个元素mod 26而已我才发现。wow这真是厉害极了。知道这个规律之后这也就好求逆了。
编写的代码如下
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 60
int main()
{
int K1[2][2] = {0}, K2[2][2] = {0};
int Temp1[2] = {0}, Temp2[2] = {0};
char P[MAX] = {0}, C[MAX] = {0};
int T1[MAX] = {0}, T2[MAX] = {0};
int len, flag=0, temp, temp1, i, j, num=0;
printf("======= Hill 密码 =======\n\n");
printf("请输入秘钥的值:\n");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
scanf("%d", &K1[i][j]);
}
}
printf</