-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimageencode.py
More file actions
269 lines (235 loc) · 10.3 KB
/
imageencode.py
File metadata and controls
269 lines (235 loc) · 10.3 KB
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
__author__ = 'nich'
import os
import jinja2
import webapp2
from PIL import Image
import json
import cloudstorage as gcs
import time
from io import BytesIO
from itertools import izip_longest # for Python 2.x
import urllib
template_dir = os.path.dirname(__file__)
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)
client_id = 'f01e2c9c566d815'
client_secret = '67dfcab0bf2aab5ff531d1514b01117aa0dd5967'
# must be divisible by 3
SECRET_KEY = '000010101000000110011100111110011100000111001001000110100101011101111000111001001'
SECRET_LENGTH = len(SECRET_KEY)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class Home(Handler):
def get(self):
self.render('home.html')
def url_to_img(url):
try:
handle = urllib.urlopen(url)
return Image.open(BytesIO(bytearray(handle.read())))
except:
return None
class Encode(Handler):
"""Create a file.
The retry_params specified in the open call will override the default
retry params for this particular file handle.
Args:
filename: filename.
"""
def make_file(self, filename, img):
write_retry_params = gcs.RetryParams(backoff_factor=1.1)
gcs_file = gcs.open(filename, 'w', content_type='image/png', options={'x-goog-acl': 'public-read'},
retry_params=write_retry_params)
img.save(gcs_file, 'png')
gcs_file.close()
def modify_value(self, position_in_message, binary_message, pix_map, i,j, colorType):
current_pixel = pix_map[i, j]
if position_in_message >= len(binary_message):
return current_pixel[colorType]
new_val = bin(current_pixel[colorType])
new_val = list(new_val)
new_val[-1] = binary_message[position_in_message]
new_val = int("".join(new_val), 2)
return new_val
def encode(self, message, image, password="password"):
if password == None or len(password)==0:
password="password"
binary_message = ''.join('{:08b}'.format(ord(c)) for c in password)
binary_message += ''.join('{:08b}'.format(ord(c)) for c in message)
binary_message += '00000000'
binary_message = SECRET_KEY + '{:08b}'.format(len(password)*8)+ binary_message
pix_map = image.load()
position_in_message = 0
length = len(binary_message)
for i in range(image.size[0]): # for every pixel:
for j in range(image.size[1]):
newPix = []
for k in range(0,3):
newPix.append(int(self.modify_value(position_in_message,binary_message, pix_map, i,j,k)))
position_in_message +=1
pix_map[i,j]=tuple(newPix)
if position_in_message >= length:
return
def post(self):
if self.request.get('pic'):
img = Image.open(BytesIO(self.request.get('pic')))
elif self.request.get('url'):
img = url_to_img(self.request.get('url'))
if not img:
self.write('Could not open the image.')
return
msg = self.request.get('msg')
resp = dict()
if img and msg:
filename = '/obrgjagm1v6rb0/' + str(int(round(time.time() * 1000))) + '.png'
# Encodes the text into the image
print 'encoding'
self.encode(msg, img, self.request.get('key'))
print 'just encoded'
# Creates a file with the given name
self.make_file(filename, img)
link = 'http://storage.googleapis.com' + filename
if self.request.get('down_link'):
resp['down_link'] = link
#return webapp2.redirect('http://storage.googleapis.com' + filename)
if self.request.get('link'):
resp['link'] = link
self.write(json.dumps(resp))
class Decode(Handler):
def grouper(self, n, iterable, padvalue=None):
"""grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"""
return izip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
def compare_index(self, current_pixel, colorType, compare_index):
if not current_pixel:
return True
val = bin(current_pixel[colorType])
last_val = val[-1]
if compare_index<SECRET_LENGTH and last_val != SECRET_KEY[compare_index]:
return True
return False
def is_done(self, bin_list, size):
if size % 8 == 0:
if sum(int(a) for a in bin_list[-8:]) == 0:
return True
return False
def decode(self, image, passwords=[]):
passwords.insert(0,"password")
message = ""
compare_index = 0
pix_map = image.load()
binCount=''
passLength = 0
password = ''
passwordList=[]
for i in range(image.size[0]):
for j in range(image.size[1]):
if compare_index ==SECRET_LENGTH+8+passLength:
break
current_pixel = pix_map[i, j]
for k in range(0,3):
if self.compare_index(current_pixel, k, compare_index):
return None
compare_index += 1
if compare_index > SECRET_LENGTH:
binCount += str(bin(current_pixel[k])[-1])
if compare_index == SECRET_LENGTH+8:
passLength=int(binCount,2)
elif compare_index > SECRET_LENGTH+8:
#password+= str(bin(current_pixel[k])[-1])
passwordList.append(str(bin(current_pixel[k])[-1]))
if compare_index == SECRET_LENGTH+8+passLength:
password = self.grouper(8,''.join(passwordList),0)
break
asciiPassword = ''
for byte in password:
character = ''.join(byte)
asciiPassword += str(unichr(int(character, 2)))
binary_message = ""
binary_message_list=[]
cur = 0
if asciiPassword in passwords:
for i in range(image.size[0]):
for j in range(image.size[1]):
current_pixel = pix_map[i, j]
red_val = bin(current_pixel[0])
green_val = bin(current_pixel[1])
blue_val = bin(current_pixel[2])
last_red_bit = red_val[len(red_val) - 1]
last_green_bit = green_val[len(green_val) - 1]
last_blue_bit = blue_val[len(blue_val) - 1]
binary_message_list.append(last_red_bit)
cur += 1
if cur >= 81+passLength+8 and self.is_done(binary_message_list, cur):
del binary_message_list[0:81+passLength+8]
binary_message = self.grouper(8, ''.join(binary_message_list), 0)
for byte in binary_message:
character = ''.join(str(a) for a in byte)
if character == '00000000':
return message
else:
message += str(unichr(int(character, 2)))
binary_message_list.append(last_green_bit)
cur += 1
if cur >= 81+passLength+8 and self.is_done(binary_message_list, cur):
del binary_message_list[0:81+passLength+8]
binary_message = self.grouper(8, ''.join(binary_message_list), 0)
for byte in binary_message:
character = ''.join(str(a) for a in byte)
if character == '00000000':
return message
else:
message += str(unichr(int(character, 2)))
binary_message_list.append(last_blue_bit)
cur += 1
if cur >= 81+passLength+8 and self.is_done(binary_message_list, cur):
del binary_message_list[0:81+passLength+8]
binary_message = self.grouper(8, ''.join(binary_message_list), 0)
for byte in binary_message:
character = ''.join(str(a) for a in byte)
if character == '00000000':
return message
else:
message += str(unichr(int(character, 2)))
else:
return None
def post(self):
if self.request.get('urls'):
print self.request.get('urls')
urls = json.loads(self.request.get('urls'))
resp = dict()
i = 0
print "about to print passwords"
passwords = []
if self.request.get('passwords'):
print "printing passwords"
passwords = json.loads(self.request.get('passwords'))
for password in passwords:
print password
for url in urls:
splitUrl = url.split(".")
#make sure url ends in .png or .jpg
if "png" in splitUrl[-1]:
img = url_to_img(url)
if (img != None):
maybe_msg = self.decode(img, passwords)
if not maybe_msg:
resp[url] = maybe_msg
i += 1
print json.dumps(resp)
self.write(json.dumps(resp))
elif self.request.get('url'):
img = url_to_img(self.request.get('url'))
msg = self.decode(img, [self.request.get('key')])
print msg
self.write(json.dumps(msg))
elif self.request.get('pic'):
img = Image.open(BytesIO(self.request.get('pic')))
msg = self.decode(img, [self.request.get('key')])
self.write(msg)
application = webapp2.WSGIApplication([
('/', Home), ('/encode', Encode), ('/decode', Decode)
], debug=True)