Created
June 8, 2013 20:50
-
-
Save jclement/5736534 to your computer and use it in GitHub Desktop.
Basic python program for generating / decoding strings with a one-time-pad.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import os | |
| import string | |
| import sys | |
| import random | |
| # ===================================================== | |
| CMIN=0x20 | |
| CMAX=0x7E | |
| CDIFF = CMAX-CMIN | |
| # ===================================================== | |
| def otp(source): | |
| key = '' | |
| out = '' | |
| with open('/dev/random') as f: | |
| for i in range(len(source)): | |
| assert ord(source[i]) >= CMIN and ord(source[i]) <= CMAX | |
| a = ord(source[i])-CMIN | |
| b = ord(f.read(1)) % CDIFF | |
| out += chr(CMIN + ((a+b)%CDIFF)) | |
| key += chr(CMIN + b) | |
| return (key, out) | |
| def decode(a,b): | |
| out = '' | |
| assert len(a) == len(b) | |
| for i in range(len(a)): | |
| out += chr(CMIN + ((ord(b[i])-CMIN)-(ord(a[i]) - CMIN)) % CDIFF) | |
| return out | |
| if __name__=='__main__': | |
| if len(sys.argv) != 2 or sys.argv[-1] not in ['-d','-e']: | |
| print "syntax: otp.py -[de]" | |
| elif sys.argv[-1] == '-d': | |
| s1 = raw_input("String #1: ").strip() | |
| s2 = raw_input("String #2: ").strip() | |
| print "========================================================" | |
| print "Decoded #1:", decode(s1,s2) | |
| print "Decoded #2:", decode(s2,s1) | |
| print "========================================================" | |
| elif sys.argv[-1] == '-e': | |
| source = raw_input("String to encrypt: ").strip() | |
| res = otp(source) | |
| print "========================================================" | |
| print "Source: ",source | |
| print "Decoded: ", decode(res[0], res[1]) | |
| print "String1: ", res[0] | |
| print "String2: ", res[1] | |
| print "========================================================" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment