Created
February 12, 2025 10:50
-
-
Save AliAlmasi/2cd9a65f97bb71ebc2779ea5eac5d67b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# USAGE: python visual_cryptography.py file_to_encrypt.png | |
# $ pip install Pillow | |
from PIL import Image, ImageDraw | |
import os, sys | |
from random import SystemRandom | |
random = SystemRandom() | |
# If you want to use the more powerful PyCrypto ($ pip install pycrypto) then uncomment the next line and comment out the previous two lines | |
#from Crypto.Random import random | |
if len(sys.argv)!=2: | |
sys.exit("This takes one argument; the image to be encrypted.") | |
infile = str(sys.argv[1]) | |
if not os.path.isfile(infile): | |
sys.exit("The file '{infile}' does not exist.".format(infile = infile)) | |
img = Image.open(infile) | |
f, e = os.path.splitext(infile) | |
out_filename_A = f+"_A.png" | |
out_filename_B = f+"_B.png" | |
img = img.convert('1') | |
width = img.size[0]*2 | |
height = img.size[1]*2 | |
out_image_A = Image.new('1', (width, height)) | |
out_image_B = Image.new('1', (width, height)) | |
draw_A = ImageDraw.Draw(out_image_A) | |
draw_B = ImageDraw.Draw(out_image_B) | |
patterns=((1,1,0,0), (1,0,1,0), (1,0,0,1), (0,1,1,0), (0,1,0,1), (0,0,1,1)) | |
for x in range(0, int(width/2)): | |
for y in range(0, int(height/2)): | |
pixel=img.getpixel((x,y)) | |
pat=random.choice(patterns) | |
draw_A.point((x*2, y*2), pat[0]) | |
draw_A.point((x*2+1, y*2), pat[1]) | |
draw_A.point((x*2, y*2+1), pat[2]) | |
draw_A.point((x*2+1, y*2+1), pat[3]) | |
if pixel==0: | |
draw_B.point((x*2, y*2), 1-pat[0]) | |
draw_B.point((x*2+1, y*2), 1-pat[1]) | |
draw_B.point((x*2, y*2+1), 1-pat[2]) | |
draw_B.point((x*2+1, y*2+1), 1-pat[3]) | |
else: | |
draw_B.point((x*2, y*2), pat[0]) | |
draw_B.point((x*2+1, y*2), pat[1]) | |
draw_B.point((x*2, y*2+1), pat[2]) | |
draw_B.point((x*2+1, y*2+1), pat[3]) | |
out_image_A.save(out_filename_A, 'PNG') | |
out_image_B.save(out_filename_B, 'PNG') | |
sys.exit("Done.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example image: https://iili.io/2m0iDB4.png
Split part A: https://iili.io/2m0sqEQ.png
Split part B: https://iili.io/2m0sFQj.png
Both parts merged: https://iili.io/2m0sfCx.png