Text Encryption/Decryption with XOR (Python)

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
vegaseat vegaseat is offline Offline Oct 3rd, 2005, 3:34 am |
0
Crypting with xor allows one to write one function that can encrypt and decrypt a file. In this example a text file is used, but it could be an image file as well. Once you have created the encrypted file you simply send it through the same function again to decrypt it. The password is looped against the file, but you can get tricky and spell forward then backward, odd/even, or every odd character twice and every even character once. This will make it harder for grandma to decipher your secret files.
Quick reply to this message  
Python Syntax
  1. # testing a simple xor encryption/decryption
  2. # tested with Python24 vegaseat 02oct2005
  3.  
  4. import StringIO
  5. import operator
  6.  
  7.  
  8. def cryptXOR(filename, pw):
  9. """
  10. cryptXOR(filename, pw) takes the file in filename and xor encrypts/decrypts it against the password pw,
  11. if the file extension is .txt indicating a normal text file, then an encrypted file with extension .txp
  12. will be written, if the file extension indicates an encrypted file .txp then a decrypted normal text
  13. file with extension .txt will be written
  14. """
  15. f = open(filename, "rb") # binary required
  16. str2 = f.read()
  17. f.close()
  18. # create two streams in memory the size of the string str2
  19. # one stream to read from and the other to write the XOR crypted character to
  20. sr = StringIO.StringIO(str2)
  21. sw = StringIO.StringIO(str2)
  22. # make sure we start both streams at position zero (beginning)
  23. sr.seek(0)
  24. sw.seek(0)
  25. n = 0
  26. #str3 = "" # test
  27. for k in range(len(str2)):
  28. # loop through password start to end and repeat
  29. if n >= len(pw) - 1:
  30. n = 0
  31. p = ord(pw[n])
  32. n += 1
  33.  
  34. # read one character from stream sr
  35. c = sr.read(1)
  36. b = ord(c)
  37. # xor byte with password byte
  38. t = operator.xor(b, p)
  39. z = chr(t)
  40. # advance position to k in stream sw then write one character
  41. sw.seek(k)
  42. sw.write(z)
  43. #str3 += z # test
  44. # reset stream sw to beginning
  45. sw.seek(0)
  46. # if filename was a normal text file, stream sw now contains the encrypted text
  47. # and is written (binary required) to a file ending with .txp
  48. if filename.endswith('.txt'):
  49. outfile = filename[:-4] + '.txp'
  50. f = open(outfile, "wb")
  51. f.write(sw.read())
  52. f.close()
  53. print "File %s written!" % outfile
  54. # if filename was encrypted text, stream sw now contains normal text
  55. # and is written to a file ending with .txt
  56. elif filename.endswith('.txp'):
  57. outfile = filename[:-4] + '.txt'
  58. f = open(outfile, "w")
  59. f.write(sw.read())
  60. f.close()
  61. print "File %s written!" % outfile
  62. #print str3 # test
  63. else:
  64. print "File %s does not have proper extension!" % filename
  65.  
  66. # clean up
  67. sr.close()
  68. sw.close()
  69.  
  70.  
  71.  
  72. # allows cryptXOR() to be used as a module
  73. if __name__ == '__main__':
  74.  
  75. str1 = \
  76. '''A list of quotes from Grade School Essays on the History of Classical Music:
  77. "J.S. Bach died from 1750 to the present"
  78. "Agnus Dei was a woman composer famous for her church music."
  79. "Refrain means don't do it. A refrain in music is the part you better not try to sing."
  80. "Handel was half German, half Italian, and half English. He was rather large."
  81. "Henry Purcell is a well-known composer few people have ever heard of."
  82. "An opera is a song of bigly size."
  83. "A harp is a nude piano."
  84. "A virtuoso is a musician with real high morals."
  85. "Music sung by two people at the same time is called a duel."
  86. "I know what a sextet is but I'd rather not say."
  87. "Most authorities agree that music of antiquity was written long ago."
  88. "My favorite composer is opus."
  89. "Probably the most marvelous fugue was between the Hatfields and the McCoys."
  90. "My very best liked piece is the bronze lullaby." '''
  91.  
  92. # save the string as a normal text file so we have it
  93. fout = open("Music101.txt", "w")
  94. fout.write(str1)
  95. fout.close()
  96.  
  97. # let's use a fixed password for testing
  98. password = "nixon"
  99.  
  100. # encrypt the text file to "Music101.txp" (check with an editor, shows a mess)
  101. cryptXOR("Music101.txt", password)
  102.  
  103. # decrypt the text file back to "Music101.txt" (check with an editor, normal text again)
  104. cryptXOR("Music101.txp", password)

Message:


Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC