Skip to content

Instantly share code, notes, and snippets.

@yohanes
Created March 3, 2019 05:15
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 yohanes/ba8d40b865d60eb03f6fc4658977f12b to your computer and use it in GitHub Desktop.
Save yohanes/ba8d40b865d60eb03f6fc4658977f12b to your computer and use it in GitHub Desktop.
#demo XOR RC4
#Yohanes Nugroho 2019
import os
from PIL import Image
key = "YOHANES"
WIDTH=200
HEIGHT=50
IMG1="image1.png"
IMG2="image2.png"
MERGED="image1+2.png"
gentext1 = "convert -size {0}x{1} -background lightblue -fill blue -pointsize 36 -gravity east label:{2} {3}"
gentext2 = "convert -size {0}x{1} -background lightblue -fill blue -pointsize 36 -gravity west label:{2} {3}"
os.system(gentext1.format(WIDTH, HEIGHT, "Yohanes", IMG1))
os.system(gentext2.format(WIDTH, HEIGHT, "Risna", IMG2))
def load_pixels(img):
im = Image.open(img)
pixels = im.load()
width, height = im.size
all_pixels = []
for x in range(width):
for y in range(height):
r,g,b = pixels[x, y]
all_pixels += [r,g,b]
return all_pixels
def save_pixels(destimage, newpixels):
background = (0, 0, 0, 255)
im = Image.new('RGB', (WIDTH, HEIGHT), background)
width, height = im.size
pixels = im.load()
for x in range(width):
for y in range(height):
r,g,b = newpixels[0:3]
newpixels = newpixels[3:]
pixels[x,y] = (r,g,b)
im.save(destimage)
#RC4 implementation note
#https://github.com/jbremer/rc4/blob/master/LICENSE.txt
def rc4(data, key):
"""RC4 encryption and decryption method."""
S, j, out = list(range(256)), 0, []
for i in range(256):
j = (j + S[i] + ord(key[i % len(key)])) % 256
S[i], S[j] = S[j], S[i]
i = j = 0
for ch in data:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
out.append(0xff & (ch ^ S[(S[i] + S[j]) % 256]))
return out
def enc_img(image, key):
pixels = load_pixels(image)
enc = rc4(pixels, key)
save_pixels("enc-"+image, enc)
return enc
def enc_xor_img(name, enc1, enc2):
res = []
for i,j in zip(enc1, enc2):
res.append(i^j)
save_pixels(name, res)
enc1 = enc_img(IMG1, key)
enc2 = enc_img(IMG2, key)
enc_xor_img(MERGED, enc1, enc2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment