Skip to content

Instantly share code, notes, and snippets.

@r-marques
Last active December 25, 2015 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r-marques/a247f7ddc61b4265c651 to your computer and use it in GitHub Desktop.
Save r-marques/a247f7ddc61b4265c651 to your computer and use it in GitHub Desktop.
image shredding algorithm
from PIL import Image
from os import urandom
import random
import sys
def encode(in_file, out_file):
# read pixel data from the image and put it in a flat list
im = Image.open(in_file)
data = list(im.getdata())
# generate a random seed which will be the key and shuffle the data
seed = urandom(20).encode('hex')
random.seed(seed)
random.shuffle(data)
# create and save the new image
out = Image.new(im.mode, im.size)
out.putdata(data)
out.save(out_file)
return seed
def decode(seed, in_file, out_file):
# read the pixel data from the image and put it in a flat list
im = Image.open(in_file)
data = list(im.getdata())
# we need to perform the inverse operation we did in encode
# with the seed we create a list with the original indexes
order = range(len(data))
random.seed(seed)
random.shuffle(order)
original_data = [0] * len(data)
for index, original_index in enumerate(order):
original_data[original_index] = data[index]
# create and save the decoded image
out = Image.new(im.mode, im.size)
out.putdata(original_data)
out.save(out_file)
def usage():
print "usage: shredding.py encode in_file outfile"
print " shredding.py decode seed in_file out_file"
if __name__ == '__main__':
if '-h' in sys.argv or '--help' in sys.argv:
usage()
sys.exit(0)
elif 'encode' in sys.argv:
seed = encode(sys.argv[2], sys.argv[3])
print "File successfully encoded"
print "Seed:", seed
sys.exit(0)
elif 'decode' in sys.argv:
decode(sys.argv[2], sys.argv[3], sys.argv[4])
print "File successfully decoded"
sys.exit(0)
else:
usage()
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment