where to buy misoprostol online how to buy valtrex
XOR Encryption With Python | Evan Fosmark

XOR Encryption With Python

XOR encryption is a great solution to go with when a task requires that a piece of data is encrypted with a key when one doesn’t have the means to use a more well-rounded algorithm. I’ve used it on a few occasions with great success. In this document, we’ll discuss how to code the XOR cipher in Python and we’ll cover the pros and cons of using it.

The Code

from itertools import izip, cycle
 
def xor_crypt_string(data, key):
    return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))

The code for XOR string encryption is surprisingly simple since the whole concept of XOR encryption is simple. Basically, it iterates over a piece of data, and for every letter, it XORs it with the key. In this function, it is done in a list comprehension. Once the list is built, it gets joined into a string and returned. Encryption and decryption both use the same function.

Examples

my_data = "Hello. This is a secret message! How fun."
my_key= "firefly"
 
# Do the actual encryption
encrypted = xor_crypt_string(my_data, key=my_key)
 
# This will obtain the original data from the encrypted
original = xor_crypt_string(encrypted, key=my_key)

The Good

XOR encryption is a very quick way to encrypt/decrypt strings based on a key. They’re perfect for cases where you’d like to transfer data safely (but not too safely. Read the next section). Furthermore, the XOR cipher needs only one function that does both encrypting and decrypting. For instance, in the above code if you encrypt something and then feed it directly back into the function with the same key, it’ll produce the unencrypted data. Also, the XOR cipher is considered the only perfect encryption method under the proper scheme for a one-time pad. (There are exceptions. Keep reading…)

The Bad

Okay, remember when I said that it can be a perfect encryption? Well, that comes with a few limitations. Namely, the key must be completely random, the key must be the length of the data being encrypted, and the key can be used once and only once. If those rules aren’t followed, then the cipher can be broken using frequency analysis.

The Right Way

Use the Python Cryptography Toolkit. It provides you with plenty of other methods to use instead of XOR encryption. A manual can be found here. Of course, doing it this way causes your code to become less portable since anybody you send it to will also be required to have the toolkit installed.

 

 

13 Comments

  1. Jordan wrote,

    Here is a function written in python using xor encryption. The file target is a file path (i.e., /root/myfile.txt) and the key can be one of two things: a simple text password (“mypassword”) or a path to a file to be used as a key(“/root/myKey.key”). I do not have izip, so I commented out the list comprehension you gave on this site.

    def xor(fileTarget, key):
    	fileTarget = fileTarget + os.listdir(fileTarget)[0]
     
    	ifile = os.path.split(fileTarget)[0]+"/xor.in"
    	ofile = os.path.split(fileTarget)[0]+"/xor.out"
    	os.rename(fileTarget, ifile)
     
    	if os.path.isfile(key):
    		kf = open(key)
    		keyData = kf.read()
    		kf.close()
    	else:
    		keyData = key
     
    	e = open(ofile, "w")
    	f = open(ifile, "r")
     
    	bytesToCopy = os.stat(os.path.split(fileTarget)[0]+"/xor.in")[6]
     
    	while bytesToCopy:
     
    		if bytesToCopy >= len(keyData):
    			data = f.read(len(keyData))
    			bytesToCopy -= len(keyData)
    			encryptedData = ''.join([chr(ord(data[i])^ord(keyData[i])) for i in xrange(len(data))])
    			# encryptedData = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
    			e.write(encryptedData)
     
    		else:
    			data = f.read(bytesToCopy)
    			bytesToCopy = 0
    			encryptedData = ''.join([chr(ord(data[i])^ord(keyData[i])) for i in xrange(len(data))])
    			# encryptedData = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
    			e.write(encryptedData)
    	os.remove(ifile)
     
    	e.close()
    	f.close()
     
    	return os.path.split(fileTarget)[0]+"/xor.out"
  2. Dan wrote,

    The one-time pad is the only cipher known to be 100% secure, because there is no way to determine that any given key is correct. The problem with trying to cryptanalyze (break) such a cipher as this is that you can never be sure that you actually have the correct key. Like you said, though, this cipher requires a key with the same length as the plaintext (unencrypted text) that is never reused and has perfect randomness. The funny thing about randomness is this: There’s no good test for it!

    Consider this sequence of numbers: 1, 1, 1, 1, 1, 1

    That sequence looks very non-random, but it’s impossible to tell if that was generated by repeating the number 1, by picking numbers randomly from a hat or from one’s mind, by choosing from a limited set of numbers using a poor random number generator, by choosing from an infinite set of numbers using a perfect random number generator…

    And of course, how do you transmit the keys safely? ;)

  3. san wrote,

    hi,
    any one help me to brak 256 byte key

  4. Todas as possibilidades de maiusculas e minusculas wrote,

    [...] LinkedIn [...]

  5. Gino wrote,

    You really make it seem so easy along with
    your presentation however I find this matter to be really something which I feel
    I’d never understand. It kind of feels too
    complicated and very large for me. I am taking a look
    ahead to your next put up, I will try to get the grasp of it!

  6. home plumbing emergency wrote,

    Hi friends, nice post and pleasant arguments commented here, I am truly enjoying by these.

  7. hookah bar and grill wrote,

    What’s up everyone, it’s my first pay a quick visit
    at this web site, and article is in fact
    fruitful in favor of me, keep up posting these types of articles or reviews.

    Feel free to visit my website; hookah bar and grill

  8. plumbing repairs raleigh nc wrote,

    I am regular reader, how are you everybody? This piece of
    writing posted at this web page is in fact fastidious.

    my website; plumbing repairs raleigh nc

  9. commercial cleaning services raleigh nc wrote,

    Attractive section of content. I just stumbled upon your web site and in accession capital to
    assert that I acquire actually enjoyed account your blog posts.
    Any way I’ll be subscribing to your augment and even I
    achievement you access consistently rapidly.

    my web page … commercial cleaning services raleigh nc

  10. karatbars international review wrote,

    Excellent post. I was checking continuously this blog and I’m impressed!

    Extremely useful information particularly the last part :) I
    deal with such information much. I was looking for this certain information for a very lengthy time.

    Thanks and good luck.

    my web blog: karatbars international review

  11. best eye wrinkle cream men wrote,

    My brother suggested I might like this web site.

    He was entirely right. This post truly made
    my day. You cann’t imagine just how much time I had spent
    for this info! Thanks!

    My site; best eye wrinkle cream men

  12. dragons Of Atlantis hack wrote,

    Hello! This post could not be written any better!
    Reading through this post reminds me of my old room mate!
    He always kept chatting about this. I will forward this page to
    him. Pretty sure he will have a good read. Thanks for sharing!

  13. HOOKAH wrote,

    My partner and I absolutely love your blog and find nearly all of your post’s to be precisely what
    I’m looking for. can you offer guest writers to write content available for you?
    I wouldn’t mind publishing a post or elaborating on some of
    the subjects you write concerning here. Again, awesome web site!

Leave a comment