-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscramb.py
2367 lines (1756 loc) · 72.3 KB
/
scramb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
#########################################################################################################
#
# Scramb.py is a region based JPEG Image Scrambler
#
VERSION = "0.5.0"
#
# For updates see git repo at:
# https://github.com/snekbeater/scrambpy
#
# Author: Snekbeater
# Contact: snekbeater at protonmail.com
#
#
# This version of Scramb.py uses and thus can encode and decode images with
# the following encoder version:
HEADER_VERSION_ENCODER = 2
# It can decode images down to the following encoder version:
HEADER_VERSION_ENCODER_MIN = 1
#
#
# Copyright (C) 2022 snekbeater
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
#########################################################################################################
import sys # commandline args + exit
import importlib # test modules exists
import subprocess # to run pip if pillow is missing
# check if PIL / Pillow is installed
# be helpful and try to install it if it is not present (for our Windows Users out there :-D )
try:
importlib.import_module("PIL")
except ImportError:
print("PIL / Pillow module is not installed with your Python installation!")
print("")
print("You can install it yourself or scramb.py can do this for you.")
print("Do it yourself with: pip install Pillow on Linux")
print(" pip.exe install Pillow on Windows")
print("")
answer = input("Do you want scramb.py to install it for you now? [y/n]")
if answer == "y":
# from https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip'])
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'Pillow'])
print("")
print("Installation code done")
input("Please press Enter to leave and then restart scramb.py as you just did before ...")
sys.exit()
from PIL import Image, ImageDraw, ImageFilter, ImageChops
import os # for changing filenames and look if files exist
import random # mix it
import math # ceil round etc
from io import BytesIO # serialize png and other files
import getopt # commandline arg handler
import pickle # serialize dictionaries V01
import json # serialize dictionaries V02
import hashlib # for password hash generation
from getpass import getpass # for getting the password from commandline
import time # for real random number generation of pki scrambler
import binascii # for real random number generation of pki scrambler
import secrets # for real random number generation of pki scrambler
import tarfile # Tar Module: https://docs.python.org/3/library/tarfile.html
from gzip import GzipFile # for public key image
HEADER_VERSION_MAGIC_NUMBER = 42
# Type IDs:
CHUNK_TYPE_RAW = 0 # raw data, not more specified
CHUNK_TYPE_TEXT = 1 # text
CHUNK_TYPE_PNG = 2 # png
CHUNK_TYPE_IMAGE_INFO = 3 # image info
CHUNK_TYPE_SCRAMBLER_PARAMETERS = 4 # scrambler parameters
CHUNK_TYPE_PUBLIC_KEY = 5 # public key
CHUNK_TYPE_TAR = 6 # tar.gz
CHUNK_TYPE_ENCRYPTED_TAR = 7 # encrypted tar.gz
# ...
CHUNK_TYPE_EXTENDED_HEADER = 64 # extended header (more bytes follow e.g. bigger size, other types, future stuff)
SCRAMBLERPARAMETERSDATAFIELD_BLOWUP = 'b'
SCRAMBLERPARAMETERSDATAFIELD_SCRAMBLER = 'a' # a like algorithm
SCRAMBLERPARAMETERSDATAFIELD_SEED = 's'
SCRAMBLERPARAMETERSDATAFIELD_ROUNDS = 'r'
SCRAMBLERPARAMETERSDATAFIELD_DISTANCE = 'd'
SCRAMBLERPARAMETERSDATAFIELD_PERCENTAGEOFTURNS = 't'
SCRAMBLERPARAMETERSDATAFIELD_PASSWORDUSED = 'p'
SCRAMBLERPARAMETERSDATAFIELD_PATCHIMAGE = 'i'
SCRAMBLERPARAMETERSDATAFIELD_CLOAKIMAGE = 'c'
#
STANDARD_JPEG_QUALITY = 100 # standard save quality
# the small "Scrambled with scramb.py"-Logo as a png file
# If you do not trust encoded stuff in code you run, you can erase this constant.
# You then just do not get a logo anymore
LOGO = b"\x80\x03C\x92\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00]\x00\x00\x00\x06\x01\x00\x00\x00\x00\x89C\xafZ\x00\x00\x00YIDATx\x9c\x01N\x00\xb1\xff\x00`\x00\x02\x10\x08\x02\x10\x00\x00\x02\x07(\x020\x00\x00\x00\x00\xfe\x80\x00\x00\x00\xfd\x80\x02\xb3l\xf1\x820\xaaH3l\xf1\x80\x00\x04\xe1\xff\xb7\xc3\x10\x00\xbc\x11\xd6\xb7\xc3\x8c\x02p\x08\x00\xff\x00\xa8\x00\xd0\x08\x00\xfd\x00\x02\xcf\xfc\x01?\xf0\x00\xc0O\xfc\x01P\x10S\xe2\x1a'o\x8da/\x00\x00\x00\x00IEND\xaeB`\x82q\x00."
def importGnuPG():
# GnuPG Module: https://docs.red-dove.com/python-gnupg/
try:
importlib.import_module("gnupg")
except ImportError:
print("python-gnupg is not installed with your Python installation!")
print("")
print("You can install it yourself or scramb.py can do this for you.")
print("Do it yourself with: pip install python-gnupg on Linux")
print(" pip.exe install python-gnupg on Windows")
print("")
print("(Note that there is also a package 'gnupg' which is not used here)")
print("")
answer = input("Do you want scramb.py to install it for you now? [y/n]")
if answer == "y":
# from https://pip.pypa.io/en/latest/user_guide/#using-pip-from-your-program
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip'])
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'python-gnupg'])
print("")
print("Installation code done")
input("Please press Enter to leave and then restart scramb.py as you just did before ...")
sys.exit()
def drawByte(draw, theByte, xpos, ypos):
# draws theByte at pixel xpos, ypos of draw object of an image
for y in range(2):
for x in range(2):
rectDuo = theByte & 3
luma = rectDuo * 85 # four possible values between 0 and 255
draw.rectangle(((x*4)+xpos,(y*4)+ypos,(x*4)+xpos+3,(y*4)+ypos+3), fill=(luma,luma,luma), outline=None)
theByte = theByte >> 2
def readByte(image, xpos, ypos):
theByte = 0
for y in (1,0):
for x in (1,0):
values = []
for suby in range(4):
for subx in range(4):
r, g, b = image.getpixel((xpos+x*4+subx, ypos+y*4+suby))
values.append(r)
values.append(g)
values.append(b)
valueSum = 0
for value in values:
valueSum = valueSum + value
valueMedian = valueSum / len(values)
rectDuo = round(valueMedian / 85) # four possible values between 0 and 255
theByte = theByte | rectDuo
if (x+y > 0): # last round no shift at the end
theByte = theByte << 2
return theByte
def serialize(image,byteArray) -> Image:
imageSpaceWidth = math.ceil(image.width / 8)
imageSpaceHeight = math.ceil(image.height / 8)
# lines on top, bottom ... etc
top = 1
bottom = 0
left = 0
right = 0
# direction of space search
direction = 0
# space in byte
freeSpace = 0
neededSpace = len(byteArray)
# fullX = no of blocks per line or column
fullLine = 0
fullColumn = 0
while (freeSpace < neededSpace):
if direction == 0: # right
top = top + 1
elif direction == 1: # down
if right == 0:
right = 2
else:
right = right + 1
elif direction == 2: # left
if bottom == 0:
bottom = 2
else:
bottom = bottom + 1
elif direction == 3: # up
if left == 0:
left = 2
else:
left = left + 1
# calculate space
fullLine = imageSpaceWidth + left + right
fullColumn = imageSpaceHeight + bottom + top
freeBlocks = (fullLine * top + fullLine * bottom + imageSpaceHeight * (left + right))
freeSpace = freeBlocks # HEADER_VERSION_ENCODER 1: a block equals a byte
# add safe zone (8 pixel distance between data and image
freeSpace = freeSpace - imageSpaceWidth
if right > 0:
freeSpace = freeSpace - imageSpaceHeight
if left > 0:
freeSpace = freeSpace - imageSpaceHeight
if bottom > 0:
freeSpace = freeSpace - imageSpaceWidth
direction = direction + 1
if direction == 4:
direction = 0
croppedim = image.crop((-8 * left, -8 * top, imageSpaceWidth*8 + 8 * right, imageSpaceHeight*8 + 8 * bottom))
draw = ImageDraw.Draw(croppedim)
# positions in blocks
posX = 0
posY = 0
# margin from edge of image in blocks
marginTop = 0
marginLeft = 0
marginBottom = 0
marginRight = 0
direction = 0
# position in byteArray
i = 0
while (i < len(byteArray)):
drawByte(draw, byteArray[i], posX*8, posY*8)
i = i + 1
if direction == 0:
if posX + 1 < fullLine - marginRight:
posX = posX + 1
else:
direction = 1
posY = posY + 1
marginTop = marginTop + 1
elif direction == 1:
if posY + 1 < fullColumn - marginBottom:
posY = posY + 1
else:
direction = 2
posX = posX - 1
marginRight = marginRight + 1
elif direction == 2:
if posX > marginLeft:
posX = posX - 1
else:
direction = 3
posY = posY - 1
marginBottom = marginBottom + 1
elif direction == 3:
if posY > marginTop:
posY = posY - 1
else:
direction = 0
posX = posX + 1
marginLeft = marginLeft + 1
return (croppedim, left*8, top*8)
def deserialize(image, length):
byteArray = []
posX = 0
posY = 0
marginTop = 0
marginLeft = 0
marginBottom = 0
marginRight = 0
direction = 0
i = 0
# TODO %8 images.. no more needed, since scrambled images always are %8=0
# correct /8 images
fullLine = math.floor(image.width / 8)
fullColumn = math.floor(image.height / 8)
# offset in blocks for the image data (image starts at (offsetX*8, offsetY*8) )
offsetX = 0
offsetY = 2
while (i < length):
byte1 = readByte(image, posX*8, posY*8)
byteArray.append(byte1)
i = i + 1
if direction == 0: #right
if posX + 1 < fullLine - marginRight:
posX = posX + 1
else:
direction = 1
posY = posY + 1
marginTop = marginTop + 1
elif direction == 1: #down
if posY + 1 < fullColumn - marginBottom:
posY = posY + 1
else:
direction = 2
posX = posX - 1
marginRight = marginRight + 1
elif direction == 2: #left
if posX > marginLeft:
posX = posX - 1
else:
direction = 3
posY = posY - 1
marginBottom = marginBottom + 1
offsetX = offsetX + 1
elif direction == 3: #up
if posY > marginTop:
posY = posY - 1
else:
direction = 0
posX = posX + 1
marginLeft = marginLeft + 1
offsetY = offsetY + 1
if offsetX > 0:
offsetX = offsetX + 1
return (byteArray, offsetX, offsetY)
def switchBlocks(image, xpos1, ypos1, xpos2, ypos2):
block1 = image.crop((xpos1,ypos1,xpos1+8,ypos1+8))
block2 = image.crop((xpos2,ypos2,xpos2+8,ypos2+8))
image.paste(block1,(xpos2,ypos2),mask=None)
image.paste(block2,(xpos1,ypos1),mask=None)
def copyBlock(imageSource,imageDest, xposSource, yposSource, xposDest, yposDest):
block = imageSource.crop((xposSource,yposSource,xposSource+8,yposSource+8))
imageDest.paste(block,(xposDest,yposDest),mask=None)
def createChunk(data, chunkType):
#future:
# type bit: 7 6 543210
# EEC? extendedSize type ID
#
#Type IDs (bits 0-5):
# 0 raw data, not more specified
# 1 text
# 2 png
# 3 image info
# 4 scrambler parameters
# ...
# 64 extended header (more bytes follow as a header e.g. other types, special stuff)
#
#extended Size (bit 6):
# =0 -> chunk max 65.536 bytes, 2 bytes size follow
# =1 -> chunk max 16.777.216 bytes, 3 bytes size follow
if (len(data) >= pow(2,24)):
print("Chunk is bigger than allowed. Panic")
sys.exit(3)
elif (len(data) >= pow(2,16)):
loByte = len(data) & 255
midByte = (len(data) >> 8) & 255
hiByte = (len(data) >> 16) & 255
chunkType = chunkType | 64 # switch bit for extended size
data.insert(0,chunkType)
data.insert(1,hiByte)
data.insert(2,midByte)
data.insert(3,loByte)
else:
loByte = len(data) & 255
hiByte = len(data) >> 8
data.insert(0,chunkType)
data.insert(1,hiByte)
data.insert(2,loByte)
return data
def decodeChunkType(data, seek):
return data[seek] & 63
def decodeChunkExtendedLength(data, seek):
return data[seek] & 64 > 0
def decodeChunkLength(data, seek):
# returns tupel (header bytes, data bytes)
if decodeChunkExtendedLength(data, seek):
return (4, (data[seek+1] << 16) + (data[seek+2] << 8) + data[seek+3])
else:
return (3, (data[seek+1] << 8) + data[seek+2])
def getChunkData(data, seek):
(headerlength, length) = decodeChunkLength(data, seek)
if decodeChunkExtendedLength(data, seek):
return data[seek+4:seek+4+length]
else:
return data[seek+3:seek+3+length]
def createImageInfo(image):
data = []
loByte = image.width & 255
hiByte = image.width >> 8
data.append(hiByte)
data.append(loByte)
loByte = image.height & 255
hiByte = image.height >> 8
data.append(hiByte)
data.append(loByte)
return data
def decodeImageInfo(data):
return ( (data[0] << 8) + data[1] , (data[2] << 8) + data[3])
def calculateResidual(img1, img2):
residu = 0
pixels = 0
diff = ImageChops.difference(img1, img2)
for y in range(diff.height):
for x in range(diff.width):
r, g, b = diff.getpixel((x, y))
residu = residu + r + g + b
pixels = pixels + 3
return residu / pixels
def calculateResidualFast(img1, img2):
residu = 0
pixels = 0
#img1 = img1.resize((math.floor(img1.width/100),math.floor(img1.height/100)))
#img2 = img2.resize((math.floor(img2.width/100),math.floor(img2.height/100)))
#img1 = img1.convert('L')
#img2 = img2.convert('L')
diff = ImageChops.difference(img1, img2)
diff = diff.resize((math.floor(diff.width/10),math.floor(diff.height/10)))
#diff = diff.convert('L')
for y in range(diff.height):
for x in range(diff.width):
r, g, b = diff.getpixel((x, y))
residu = residu + r + g + b
pixels = pixels + 3
#r = diff.getpixel((x, y))
#residu = residu + r
#pixels = pixels + 1
return residu / pixels
def calculateSubMapScramblePercent(submap1, submap2):
same = 0
for i in range(len(submap1)):
if submap1[i] == submap2[i]:
same = same + 1
return same / len(submap1)
# from https://stackoverflow.com/questions/19140589/linear-congruential-generator-in-python
def lcg(x, a, c, m):
while True:
x = (a * x + c) % m
yield x
def random_uniform_sample(n, interval, seed=0):
a, c, m = 1103515245, 12345, 2 ** 31
bsdrand = lcg(seed, a, c, m)
lower, upper = interval[0], interval[1]
sample = []
for i in range(n):
observation = (upper - lower) * (next(bsdrand) / (2 ** 31 - 1)) + lower
sample.append(round(observation))
return sample
def createSubstitutionMapFromMask(maskimage):
serialPos = 0
substitutionMap = []
for y in range(maskimage.height):
for x in range(maskimage.width):
luma = maskimage.getpixel((x,y))
if luma > 0:
substitutionMap.append(serialPos)
serialPos = serialPos + 1
return substitutionMap
def createSubstitutionMatrixFromMask(maskimage):
matrix = [None] * maskimage.width
for y in range (maskimage.width):
matrix[y] = [None] * maskimage.height
for y in range(maskimage.height):
for x in range(maskimage.width):
luma = maskimage.getpixel((x,y))
if luma > 0:
matrix[x][y] = (x,y)
return matrix
def turnBlockInMatrix(matrix, x, y, clockwise=True):
if (x + 1 < len(matrix)) and (y + 1 < len(matrix[x-1])):
if (matrix[x][y] is not None) and (matrix[x+1][y] is not None) and (matrix[x][y+1] is not None) and (matrix[x+1][y+1] is not None):
# 0, 0 +1, 0
#
# 0,+1 +1.+1
if clockwise:
t = matrix[x ][y ]
matrix[x ][y ] = matrix[x ][y+1]
matrix[x ][y+1] = matrix[x+1][y+1]
matrix[x+1][y+1] = matrix[x+1][y ]
matrix[x+1][y ] = t
else:
t = matrix[x+1][y ]
matrix[x+1][y ] = matrix[x+1][y+1]
matrix[x+1][y+1] = matrix[x ][y+1]
matrix[x ][y+1] = matrix[x ][y ]
matrix[x ][y ] = t
def scrambleBlocksOfImageWithMatrix(matrix, image, reverse=False):
originalImage = image.copy()
for y in range(len(matrix[0])):
for x in range(len(matrix)):
if matrix[x][y] is not None:
if reverse == False:
copyBlock(originalImage,image, x*8, y*8,matrix[x][y][0]*8,matrix[x][y][1]*8)
else:
copyBlock(originalImage,image,matrix[x][y][0]*8,matrix[x][y][1]*8, x*8, y*8)
return image
def mixSubstitutionMatrix(matrix, seed = 0, percentOfTurns = 20):
print("calculating subseeds...")
print("seed ", seed)
subSeeds = random_uniform_sample(3, [0,1000], seed=seed)
size = len(matrix) * len(matrix[0])
print("blocks ", size)
numberOfTurns = round(size * percentOfTurns * 0.01)
print("number of turns", numberOfTurns)
xPositions = random_uniform_sample(numberOfTurns, [0,len(matrix)-1], seed=seed+subSeeds[0])
yPositions = random_uniform_sample(numberOfTurns, [0,len(matrix[0])-1], seed=seed+subSeeds[1])
reverse = random_uniform_sample(numberOfTurns, [0,1], seed=seed+subSeeds[2])
for i in range(numberOfTurns):
turnBlockInMatrix(matrix, xPositions[i], yPositions[i], clockwise = reverse[i])
return matrix
def mixSubstitutionMap_ultra(substitutionMap, seed = 0, rounds = 4):
# really totally mixed
randnumbers = random_uniform_sample(len(substitutionMap)*rounds*2, [0,len(substitutionMap)*2000], seed=seed)
substitutionMapTemp = []
i = 0
for rou in range(rounds):
while len(substitutionMap) > 0:
value = substitutionMap.pop(randnumbers[i]%len(substitutionMap))
substitutionMapTemp.append(value)
i = i + 1
while len(substitutionMapTemp) > 0:
value = substitutionMapTemp.pop(randnumbers[i]%len(substitutionMapTemp))
substitutionMap.insert(0,value)
i = i + 1
return substitutionMap
def mixSubstitutionMap_heavy(substitutionMap, seed = 0, rounds = 4):
# total mixed
randnumbers = random_uniform_sample(len(substitutionMap)*rounds, [0,len(substitutionMap)-1], seed=seed)
for i in range(len(randnumbers)):
value = substitutionMap.pop(randnumbers[i])
substitutionMap.append(value)
return substitutionMap
def mixSubstitutionMap_medium(substitutionMap, seed = 0, distance=10, rounds = 1):
# slightly mixed
#rounds = 1
randnumbers = random_uniform_sample(len(substitutionMap)*rounds, [distance*-1,distance], seed=seed)
for r in range(rounds):
for i in range(len(substitutionMap)):
value = substitutionMap.pop(i)
substitutionMap.insert(i+randnumbers[i+len(substitutionMap)*r],value)
return substitutionMap
def createJPEGSampleInMemory(image, quality=80):
memoryFile = BytesIO()
image.save(memoryFile, format='JPEG', quality=quality)
return Image.open(memoryFile)
#def copyBlock(sourceImage, sx, sy, targetImage, tx, ty):
## block1 = sourceImage.crop((sx,sy,sx+8,sy+8))
# targetImage.paste(block1,(tx,ty),mask=None)
def transferBlocks(sourceImage, sourceMaskImage, targetImage, targetMaskImage):
#print("Blocks Source: ",countBlocksOfMask(sourceMaskImage))
#print("Blocks Target: ",countBlocksOfMask(targetMaskImage))
if (countBlocksOfMask(sourceMaskImage) < countBlocksOfMask(targetMaskImage)):
blocksToCopy = countBlocksOfMask(sourceMaskImage)
else:
blocksToCopy = countBlocksOfMask(targetMaskImage)
sx = -1
sy = 0
tx = -1
ty = 0
copiedBlocks = 0
while (copiedBlocks < blocksToCopy):
while True:
sx = sx + 1
if sx == sourceMaskImage.width:
sy = sy + 1
sx = 0
if (sourceMaskImage.getpixel((sx,sy)) > 0):
break
while True:
tx = tx + 1
if tx == targetMaskImage.width:
ty = ty + 1
tx = 0
if (targetMaskImage.getpixel((tx,ty)) > 0):
break
copyBlock(sourceImage,targetImage,sx*8,sy*8,tx*8,ty*8)
copiedBlocks = copiedBlocks + 1
def transferBlocksRandom(sourceImage, sourceMaskImage, targetImage, targetMaskImage, tint=None, randomTint=False, invertColor=False):
blocksToCopy = countBlocksOfMask(targetMaskImage)
sx = -1
sy = 0
tx = -1
ty = 0
copiedBlocks = 0
while (copiedBlocks < blocksToCopy):
while True:
# TODO: might take a while when only a few allowed blocks are in source mask...
sx = random.randint(0,sourceMaskImage.width-1)
sy = random.randint(0,sourceMaskImage.height-1)
if (sourceMaskImage.getpixel((sx,sy)) > 0):
break
while True:
tx = tx + 1
if tx == targetMaskImage.width:
ty = ty + 1
tx = 0
if (targetMaskImage.getpixel((tx,ty)) > 0):
break
copyBlock(sourceImage,targetImage,sx*8,sy*8,tx*8,ty*8)
if (tint != None) or randomTint or invertColor:
if randomTint:
r = random.randint(0,16)
g = random.randint(0,16)
b = random.randint(0,16)
tint = (r*r,g*g,b*b)
# tint = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
tintBlock(targetImage,tx,ty, tint, invertColor)
copiedBlocks = copiedBlocks + 1
def tintBlock(image, sx, sy, tint=None, invertColor=False):
for y in range(0,8):
for x in range(0,8):
r, g, b = image.getpixel((sx*8 + x,sy*8 + y))
if invertColor:
r = 255 - r
g = 255 - g
b = 255 - b
newColor = (r,g,b)
if tint != None:
tr, tg, tb = tint
newColor = (int((r+tr)/ 2),int((g+tg)/ 2),int((b+tb)/ 2))
# test result as stripes for comparison:
#if (x%2==0):
image.putpixel((sx*8+x,sy*8+y), newColor)
def createShadowImageTargetBlock(image, sx, sy):
for y in range(0,8):
for x in range(0,8):
if (x%2==y%2):
image.putpixel((sx*8+x,sy*8+y), (0,0,0))
else:
image.putpixel((sx*8+x,sy*8+y), (255*(x%2),255*(y%2),255))
def createShadowImageTargetBlocks( targetImage, targetMaskImage):
for y in range(targetMaskImage.height):
for x in range(targetMaskImage.width):
luma = targetMaskImage.getpixel((x,y))
if luma > 0:
createShadowImageTargetBlock(targetImage,x,y)
def isShadowImageTargetBlock(image, sx, sy):
for y in range(0,8):
for x in range(0,8):
if (x%2==y%2):
if image.getpixel((sx*8+x,sy*8+y)) != (0,0,0):
return False
else:
if image.getpixel((sx*8+x,sy*8+y)) != (255*(x%2),255*(y%2),255):
return False
return True
def stampShadowImage(image, shadowImage):
for y in range(int(image.height / 8)):
for x in range(int(image.width / 8)):
if isShadowImageTargetBlock(image,x,y):
copyBlock(shadowImage,image,x*8,y*8,x*8,y*8)
def scrambleBlocksOfImageWithCopy(substitutionMapSource, substitutionMap, image, reverse=False):
# image must have %8=0 pixel width/height at this point!
# mask and thus subMap must fit to that!
sourceim = image.copy()
for ii in range(len(substitutionMap)):
blocksWidth = math.floor(image.width / 8)
if reverse:
i = len(substitutionMap) - 1 - ii
else:
i = ii
x1 = substitutionMapSource[i] % blocksWidth
y1 = math.floor(substitutionMapSource[i] / blocksWidth)
x2 = substitutionMap[i] % blocksWidth
y2 = math.floor(substitutionMap[i] / blocksWidth)
copyBlock(sourceim,image, x1*8, y1*8,x2*8,y2*8)
return image
def scrambleBlocksOfImageWithSwitch(substitutionMapSource, substitutionMap, image, reverse=False):
# image must have %8=0 pixel width/height at this point!
# mask and thus subMap must fit to that!
for ii in range(len(substitutionMap)):
blocksWidth = math.floor(image.width / 8)
if reverse:
i = len(substitutionMap) - 1 - ii
else:
i = ii
x1 = substitutionMapSource[i] % blocksWidth
y1 = math.floor(substitutionMapSource[i] / blocksWidth)
x2 = substitutionMap[i] % blocksWidth
y2 = math.floor(substitutionMap[i] / blocksWidth)
switchBlocks(image, x1*8, y1*8,x2*8,y2*8)
return image
def createRandomSubMaskImage(pngMaskSource, seed=0):
mode = '1'
color = (0)
subMaskImage = Image.new(mode, (pngMaskSource.width,pngMaskSource.height), color)
randomPixels = random_uniform_sample(pngMaskSource.height * pngMaskSource.width, [0,1], seed)
for y in range(pngMaskSource.height):
for x in range(pngMaskSource.width):
luma = pngMaskSource.getpixel((x,y))
if luma > 0:
subMaskImage.putpixel((x,y), randomPixels[x*y])
return subMaskImage
def invertSubMaskImage(pngMaskSource, subMaskImageSource):
mode = '1'
color = (0)
subMaskImage = Image.new(mode, (pngMaskSource.width,pngMaskSource.height), color)
for y in range(pngMaskSource.height):
for x in range(pngMaskSource.width):
luma = pngMaskSource.getpixel((x,y))
if luma > 0:
subMaskImage.putpixel((x,y), 1 - subMaskImageSource.getpixel((x,y)))
return subMaskImage
def invertMaskImage(pngMaskSource):
mode = '1'
color = (0)
subMaskImage = Image.new(mode, (pngMaskSource.width,pngMaskSource.height), color)
for y in range(pngMaskSource.height):
for x in range(pngMaskSource.width):
subMaskImage.putpixel((x,y), 1 - pngMaskSource.getpixel((x,y)))
return subMaskImage
def placeLogo(image, xpos, ypos):
if ("LOGO" in globals()): # check if LOGO constant exists in case the user deletes it for security
logoData = pickle.loads( bytes(LOGO) )
logoFile = BytesIO(bytearray(logoData))
logoImage = Image.open(logoFile)
print("Placing Logo at ",xpos+1, ypos+1)
image.paste(logoImage,(xpos+1,ypos+1),mask=None)
return image
def resizeQuads(image):
# shrinks an image to 50% (used for images that where blown up to 200%
# ignores 50% of pixels in a way that it does not use the outermost pixels of an 16x16 block
# which mostly will have compression artifacts (~ are darker than their neighbour
#
# . . . . . . . . . . . . . . . .
# . a . a . a . a . a . a . a a .
# . . . . . . . . . . . . . . . .
# . a . a . a . a . a . a . a a .
# . . . . . . . . . . . . . . . . => a a a a a a a a
# . a . a . a . a . a . a . a a . a a a a a a a a
# . . . . . . . . . . . . . . . . a a a a a a a a
# . a . a . a . a . a . a . a a . a a a a a a a a
# . . . . . . . . . . . . . . . . a a a a a a a a
# . a . a . a . a . a . a . a a . a a a a a a a a
# . . . . . . . . . . . . . . . . a a a a a a a a
# . a . a . a . a . a . a . a a . a a a a a a a a
# . . . . . . . . . . . . . . . .
# . a . a . a . a . a . a . a a .
# . a . a . a . a . a . a . a a .
# . . . . . . . . . . . . . . . .
resultim = image.resize((int(image.width / 2), int(image.height / 2)),resample=Image.NEAREST)
w = [1,1,1,1,1,1,1,0]
v = [1,1,1,1,1,1,1,0]
for y in range(resultim.height):
for x in range(resultim.width):
r, g, b = image.getpixel((x*2+v[x%8], y*2+w[y%8]))
resultim.putpixel((x,y), (r,g,b))
return resultim
def calculateChecksum(data):
checksum = 0
for entry in data:
checksum = (checksum & 255) ^ (entry & 255)
return checksum
def calculatePasswordSeed(password):
pw_bytes = password.encode('utf-8')
hashed_password = hashlib.sha256(pw_bytes).hexdigest()
passwordSeed = int(hashed_password,16)
passwordSeed = passwordSeed % 100000000000000000
return passwordSeed
def countBlocksOfMask(maskimage):
numberOfBlocks = 0
for y in range(maskimage.height):
for x in range(maskimage.width):
luma = maskimage.getpixel((x,y))
if luma > 0:
numberOfBlocks = numberOfBlocks + 1
return numberOfBlocks
def createTar():
tarFile = BytesIO()
tar = tarfile.open(fileobj=tarFile, mode="w:gz")
return (tarFile, tar)
def openTar(bytesData):
tarFile = BytesIO()
tarFile.write(bytesData)
tarFile.seek(0)
tar = tarfile.open(fileobj=tarFile, mode="r:gz")
return tar
def insertFileIntoTar(tar, filename, bytesData):
binaFile = BytesIO()
binaFile.write(bytesData)
membertarinfo = tarfile.TarInfo(filename)
membertarinfo.size = binaFile.getbuffer().nbytes
binaFile.seek(0)
tar.addfile(membertarinfo, fileobj=binaFile)
binaFile.close()
def closeTar(tar):
tar.close()
def printHelp():
print("")
print("Scramble:")
print(" scramb.py -i <inputfile> [-m <mask.png/.jpg>] -o <outputfile.jpg> [OPTIONS]")
print(" You must use -m and/or -s for scramb.py to detect that you want to scramble")
print("Descramble:")
print(" scramb.py <inputfile.jpg> (also usable for drag & drop)")
print(" scramb.py -i <inputfile.jpg> -o <outputfile.jpg>")
print("Calculate Residue:")
print(" scramb.py -r <imagefile1.jpg> <imagefile2.jpg>")
print("Create GnuPG Public Key Image:")
print(" scramb.py --export-public-key <key-id> -i <center-image> -o <outputfile.jpg>")
print("Import GnuPG Public Key Image into your keyring:")
print(" scramb.py <publicKeyImageFile.jpg> (also usable for drag & drop)")