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.

 

 

4 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 [...]

Leave a comment

Take Albuterol Inhaler
Order Inhaler Albuterol
Buy Albuterol Online no Prescription
Online Buy Albuterol Without a Prescription
Purchase Online Without a Prescription Albuterol
Online Buying Aldactone
Purchase Online Without a Prescription Aldactone
Aldactone for Acne
Buying Aldactone Legally
Buy Tablets Aldactone Online
Cheapest Buy Allopurinol
Purchase Allopurinol Online no Prescription
Buy Without a Prescription Allopurinol
Buy Allopurinol Free Delivery
Legally Order Allopurinol
Buy Anafranil Without a Prescription
Buy Anafranil Pills
Buy Anafranil Medication
Buying Without a Prescription Anafranil Online
Take no Prescription Anafranil
Buying Atarax Overnight Delivery
Purchase Atarax Free Delivery
Alternative Purchase Atarax
Purchase Atarax by Phone
Legally Purchase Atarax
Order Avodart Without a Prescription
Tablets Order Avodart
Pills Buying Avodart
Buy Avodart Medication
Tablets Purchase Avodart
Alternative Purchase Bactrim
Take Bactrim Next Day Delivery
Online Buying Bactrim
Cheapest Buy Bactrim
Purchase Bactrim Without a Prescription
Buy Celecoxib Overnight Delivery
Purchase Cheapest Celecoxib
Tablets Buy Celecoxib
Buying Without Prescription Celecoxib
Order Online Without a Prescription Celecoxib
Take Cipro Legally
Purchase Cipro by Phone
Purchase Online no Prescription Cipro
Buy Pills Cipro
Order Cipro COD
Purchase Clomid Serophene Generic
100 Clomid Serophene
Cheapest Buy Clomid Serophene
Order Clomid Serophene by Phone
Take Clomid Serophene Medication
Buying Dapsone
Purchase Dapsone COD
Buy Dapsone Free Delivery
Take Dapsone Next Day Delivery
Order Cheapest Dapsone
Generic Buying Desyrel
Order Cheap Desyrel
Take Desyrel Next Day Delivery
Buy Desyrel Tablets
Buy Desyrel Cheapest
Buy Diflucan Medication
Buy Diflucan Pills
Take Diflucan Pills
Purchase no Prescription Diflucan
Order Cheapest Diflucan
Buying Dilantin Next Day Delivery
Dilantin Phenytoin
Buying Dilantin Overnight Delivery
Legally Purchase Dilantin
Purchase Dilantin Alternative
Purchase Diovan Pills
Buy Diovan Pills
Order no Prescription Diovan
Purchase Online Without Prescription Diovan
Buy Cheap Diovan
Buy Doxycycline Medication
Order Doxycycline Without a Prescription
Take Doxycycline Daily Dose
100 Doxycycline
Buying Doxycycline
Buy Elavil COD
Buy Elavil Medication
Order Elavil Generic
Order Elavil Pills
Purchase Elavil Drug
Order Generic Erythromycin
Buy Erythromycin Medication
Buy Erythromycin Without a Prescription
Purchase Online Without a Prescription Erythromycin
Buying Erythromycin Overnight Delivery
Order no Prescription Estrace
Buying Without Prescription Estrace
Take Estrace Drug
Purchase Estrace Alternative
Order Generic Estrace
Order Furosemide Pills
Buy Alternative Furosemide
Order Pills Furosemide
Take Furosemide Medication
Order Cheapest Furosemide
Buy Glucophage Pills
Tablets Order Glucophage
Take Glucophage Legally
Purchase no Prescription Glucophage
Why Take Glucophage
Purchase Imitrex Free Delivery
Buying Imitrex Without Prescription
Buying Without a Prescription Imitrex Online
Buy Cheapest Imitrex
Imitrex Generic
Buying Pills Inderal
Buy Inderal no Prescription
Purchase Inderal COD
Alternative Purchase Inderal
Purchase no Prescription Inderal
Order Lasix no Prescription
Purchase Lasix COD
Purchase Lasix Without a Prescription
Buying Lasix Without Prescription
Tablets Purchase Lasix
Buy no Prescription Levaquin
Buy Levaquin Next Day Delivery
Take no Prescription Levaquin
Purchase Levaquin Generic
Buy Alternative Levaquin
Buying Lexapro no Prescription
Generic Buying Lexapro
Purchase Lexapro COD
Purchase Lexapro no Prescription
Tablets Purchase Lexapro
Buy Lipitor Free Delivery
Order Lipitor no Prescription
Online Buy Lipitor Without a Prescription
Tablets Buying Lipitor
Generic Purchase Lipitor
Purchase Lisinopril Free Delivery
Purchase Lisinopril Alternative
Take Lisinopril Without Prescription
Online Order Lisinopril Without Prescription
Tablets Buying Lisinopril
Alternative Order Methotrexate
Purchase Methotrexate COD
Why Take Methotrexate
Purchase Methotrexate Online Without Prescription
Purchase Methotrexate Online no Prescription
Cheapest Buy Nizoral
Order Nizoral Free Delivery
Purchase Nizoral by Phone
Alternative Order Nizoral
Purchase Nizoral Drug
Take Nolvadex Without Prescription
Cheapest Order Nolvadex
Take Nolvadex Drug
Purchase Online no Prescription Nolvadex
Purchase Nolvadex Medication
Nortriptyline Antidepressant
Buy Tablets Nortriptyline Online
When to Take Nortriptyline
Purchase Nortriptyline Pills
Buying Without Prescription Nortriptyline
Tablets Buy Ortho Tri-Cyclen
Order Ortho Tri-Cyclen Generic
Take no Prescription Ortho Tri-Cyclen
Purchase Ortho Tri-Cyclen COD
Take Ortho Tri-Cyclen Without Prescription
Purchase Online Without a Prescription Premarin
Pills Buying Premarin
Tablets Buying Premarin
Order Premarin COD
Tablets Buy Premarin
Buy Tablets Proscar Online
Buy Tablets Proscar
Buy no Prescription Proscar Online
Purchase Proscar Alternative
Purchase Cheapest Proscar
Buy Risperdal by Phone
Order Risperdal Medication
Generic Order Risperdal
Purchase Risperdal Online no Prescription
Buy Risperdal Next Day Delivery
Take Synthroid Free Delivery
Take Synthroid Pills
Buy Without a Prescription Synthroid
Purchase Synthroid Alternative
Take Synthroid Legally
Generic Order Topamax
Order Online Without a Prescription Topamax
Take no Prescription Topamax
Order Cheap Topamax
Buy Topamax Without a Prescription
Valtrex Acyclovir
Pills Purchase Valtrex
Generic Buying Valtrex
Online Buy Valtrex Without a Prescription
Order Valtrex COD
Purchase Online no Prescription Zithromax
Buy Zithromax Next Day Delivery
Purchase Zithromax Pills
Buy Zithromax Free Delivery
Buying Without a Prescription Zithromax Online