现代密码体制的萌芽

维尔南(Vernam)密码被视为是现代密码体制的萌芽。它是美国电话电报公司的Gilbert Vernam在1917年为电报通信设计的一种非常方便的密码,在近代计算机和通信系统设计中得到了广泛应用。
维尔南密码的特点是通过一个密钥流生成器(key stream generator)来持续生成二进制密钥。密钥文件大小与待加密文件大小相同(精确到字节)。换言之,待加密文件越大,密钥文件越大,加密强度越高!举个例子,如果想加密一个5M的文件,那么密钥长度将高达40,000,000位,输出文件大小则仍为5M。想要在”有生之年”靠穷取法破解出密码,几乎不可能完成的任务。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import math
import pyaudio
from struct import unpack
from random import shuffle, sample

opzioni = {
"format": pyaudio.paFloat32,
"channels": 2,
"rate": 96000,
"input": True,
"frames_per_buffer": 1024
}

class generator:
def _nums(l, n):
for i in range(0, len(l), n):
chunk = l[i:i+n]
if any(chunk):
yield unpack('>L', chunk)[0]

def random(a, b, n):
audio = pyaudio.PyAudio()
raw_data = audio.open(**opzioni).read(opzioni["rate"] // opzioni["frames_per_buffer"] * int(10*math.log(n)))
audio.terminate()

sequence = generator._nums(raw_data, 4)
sequence = sample(list(sequence), n)
m = max(sequence)

return map(lambda x: a + (b-a) * (x/m), sequence)

def onetimepad(l):
return tuple(map(int, generator.random(0, 2*16, l)))

class VernamCipher:
def __init__(self):
self.max = 2 ** 16

def encryption(self, plaintext):
'''
加密函数
'''
encrypted = []
key = ()
if key is ():
key = generator.onetimepad(len(plaintext))
for i, character in enumerate(plaintext):
encrypted.append(
chr((ord(character) + key[i]) % self.max))
return "".join(encrypted), key

def decryption(self, cyphertext, key):
'''
解密函数
'''
encrypted = []
for i, character in enumerate(cyphertext):
encrypted.append(chr((ord(character) - key[i]) % self.max))
return "".join(encrypted)

t_plain = '12.25 HappyBirthday!'
t = VernamCipher()
print('明文是:', t_plain)
t_cypher, t_key = t.encryption(t_plain)
print('密文是:', t_cypher)
t_result = t.decryption(t_cypher, t_key)
print('解密结果是:', t_result)