加解密学习之
密码学
模运算和经典密码学
a = r mod m
a = q*m + r
余数不唯一
12 = 3 mod 9
12 = 21 mod 9
12 = -6 mod 9
{...3,12,21,30...}上面的组合就是等价类,比如模数9还存在另外8个等价类。
{...0,10,19...}{...1,10,19...}
...
{...8,17,26...}
余数的选择
一般 0 ≤ r ≤ m − 1
整数环
- The set Zm = {0,1,2,...,m−1}
- Two operations “+” and “×” for all a, b ∈ Zm such that:
1.a + b ≡ c mod m,(c ∈ Zm)
2.a × b ≡ d mod m,(d ∈ Zm)
ie:Z9 = {0,1,2,3,4,5,6,7,8}
6 + 8 = 14 ≡ 5 mod 9
6 × 8 = 48 ≡ 3 mod 9
整数环的下列特性:
- 任何两数相加或相乘的结果都在环里面,闭环。
- 加乘都可以叠加
- 总有元素0符合加法规则,a + 0 = a mod m
- 对任何元素a总有一个负元素-a,使得 a+(-a) = 0 mod m
- 总有元素1符合乘法规则,a*1 = a mod m
- ...
位移加密(凯撒加密)
把26个字母编码 0到25
然后得到整数环 Z26
Definition 1.4.3 Shift Cipher
Let x,y,k ∈ Z26.
Encryption:$e_k(x) = x+k \mod 26$
.
Decryption:$d_k(y) = x-k \mod 26$
.
ATTACK 就是 0,19,19,0,2,10
如果k = 17,右移动17位,密文就是rkkrtb,
很不安全,通过暴力破解和词频分析就很容易解决
仿射加密
Definition 1.4.4 Affine Cipher
Let x,y,a,b ∈ Z26
Encryption: $e_k(x) = y = a \times x+b \mod 26$
.
Decryption: $d_k(y) = x = a^{-1} \times (y-b) \mod 26$
.
with the key: k = (a, b), which has the restriction: gcd(a, 26) = 1
解密过程根据加密过程可以轻松得出:
$ a \times x+b = y \mod 26$
$ a\times x = (y-b) \mod 26 $
$x = a^{-1} \times (y-b) \mod 26$
c++仿射加密
#include <iostream> //仿射加密,sorcery --> welcylk
using namespace std;
#include <string.h>
int Fsenc(char s[])
{
int i = 0;
int a[99];
char *p = s;
while (*p != '\0')
{
a[i] = s[i] - 'a'; // 字符转换为数字
a[i] = (11 * a[i] + 6) % 26; // 仿射加密函数
s[i] = a[i] + 'a'; // 数字转换为字符
i++;
p++;
}
return 1;
}
int Fsdec(char s[])
{
int i = 0;
int a[99];
char *p = s;
while (*p != '\0')
{
a[i] = s[i] - 'a'; // 字符转换为数字
a[i] = (19 * a[i] + 16) % 26; // 仿射解密函数
s[i] = a[i] + 'a'; // 数字转换为字符
i++;
p++;
}
return 1;
}
int main()
{
char s[99];
gets(s);
Fsenc(s);
cout << "加密后:";
for (int i = 0; i < 7; i++)
{
cout << s[i];
if ((i + 1) % 7 == 0)
cout << endl;
}
Fsdec(s);
cout << "解密后明文:";
for (int i = 0; i < 7; i++)
{
cout << s[i];
if ((i + 1) % 7 == 0)
cout << endl;
}
}