您的位置:首页 > 其它

线性代数的一则数据加密应用

2012-05-03 14:43 183 查看
最近复习线性代数准备考试,看最后一章有关于计算机应用方面的,便拿过来测试了下。

希尔密码(Hill Password)是运用基本矩阵论原理的替换密码,由Lester S. Hill在1929年发明。用的就是利用这种加密原理。

基础理论:

根据矩阵的这个性质,我们先存储一个N阶可逆阵A,将数据按列存入矩阵B,
AB可得到新的矩阵C,C为加密数据。
根据性质,我们将A的逆矩阵A*C则可以得到原始数据。
下面是编码测试:

#pragma once
#include <stdio.h>
#include <string.h>
#define MATRIX_O 3
#define MAX_M 256

int Matrix_M[3][3] = {    //加密矩阵
3, -1, 4,
1, 0,  0,
2, 1, -5
};
int Matrix_T[3][3] = {    //解密矩阵
0,  1,  0,
-5, 23, -4,
-1, 5,  -1
};

void MatrixEncode(char *pSource, int TextLen, int matrix[][MATRIX_O], char *OutChar)
{
int i, t, j, n, itr = 0;
int total = 0;

n = TextLen / MATRIX_O;
if (TextLen % MATRIX_O)
n++;

for ( i = 0; i < n; i++)
{
for (t = 0; t < MATRIX_O; t++)
{
total = 0;
for (j = 0;j < MATRIX_O; j++)
total += matrix[t][j] * pSource[i*MATRIX_O+j];
OutChar[itr++] = total % 256;  //base Number
}
}
}

int main(int argc, char **argv)
{
char Encode[MAX_M] = {0},
Decode[MAX_M] = {0};

char *pSource= "I Miss You.";
printf("Source string: %s\n", pSource);
MatrixEncode(pSource, strlen(pSource), Matrix_M, Encode);
printf("Encode:\n");
for (unsigned int i = 0; i < strlen(pSource); i++)
printf("%d ", Encode[i]);
putchar('\n');

MatrixEncode(Encode, strlen(Encode), Matrix_T, Decode);
printf("\nDecode : %s\n", Decode);
for (i = 0; i < strlen(pSource); i++)
printf("%d ", Decode[i]);
putchar('\n');
printf("\nDecode : %s\n", Decode);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: