jueves, 23 de agosto de 2012

One Time Pad

In cryptography, the one-time pad (OTP) is a type of encryption which has been proven to be impossible to crack if used correctly. Each bit or character from the plaintext is encrypted by a modular addition with a bit or character from a secret random key (or pad) of the same length as the plaintext, resulting in a ciphertext.



 The "pad" part of the name comes from early implementations where the key material was distributed as a pad of paper, so the top sheet could be easily torn off and destroyed after use. For easy concealment, the pad was sometimes reduced to such a small size that a powerful magnifying glass was required to use it. Photos show captured KGB pads that fit in the palm of one's hand, or in a walnut shell. To increase security, one-time pads were sometimes printed onto sheets of highly flammable nitrocellulose.

Here the code, a brief implementation in python:

1.- The random key is generated.
2.- That key is used for encrypt the message.
3.- The same key and the ciphertext are used for decrypt the message.



from random import *

def create_key(message):
 abc = "abcdefghijklmnopqrstuvwxyz0123456789;.:-_/@\&$%!?()[]#+^"
 key = []
 for char in message:
  key += abc[randint(0,55)]
 return key
 
def encrypt(message, key):
    res = ""
    for i in range(len(message)):
        messagechar = ord(message[i]) - ord(start)
        keychar = ord(key[i]) - ord(start)
        calcuchar = (messagechar + keychar) % modulo
        convertchar = chr(calcuchar + ord(start))
        res += convertchar
    return res

def decrypt(message, key):
    res = ""
    for i in range(len(message)):
        messagechar = ord(message[i]) - ord(start)
        keychar = ord(key[i]) - ord(start)
        calcuchar = (messagechar - keychar) % modulo
        convertchar = chr(calcuchar + ord(start))
        res += convertchar
    return res

#main
start = ' ' 
end = '~'  
              
modulo = ord(end) - ord(start) 
message = "this message is only a test to show a small implemetation of otp"
#key =  "AKebnbl5fFWXTXYkfd=I_XujRdvgULghs;ucO_YeyVc"

key = create_key()
encryp = encrypt(message, key)
decryp = decrypt(encryp, key)

#print modulo
print ""
print "Message : ", message
print ""
print "Encrypted:", encryp
print ""
print "Decrypted:", decryp
print ""
print "Key :     ", key



Here a capture of the script running:



Sorry if the SyntaxHighlighter fails.
__________________________________________________________________________________
References