Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #XOR encryption mode
- #keeps messages from existing in plaintext form by encrypting them immediately. Generates random key which can be #written to a file and stored elsewhere otherwise they can never be opened!
- #!/usr/bin/env python2
- from os import urandom
- #generates xor key and string variable
- def genkey(length):
- """Generate key"""
- return urandom(length * 2)
- def xor_strings(s,t):
- """xor two strings together"""
- return "".join(chr(ord(a)^ord(b)) for a,b in zip(s,t))
- #checks input to match encrypt or decrypt option
- while True:
- user_input = raw_input('(E)ncrypt or (D)ecrypt? ')
- if user_input in ['E', 'D', 'e', 'd']:
- break
- else:
- print('That is not a valid option!')
- if user_input in ['E', 'e']:
- #prompts for message and opens appropriate filenames
- message =raw_input(b"What is your message? ")
- file1=open(raw_input(b"Enter the full filepath to write to: "), 'w')
- file2=open(raw_input(b"Enter a filepath for the key: "), 'w')
- print 'message:', message
- #prints key
- key = genkey(len(message))
- print 'key:', key
- #prints code and key to files
- cipherText = xor_strings(message, key)
- coded = cipherText
- print 'cipherText:', cipherText
- file1.write(coded)
- file1.close()
- file2.write(key)
- file2.close()
- # verifies code and key
- if xor_strings(cipherText, key) == message:
- print 'Encode passed'
- else:
- print 'Encode failed'
- elif user_input in ['d', 'D']:
- #opens encrypted file
- file1=open(raw_input("What is the full filepath of the file containing the message? "))
- file2=open(raw_input("What is the full filepath of the file containing the key? "))
- #reads encrypted file
- message=file1.read()
- key=file2.read()
- #prints decrypted message/contents
- print 'decrypted:', xor_strings(message, key)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement