Security and Cryptography in Python - One Time Pad

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:

Security and Cryptography in Python - One Time Pad

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:

Security and Cryptography in Python - One Time Pad

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:

Security and Cryptography in Python - One Time Pad

上一篇:密码学系列之:feistel cipher


下一篇:Security and Cryptography in Python - Stream Ciphers(4)