• Security and Cryptography in Python


    Security and Cryptography in Python - Stream Ciphers(3)

    The problem of re-use of keys in Stream Ciphers
    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() % 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)])
    
    # Eve goes to Alice
    eves_message =  "This is Eve's most valued secrets of all her life".encode()
    
    # This is Alice alone
    key = KeyStream(10)
    message = eves_message
    print(message)
    cipher = encrypt(key, message)
    print(cipher)
    
    # This is Eve(alone) all evil
    eves_key_stream = get_key(eves_message, cipher)
    
    # This is Bob
    key = KeyStream(10)
    message = encrypt(key, cipher)
    print(message)
    
    # Alice again
    message = "Hi Bob, let's meet a plan our world domination.".encode()
    key = KeyStream(10)
    cipher = encrypt(key, message)
    print(cipher)
    
    # Bob again
    key = KeyStream(10)
    message = encrypt(key, cipher)
    print(message)
    
    # Eve again (more evil than ever)
    print(" THIS IS EVE")
    print(crack(eves_key_stream, cipher))
    

    Running Result:

    image-20210206181636646

    相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。
  • 相关阅读:
    Effective JavaScript Item 40 避免继承标准类型
    基于express+redis高速实现实时在线用户数统计
    HDOJ 4009 Transfer water 最小树形图
    iOS Sprite Kit教程之xcode安装以及苹果帐号绑定
    Swift2.0语言教程之类的嵌套与可选链接
    Swift2.0语言教程之下标脚本
    Swift2.0语言教程之类的方法
    Swift2.0语言教程之类的属性
    Swift2.0语言教程之闭包
    Swift2.0语言教程之函数嵌套调用形式
  • 原文地址:https://www.cnblogs.com/keepmoving1113/p/14382356.html
Copyright © 2020-2023  润新知