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)
|