So to refresh my mind I read the wiki article on One Time Pads (OTP for short) and it said some stuff about the message being encoded using modular addition bit by bit from the key. It is effectively secure when the key is the same length or longer than the plaintext.
What I got from that without really thinking about it at all is that the easiest way to enact a substitution involving a change by modular addition from a key of the same length as the message would be to add modularly the ascii values of each corresponding character of the plaintext and the key. Example:
key = HATE (72, 65, 84, 69)
plaintext = LOVE (76, 79, 86, 69)
resulting ciphertext = UQkK (85, 81, 107, 75)
This means in the code we clearly need a key = raw_input("Put in a key: ") and a plaintext = raw_input("Put in a message: ") This will give us two strings to add the way I have show above. How to implement that though? My favourite way to do a one line mathematic calculation repeatedly in python is with a lambda function, which in this case would be defined as:
C = lambda x, y: ((x + y) % 95) + 32
Applied as shown above in python that little bit of code would look like this:
key = raw_input("Put in a key: ")
plain = raw_input("Put in a message: ")
cipher = []
C = lambda x, y: ((x+y) % 95) + 32
for i in range(0, len(key)):
cipher.append(C(ord(key[i]), ord(plain[i])))
Given the example above, the above code will give you the correct cipher text. There are three problems remaining with the above code;
The key doesn't HAVE to be the same length as the message, which will cause the program to err.
The security of the message depends on a random key, which let's face it, if we let someone enter something it very well may not be that random.
The cipher still only uses substitution and not obfuscation, which may not be critical, but does cause a decrease in security.
The solution to that would be to seed a random generator with the chosen key, and generate an array of appropriate size filled with aptly sized integers to match the message. This requires a seed-able random generator. The following code is how I would get this done in python, feel free to discuss why I did what I did, how I did it, and what is still clearly wrong with this:
#! bin/env/python
from random import Random
from sys import stdout
R = Random()
plain = raw_input("Put in your message: ")
R.seed(raw_input("Put in a key that is at least as long as your message: "))
C = lambda x, y: ((x+y) % 95) + 32
for i in range(0, len(plain)):
stdout.write(chr(C(ord(plain[i]), R.randint(1, 95))))
stdout.write('\n')
Comments
No Comments Exist
Be the first, drop a comment!