• Security and Cryptography in Python


    Security and Cryptography in Python - One Time Pad

    XOR Example
    def xor(x, s):
        print(x, 'xor', s, '=', x^s)
    
    def xorb(x, s):
        print(bin(x), 'xor', bin(s), '=', bin(x^s))
    
    xor(4, 8)
    xorb(4, 8)
    xor(4, 4)
    xorb(4, 4)
    xor(255, 1)
    xorb(255, 1)
    xor(255, 128)
    xorb(255, 128)
    

    Running Result:

    image-20210206110628193

    What is One Time Pad?

    Encryption: message^key(random) = cipher

    Decryption: cipher^key(random) = message

    import random
    
    def generate_key_stream(n):
        return bytes(random.randrange(0, 256) for i in range(n))
    
    def xor_bytes(key_stream, message):
        length = min(len(key_stream), len(message))
        return bytes([key_stream[i]^ message[i] for i in range(length)])
    
    message = "YOU ARE AWESOME"
    message = message.encode()
    key_stream = generate_key_stream(len(message))
    cipher = xor_bytes(key_stream, message)
    print(key_stream)
    print(cipher)
    print(xor_bytes(key_stream, cipher))
    

    Running Result:

    image-20210206122447248

    One Time Pad - Security

    The One Time Pad is unbreakable

    Requirements:

    • Key stream only used once
    • Key stream only know by sender and receiver
    • Key stream is generated by true randomness

    Why can't One Time Pad be Broken?

    You can decrypted to any plaintext available in the universe with that length.

    import random
    
    def generate_key_stream(n):
        return bytes(random.randrange(0, 256) for i in range(n))
    
    def xor_bytes(key_stream, message):
        length = min(len(key_stream), len(message))
        return bytes([key_stream[i]^ message[i] for i in range(length)])
    
    # this is done by your enemy
    message = "DO ATTACK"
    message = message.encode()
    key_stream = generate_key_stream(len(message))
    cipher = xor_bytes(key_stream, message)
    
    # this is us trying to break it
    print(cipher)
    message = "NO ATTACK"
    message = message.encode()
    guess_key_stream = xor_bytes(message, cipher)
    print(xor_bytes(guess_key_stream, cipher))
    

    Running Result:

    image-20210206124345742

    相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。
  • 相关阅读:
    Springboot打包成WAR包独立布署后找不到静态js文件
    layui实现数据分页功能(ajax异步)
    layer.prompt(options, yes)
    layer回调函数
    Html中的position:absolute的意思
    SQL基础-DML
    mysql的pager命令
    由于rngd进程导致的tomcat 启动慢
    elasticsearch安装
    zookeeper的observer模式
  • 原文地址:https://www.cnblogs.com/keepmoving1113/p/14381187.html
Copyright © 2020-2023  润新知