Security and Cryptography in Python - Stream Ciphers(4)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Security and Cryptography in Python - Stream Ciphers(4),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1715字,纯文字阅读大概需要3分钟。
内容图文
![Security and Cryptography in Python - Stream Ciphers(4)](/upload/InfoBanner/zyjiaocheng/606/3af2dd7d85314e2e8fac79ccb4459fc5.jpg)
Security and Cryptography in Python - Stream Ciphers(4)
Low entropy - Brute force of our Stream Cipher
import random
class KeyStream:
def __init__(self, key=1):
self.next = key
def rand(self):
self.next = (1103515245*self.next + 12345) % 2**31
return self.next
def get_key_byte(self):
return (self.rand()//2**23) % 256
def encrypt(key, message):
return bytes([message[i]^ key.get_key_byte() for i in range(len(message))])
def transmit(cipher, likely):
b = []
for c in cipher:
if random.randrange(0, likely) == 0:
c = c ^ 2**random.randrange(0, 8)
b.append(c)
return bytes(b)
def modification(cipher):
mod = [0]*len(cipher)
mod[10] = ord(' ') ^ ord('1')
mod[11] = ord(' ') ^ ord('0')
mod[12] = ord('1') ^ ord('0')
return bytes([mod[i] ^ cipher[i] for i in range(len(cipher))])
def get_key(message, cipher):
return bytes([message[i] ^ cipher[i] for i in range(len(cipher))])
def crack(key_stream, cipher):
length = min(len(key_stream), len(cipher))
return bytes([key_stream[i] ^ cipher[i] for i in range(length)])
def brute_force(plain, cipher):
for k in range(2**31):
bf_key = KeyStream(k)
for i in range(len(plain)):
xor_stream = plain[i] ^ cipher[i]
if xor_stream != bf_key.get_key_byte():
break
else:
return k
return False
# This is Alice
secret_key = random.randrange(0, 2**20)
print(secret_key)
key = KeyStream(secret_key)
header = "MESSAGE: "
message = header + "My secret message to Bob"
message = message.encode()
print(message)
cipher = encrypt(key, message)
print(cipher)
# This is Bob
key = KeyStream(secret_key)
message = encrypt(key, cipher)
print(message)
# This is Eve
bf_key = brute_force(header.encode(), cipher)
print("Eve's brute force key:", bf_key)
key = KeyStream(bf_key)
message = encrypt(key, cipher)
print(message)
Running Result:
内容总结
以上是互联网集市为您收集整理的Security and Cryptography in Python - Stream Ciphers(4)全部内容,希望文章能够帮你解决Security and Cryptography in Python - Stream Ciphers(4)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。