Advertisement
freddy87

XOR Message Encryption

Jun 12th, 2016
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #XOR encryption mode
  2. #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!
  3.  
  4.  
  5. #!/usr/bin/env python2
  6.  
  7. from os import urandom
  8.  
  9. #generates xor key and string variable
  10. def genkey(length):
  11. """Generate key"""
  12. return urandom(length * 2)
  13.  
  14. def xor_strings(s,t):
  15. """xor two strings together"""
  16. return "".join(chr(ord(a)^ord(b)) for a,b in zip(s,t))
  17.  
  18. #checks input to match encrypt or decrypt option
  19. while True:
  20. user_input = raw_input('(E)ncrypt or (D)ecrypt? ')
  21. if user_input in ['E', 'D', 'e', 'd']:
  22. break
  23. else:
  24. print('That is not a valid option!')
  25.  
  26. if user_input in ['E', 'e']:
  27. #prompts for message and opens appropriate filenames
  28. message =raw_input(b"What is your message? ")
  29. file1=open(raw_input(b"Enter the full filepath to write to: "), 'w')
  30. file2=open(raw_input(b"Enter a filepath for the key: "), 'w')
  31. print 'message:', message
  32. #prints key
  33. key = genkey(len(message))
  34. print 'key:', key
  35. #prints code and key to files
  36. cipherText = xor_strings(message, key)
  37. coded = cipherText
  38. print 'cipherText:', cipherText
  39. file1.write(coded)
  40. file1.close()
  41. file2.write(key)
  42. file2.close()
  43.  
  44. # verifies code and key
  45. if xor_strings(cipherText, key) == message:
  46. print 'Encode passed'
  47. else:
  48. print 'Encode failed'
  49.  
  50. elif user_input in ['d', 'D']:
  51. #opens encrypted file
  52. file1=open(raw_input("What is the full filepath of the file containing the message? "))
  53. file2=open(raw_input("What is the full filepath of the file containing the key? "))
  54. #reads encrypted file
  55. message=file1.read()
  56. key=file2.read()
  57. #prints decrypted message/contents
  58. print 'decrypted:', xor_strings(message, key)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement