Frage

I'm looking for a small easy program to scramble and descramble a file's contents. The file is a zip file so it might contain any characters. Was thinking something like two's complement or something, but not sure how to do it in Python.

The reason for this is that my current employer has draconian internet and file installation laws and I would like to mail myself files without the mailer detecting the attachment as a zip file (which it does even if you rename it to .jpg).

I already have Python installed on my work machine.

War es hilfreich?

Lösung

You could try xor'ing the contents of the file with a specific value, creating an XOR-cipher, just be sure to read/write the file in binary mode. You'd have to test this out to see if this works for your purposes (it does fine with text files, and I don't see why it wouldn't work for binaries.)

Of course you have to use the same (key) value (for instance a character) to encode and decode - though you can use the same code for both of these operations.

Here's some code I recently put together which does just that:

import sys

def processData(filename, key):
    with open(filename, 'rb') as inf, open(filename+'.xor', 'wb') as outf:
        for line in inf:
            line = ''.join([chr(ord(c)^ord(key)) for c in line])
            outf.write(line)

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print 'Usage: xor_it filename key'
        print '       key = a single character'
    else:
        processData(sys.argv[1], sys.argv[2])

Andere Tipps

I have had success with stealthZip getting through e-mail and proxy restrictions!

However, if you do want to do it in python, you could try using pickle. Load the file in binary mode, pickle it, send it over, and unpickle it on the receiving end. I don't know how well pickle functions with binaries though.

You could also simply base64 encode the file. This will make your file larger, but has the benefit of being all ascii text (which you could then just paste in the email.)

Note this will overwrite the current file. It wouldn't be hard to change it to output to another file.

#b64.py
import base64
import sys

def help():
    print """Usage: python b64.py -[de] file
    -d\tdecode
    -e\tencode"""
    sys.exit(0)

def decode(filename):
    with open(filename) as f:
        bin = base64.b64decode(f.read())
    with open(filename,'wb') as f:
        f.write(bin)

def encode(filename):
    with open(filename,'rb') as f:
        text = base64.b64encode(f.read())
    with open(filename,'w') as f:
        f.write(text)

if len(sys.argv) != 3:
    help()

if sys.argv[1] == "-d":
    decode(sys.argv[2])
elif sys.argv[1] == "-e":
    encode(sys.argv[2])
else:
    help()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top