def _decode(dataset, model_type, epochs, experiment_id, attack_name, experiment_time): pictures_path = default_path.format(experiment_id, attack_name, experiment_time) model, x_train, x_test, y_train, y_test = load_model(dataset=dataset, model_type=model_type, epochs=epochs) score = [] lsb_score = [] stat_score = [] ensemble_score = [] for file in os.listdir(pictures_path): if file.endswith(".{}".format(extension)): path = "{}/{}".format(pictures_path, file) img = img_to_array(load_img(path)) / palette img_class = np.argmax(model.predict(np.array([img]), verbose=0)) index = file.index("_truth") - 1 real_class = int(file[index:index + 1]) score.append(real_class == img_class) steg_msg = lsb.reveal(path) lsb_score.append(0 if lsb_score == None else 1) bitrate_R = attacks.spa(path, 0) bitrate_G = attacks.spa(path, 1) bitrate_B = attacks.spa(path, 2) threshold = 0.05 if bitrate_R < threshold and bitrate_G < threshold and bitrate_B < threshold: stat_score.append(0) else: stat_score.append(1) #logger.info("img {} decoded as {} stegano {}".format(file,img_class,steg_msg)) logger.info("decoding score {}".format(np.mean(np.array(score)))) real_path = "{}/ref".format(pictures_path) for file in os.listdir(pictures_path): if file.endswith(".{}".format(extension)): path = "{}/{}".format(pictures_path, file) e4s_score = _detect_e4s_srm( file_path=path, model_file="e4s_srm_bossbase_lsbm0.10_gs.model") ensemble_score.append(e4s_score) steg_msg = lsb.reveal(path) lsb_score.append(1 if lsb_score == None else 0) spa_score = _detect_spa(path) stat_score.append(spa_score) lsb_score_mean = np.mean(np.array(lsb_score)) stat_score_mean = np.mean(np.array(stat_score)) logger.info("lsb detection score {}, stats detection score {}".format( lsb_score_mean, stat_score_mean))
def perform(original_image_path, changed_image_path): original_image = Image.open(original_image_path) changed_image = Image.open(changed_image_path) w, h = original_image.size tile_size = 64 hash_length = 64 threshold = hash_length * 0.15 column, row = count_tiles_size(w, h, tile_size) # Slice image to 64x64 blocks original_tiles = image_slicer.slice(original_image_path, number_tiles=column * row, col=column, row=row, save=False) changed_tiles = image_slicer.slice(changed_image_path, number_tiles=column * row, col=column, row=row, save=False) # Итеративно проходим по каждому блоку изображения for original_tile, changed_tile in zip(original_tiles, changed_tiles): # Получаем хеш блока original_hash = imagehash.phash_simple(original_tile.image) changed_hash = imagehash.phash_simple(changed_tile.image) # Прям хеш методом наименее значащего бита original_tile.image = lsb.hide(original_tile.image, str(original_hash)) changed_tile.image = lsb.hide(changed_tile.image, str(changed_hash)) # Забираем хеш из изображения decoded_original_hash = lsb.reveal(original_tile.image.copy()) decoded_changed_hash = lsb.reveal(changed_tile.image.copy()) # Вычисляем расстояние Хемминга и сравниваем его с пороговой границей if hamming_distance(decoded_original_hash, decoded_changed_hash) > threshold: # Закрашиваем измененные области # The current version supports all possible conversions between “L”, “RGB” and “CMYK.” The matrix argument only supports “L” and “RGB”. rgb2xyz = (0.412453, 0.357580, 0.180423, 0, 0.212671, 0.215160, 0.072169, 0, 0.019334, 0.919193, 0.950227, 0) changed_tile.image = changed_tile.image.convert("RGB", rgb2xyz) result_image = image_slicer.join(changed_tiles, w, h) file_name = original_image_path.split(".")[-2] result_image_path = original_image_path.replace(file_name, file_name + "_result") result_image.save(result_image_path) original_image.show() changed_image.show() result_image.show()
def recuperar_de_imgs(self, fromdir, usar_metadatos): #parts = os.listdir(fromdir) #todir = parts[0].split('_part_')[0] + '_parts' todir = fromdir + '_parts' # Creamos un directorio (si no existe). if not os.path.exists(todir): os.mkdir(todir) else: for fname in os.listdir(todir): # Si el directorio existe y tiene contenido, dejamos el directorio y eliminamos el contenido del directorio. os.remove(os.path.join(todir, fname)) parts = os.listdir(fromdir) parts.sort() for index, part in enumerate(parts): # De la primera imagen extraemos: la extensión y el contenido. if 'part_001' in part: if usar_metadatos == True: # Si la opción seleccionada en la interfaz es la de Metadatos. extension = recuperar_informacion(self, fromdir + '/' + part, 'extension') content = recuperar_informacion(self, fromdir + '/' + part, 'contenido') else: # Si la opción seleccionada en la interfaz es la de LSB. if get_tipo(self, fromdir + '/' + part) == '.jpg' or get_tipo(self, fromdir + '/' +part) == '.jpeg': # Si la imagen es JPG, muestra error. self.listWidget.addItem("Error!! El método LSB sólo permite imágenes PNG.") return else: extension = lsb.reveal(fromdir + '/' + part).split("#####")[1] content = lsb.reveal(fromdir + '/' + part).split("#####")[2] # De las demás imágenes extraemos solo el contenido. else: if usar_metadatos == True: content = recuperar_informacion(self, fromdir + '/' + part, 'contenido') else: if get_tipo(self, fromdir + '/' + part) == '.jpg' or get_tipo(self, fromdir + '/' + part) == '.jpeg': self.listWidget.addItem("Error!! El método LSB sólo permite imágenes PNG.") return else: content = lsb.reveal(fromdir + '/' + part).split("#####")[0] nombre_fich = part[:part.rfind('.')] + '.enc' filename = os.path.join(todir, nombre_fich) escribirFichero(self, filename, content) # Una vez que hemos extraído todo el contenido de las imágenes, lo escribimos en el fichero de destino. return (todir, extension)
def obtener_firma(self, img_name, metadatos): if metadatos: firma = Metadatos.obtener_firma_img(self, img_name) # Extrae la firma de la primera imagen empleando Metadatos. else: firma = lsb.reveal(img_name).split("#####")[0] # Extrae la firma de la primera imagen empleando LSB. return firma
def AcceptInvite(ContactName, InputFile, OutputFile): contents = lsb.reveal(InputFile) try: # check that the data rertived from the file is valid print(contents) PublicKeyID, PublicKey, Max, IDpassword = json.loads( contents) #take variables out of JSON PublicKeyID, PublicKey, Max = int(PublicKeyID), int(PublicKey), int( Max) # Convert variables to integers to check they are integers if PublicKey > Max: #ensure PublicKey is smaller than Max raise ValueError if PublicKeyID > 9223372036854775807: #ensure PublicKeyID is small enough for database raise ValueError if Max > (2**2048): #ensure max small enough to be real raise ValueError if PublicKey < 10000: #small values for PublicKey damage security raise ValueError except (ValueError, json.decoder.JSONDecodeError): print("Invalid invite file" ) #if not JSON: JSONDecodeError; if wrong JSON: ValueError return () ContactID = AddContact(PublicKeyID, PublicKey, Max, IDpassword, ContactName) for RerturnedData in CreateKeypair(ContactID): # Create Keypair to send if type(RerturnedData) is str: yield (RerturnedData) else: MyPublicKeyID, MyPublicKey, MyMax = RerturnedData MessageContents = json.dumps( ["Invite Accepted", MyPublicKeyID, MyPublicKey, MyMax]) print("AI-1") SM = SendMessage(OutputFile, MessageContents, IDpassword, PublicKey, Max, ContactID, PublicKeyID) for ReturnedData in SM: yield (ReturnedData)
def dec(filename): decrypt_message = lsb.reveal(filename) decryptmess = decrypt_message dec = Toplevel(root) dec.geometry("400x200") dec.config(bg="maroon") dec.title("decode") path = StringVar() yam = StringVar() yam = decryptmess lab1 = Label(dec, text="welcome!!!", bg='maroon', fg='white').place(relx=0.4, rely=0.05) lab2 = Label(dec, text='VIEW THE SECRETE MESSAGE!!!!!', bg="maroon", fg="white").place(relx=0.3, rely=0.2) lab3 = Label(dec, text=yam, bg='maroon', fg='white', bd=5).place(relx=0.2, rely=0.4) lab4 = Label(dec, text="visit 2020 NEPAL", bg="maroon", fg="white").place(relx=0.3, rely=0.6)
def SteganographyDecrypt(): print( " _______.___________. _______ _______ ___ .__ __. ______ _______ .______ ___ .______ __ __ ____ ____ " ) print( " / | || ____| / _____| / \\ | \\ | | / __ \\ / _____|| _ \\ / \\ | _ \\ | | | | \\ \\ / / " ) print( " | (----`---| |----`| |__ | | __ / ^ \\ | \\| | | | | | | | __ | |_) | / ^ \\ | |_) | | |__| | \\ \\/ / " ) print( " \\ \\ | | | __| | | |_ | / /_\\ \\ | . ` | | | | | | | |_ | | / / /_\\ \\ | ___/ | __ | \\_ _/ " ) print( ".----) | | | | |____ | |__| | / _____ \\ | |\\ | | `--' | | |__| | | |\\ \\----./ _____ \\ | | | | | | | | " ) print( "|_______/ |__| |_______| \\______| /__/ \\__\\ |__| \\__| \\______/ \\______| | _| `._____/__/ \\__\\ | _| |__| |__| |__| " ) print( " \n " ) print("Move the image to\'De\'") file = input("Enter Filename with extension:") rev = lsb.reveal("./Stego/De/" + file) ldscr() print("The hidden message is:-\n" + rev) jh = input()
def FetchKeyData(keyfile): # Fetch key data file from the file. fs = FileSystemStorage() fs.save(keyfile.name, keyfile) path = os.path.join(MEDIA_ROOT, keyfile.name) data = lsb.reveal(path) os.remove(path) return data
def retrieve(self, input_image_file): """ Retrieve the encrypted data from the image. :param input_image_file: Input image file path :return: """ cypher_data = lsb.reveal(input_image_file) if not cypher_data: return None cypher_data = base64.b64decode(cypher_data) # Retrieve the dynamic initialization vector saved iv = cypher_data[:AES.block_size] # Retrieved the cypher data cypher_data = cypher_data[AES.block_size:] try: decryption_suite = AES.new(self.key, AES.MODE_CBC, iv) decrypted_data = unpad(decryption_suite.decrypt(cypher_data), self.block_size) try: return decrypted_data.decode('utf-8') except UnicodeDecodeError: # Binary data - returns as it is return decrypted_data except ValueError: return None
def listen_to_peers(c): global private_key while True: # data received from client rec_msg = c.recv(1024) if(not rec_msg): break size = int(rec_msg.decode('ISO-8859-1')) c.sendall("GOT SIZE".encode('ISO-8859-1')) data = bytearray() while(len(data) < size): data += c.recv(40960000) if not data: print('Bye') break # check for digital signature image = Image.open(io.BytesIO(data)) img_msg = lsb.reveal(image) decrypted = private_key.decrypt(img_msg.encode('ISO-8859-1')) received_msg = decrypted.decode('ISO-8859-1') received_msg = received_msg.split('#') sender_name = received_msg[0].strip() msg_body = str(':'.join(received_msg[1:])) # print(msg_body, received_msg) # print(received_msg, sender_name) print(sender_name, 'says :',msg_body)
def decodeText(): secret_image = request.form['secret_image'] password = request.form['pwd'] image = base64.decodebytes(secret_image.encode()) count = 0 for i in summary: if i.key.startswith('secret_decoder_images/'): count = count + 1 secret_file_received = 'secret_decoder_images/img' + str(count) + '.png' client.put_object(Bucket='pdf-save-repo', Body=image, Key=secret_file_received) object_acl = resource.ObjectAcl('pdf-save-repo', secret_file_received) object_acl = object_acl.put(ACL='public-read') response = requests.get( "https://pdf-save-repo.s3.ap-south-1.amazonaws.com/" + secret_file_received) img = Image.open(io.BytesIO(response.content)) message = lsb.reveal(img) json_data = json.loads(message) obj = resource.Object("pdf-save-repo", secret_file_received) obj.delete() if json_data['pwd'] != password: return {'message': "Wrong password for the image"} else: return {'encoded_data': json_data['encoded_data']}
def get_signature(input_image: str) -> Optional[str]: """Obtains the signature of the image at the supplied path. :param input_image: the input image path :return: the signature if the image is signed, else None """ return lsb.reveal(input_image)
def reveal_image(): form = SHA512Form() if request.method == "POST": if request.files: if "filesize" in request.cookies: if not allowed_image_filesize(request.cookies["filesize"]): flash("Filesize exceeded maximum limit", 'danger') return redirect(request.url) image = request.files["image"] if image.filename == "": flash("No filename", 'danger') return redirect(request.url) if allowed_image(image.filename): filename = secure_filename(image.filename) image.save( os.path.join(app.config["IMAGE_UPLOADS"], 'secret\\' + filename)) clear_message = lsb.reveal(app.config["IMAGE_UPLOADS"] + 'secret\\' + filename) if clear_message != None: return render_template("reveal.html", title="Revel Secret Text", message=clear_message) else: flash('No Secret Messages in this file', 'danger') return redirect(request.url) else: flash("That file extension is not allowed", 'danger') return redirect(request.url) return render_template("reveal.html", title="Stegano")
def extract(img, password, offset): # extract data from an image y = lsb.reveal(img, encoding="UTF-8", shift=offset) if y is None: return "Unable to retrieve any embedded data" x = unlukefuscate(y) s1 = x[:44] # salt (first 44) s2 = x[44:68] # Initialization Vector (next 24) s3 = x[68:] # Cipher Text / encrypted message (rest of message) salt = b64decode(s1) # base64 decoded salt iv = b64decode(s2) # base64 decoded init vector ct = b64decode(s3) # base64 decoded cipher text key = PBKDF2(password, salt, dkLen=32) # Your key that you can encrypt with try: cipher = AES.new(key, AES.MODE_CBC, iv) pt = unpad(cipher.decrypt(ct), AES.block_size) dec_dat = pt.decode() sequence = dec_dat.split(":")[-1] p_seq = sequence.split(",") trimmed = dec_dat[:-(len(sequence) + 1)] ret_data = str(p_seq[0]) + " of " + str(p_seq[1]) + "\n" + trimmed return ret_data except ValueError: return "Decryption failed"
def decode(): img = input("Enter the name of secret file(with extension): ") cipher_text = lsb.reveal(img) keyword = input("Enter keyword: ") key = generateKey(cipher_text, keyword) message = originalText(cipher_text, key) return str(message)
def start_operation(self): key_box = self.textbox_key.toPlainText() image = self.path_textBox.text() path_save = self.output_textBox.text() if (key_box != '') and (image != ''): try: clear_message = lsb.reveal(image) clear_message_byte = str.encode( clear_message) #Convert String to Byte decrypted_text = PrpCrypt(key_box).decrypt(clear_message_byte) op = True if op == True: file_secure_output = self.output_textBox.text() open_file = open(file_secure_output, "w") open_file.writelines(decrypted_text) open_file.close() time.sleep(1) QMessageBox.about( self, 'Success', 'Process completed!\nYour message is stored in:\n{}'. format(file_secure_output)) #Clear All The Input Boxes. self.clear_all() except: QMessageBox.about(self, 'Error', 'Wrong Key!') else: QMessageBox.about(self, 'Error', 'Wrong Key or Input image not found!')
def _decode(dataset, model_type, epochs, experiment_id, attack_name, experiment_time, extension=None): if not extension: extension = default_extension pictures_path = default_path.format(experiment_id, attack_name, experiment_time) model, x_train, x_test, y_train, y_test = load_model(dataset=dataset, model_type=model_type, epochs=epochs) score = [] for file in os.listdir(pictures_path): if file.endswith(".{}".format(extension)): path = "{}/{}".format(pictures_path, file) image = load_img(path) if len(image.size) < 3: image = image.convert("RGB") if image.width != 32: image = image.resize((32, 32), Image.BILINEAR) img = img_to_array(image) / palette img_class = np.argmax(model.predict(np.array([img]), verbose=0)) index = file.index("_truth") - 1 real_class = int(file[index:index + 1]) steg_msg = lsb.reveal(path) logger.info("img {} decoded as {} stegano {}".format( file, img_class, steg_msg)) score.append(real_class == img_class) logger.info("decoding score {}".format(np.mean(np.array(score))))
def POST(self): input = web.input(file={}) filename = input['file'].filename fileds = input['file'].value if filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg') and filename.count('/') == -1: os.chdir('static/files') with open(filename, 'wb') as fout: shutil.copyfileobj(input['file'].file, fout, 100000) os.chdir('../../') # do NOT touch above code if filename.endswith('.png'): return ''' <!DOCTYPE html> <html lang="en"> <head> <title>Attempted to Decode</title> <meta charset="utf-8"> </head> <body> '''+lsb.reveal("static/files/"+filename)+"<p>Message decoded should be above.</p></body></html>" if filename.endswith('.jpg') or filename.endswith('.jpeg'): return ''' <!DOCTYPE html> <html lang="en"> <head> <title>Attempted to Decode</title> <meta charset="utf-8"> </head> <body> '''+exifHeader.reveal("static/files/"+filename)+"<p>Message decoded should be above.</p></body></html>"
def stego(): print("hi") global numBytes, numExfilFiles, numFiles, dT, eD,flg,textAdd,gpath numF=1 flg=1 downloadImage() while numF<=numFiles: print("hey") textF=open((gpath+"\\"+str(numF)+"combinedExfil.txt"), "r") numBytestextEx=0 textAdd="" last=checkLine(gpath+"\\"+str(numF)+"combinedExfil.txt") for line in textF: if numBytestextEx+sys.getsizeof(line)<20000: numBytestextEx+=sys.getsizeof(line) textAdd+=line if line==last: secret = lsb.hide(gpath+"\\diamond_PNG6695.png" , textAdd) secret.save(gpath+"\\X"+str(numExfilFiles)+"combinedExfil.png") elif numBytestextEx+sys.getsizeof(line)>=20000: textAdd=line secret = lsb.hide(gpath+"\\diamond_PNG6695.png", textAdd) secret.save(gpath+"\\X"+str(numExfilFiles)+"combinedExfil.png") print(lsb.reveal(gpath+"\\X"+str(numExfilFiles)+"combinedExfil.png")) numExfilFiles+=1 if line==last: secret = lsb.hide(gpath+"\\diamond_PNG6695.png", textAdd) secret.save(gpath+"\\X"+str(numExfilFiles)+"combinedExfil.png") numF+=1
def show_msg(img): clear = lsb.reveal("imgs/new_"+img) if clear: with open("archives/messages.csv", "a") as file: file.write(f"{img},{clear}\n") return clear return "Nenhuma Mensagem encontrada"
def generate_images(dir_name, word): print("generating images for " + current_dir + " " + dir_name + "...") clear_message = "" current_index = 0 loop_index = 0 print("generating word: " + word) for count in range(len(word)): base_dir = current_dir + dir_name + "/" if not os.path.exists(base_dir): os.makedirs(base_dir) current = word[count] file = base_dir + str( loop_index) + "-" + file_keys[current_index] + '.png' height = random.randint(50, 955) width = random.randint(250, 955) img = Image.new('RGB', (width, height)) draw = ImageDraw.Draw(img) fonts_path = "~/Library/Fonts" font = ImageFont.truetype(os.path.join(fonts_path, 'slkscr.ttf'), 9) draw.text((0, random.randint(10, height - 20)), randomString(random.randint(2, 255)), (random.randint(50, 255), random.randint( 50, 255), random.randint(50, 255)), font=font) img.save(file) secret = lsb.hide(file, current) secret.save(file) clear_message += lsb.reveal(file) current_index = current_index + 1 if current_index > 6: current_index = 0 loop_index = loop_index + 1
def retrieve(input_image_file, key): block_size = 32 cipher_data = lsb.reveal(input_image_file) if not cipher_data: return None cipher_data = base64.b64decode(cipher_data) # Retrieve the dynamic initialization vector saved iv = cipher_data[:AES.block_size] # Retrieved the cipher data cipher_data = cipher_data[AES.block_size:] try: decryption_suite = AES.new(key, AES.MODE_CBC, iv) decrypted_data = unpad(decryption_suite.decrypt(cipher_data), block_size) try: return decrypted_data.decode('utf-8') except UnicodeDecodeError: # Binary data - returns as it is return decrypted_data except ValueError: return None
def test_hide_and_reveal_UTF32LE(self): messages_to_hide = 'I love 🍕 and 🍫!' secret = lsb.hide("./tests/sample-files/Lenna.png", messages_to_hide, 'UTF-32LE') secret.save("./image.png") clear_message = lsb.reveal("./image.png", 'UTF-32LE') self.assertEqual(messages_to_hide, clear_message)
def basla(k1, k2): baslangic = datetime.now() aesCozme(str(k1) + '.png') aesCozme(str(k2) + '.png') birlestirme(k1, k2) clear_message = lsb.reveal('ÇözülmüşResimRGB.png') print('resime gizlenmiş olan veri : ', clear_message) print('RGB çözme bitti --- çözme Süresi : ', (datetime.now() - baslangic))
def decode_pic(): hiddenMessage = lsb.reveal("output.png") if hiddenMessage == None: l = Label(decodeTab, text="No hidden message found") l.pack() else: l = Label(decodeTab, text=hiddenMessage, font=myFont) l.pack()
def test_hide_and_reveal(self): messages_to_hide = ['a', 'foo', 'Hello World!', ':Python:'] for message in messages_to_hide: secret = lsb.hide("./tests/sample-files/Lenna.png", message) secret.save("./image.png") clear_message = lsb.reveal("./image.png") self.assertEqual(message, clear_message)
def main(): print HTML_HEADER print HEAD data = cgi.FieldStorage() fileds = data['file'] if fileds.filename.endswith('.jpg') or fileds.filename.endswith('.png') or fileds.filename.endswith('.jpeg') or fileds.filename.endswith('.tiff') and fileds.filename.count('/') == -1: os.chdir('files') with open(fileds.filename, 'wb') as fout: shutil.copyfileobj(fileds.file, fout, 100000) os.chdir('../') # do NOT touch above code if fileds.filename.endswith('.png'): print lsb.reveal("files/"+fileds.filename) if fileds.filename.endswith('.jpg') or fileds.filename.endswith('.jpeg'): print exifHeader.reveal("files/"+fileds.filename) print "<p>Attempted to decode.</p>" print END
def test_hide_and_reveal_UTF32LE(self): messages_to_hide = 'I love 🍕 and 🍫!' secret = lsb.hide("./tests/sample-files/Lenna.png", messages_to_hide, encoding='UTF-32LE') secret.save("./image.png") clear_message = lsb.reveal("./image.png", encoding='UTF-32LE') self.assertEqual(messages_to_hide, clear_message)
def main_function(original_image_filename, deformed_image_filename): original_image = Image.open(original_image_filename) deformed_image = Image.open(deformed_image_filename) # расчет количества блоков n = 64 width, height = original_image.size col = math.ceil(width / n) row = math.ceil(height / n) # пороговая величина threshold = n * 0.15 # разбитие изображений на блоки orig_img_tiles = image_slicer.slice(original_image_filename, col=col, row=row, save=False) deform_img_tiles = image_slicer.slice(deformed_image_filename, col=col, row=row, save=False) for orig_block, deform_block in zip(orig_img_tiles, deform_img_tiles): # getting block hash orig_hash = myimagehash.phash_simple(orig_block.image) deform_hash = myimagehash.phash_simple(deform_block.image) # hide a message(hash) in images with the LSB orig_block.image = lsb.hide(orig_block.image, str(orig_hash)) deform_block.image = lsb.hide(deform_block.image, str(deform_hash)) # Find a message(hash) in images with the LSB decoded_orig_hash = lsb.reveal(orig_block.image.copy()) decoded_deform_hash = lsb.reveal(deform_block.image.copy()) if hamming_distance(decoded_orig_hash, decoded_deform_hash) > threshold: deform_block.image = deform_block.image.convert("L") result_image = image_slicer.join(deform_img_tiles, width, height) result_image.save("./images/result.png") original_image.show() deformed_image.show() result_image.show()
def test_with_text_file(self): text_file_to_hide = "./tests/sample-files/lorem_ipsum.txt" with open(text_file_to_hide) as f: message = f.read() secret = lsb.hide("./tests/sample-files/Lenna.png", message) secret.save("./image.png") clear_message = lsb.reveal("./image.png") self.assertEqual(message, clear_message)
def stego_out(picture): hidden_ct = lsb.reveal(picture) #Parse here dt = eval(hidden_ct) message = dt['msg'] nonce = dt['nc'] mac = dt['mc'] return message, nonce, mac
def decodeImage(self): try: message = lsb.reveal(self.path.text) self.labelDecode.text = message message = "Msg: Successfully decoded message." self.decodeMessage.text = message except: message = "Msg: Something went wrong - This image may not have an encoded message." self.decodeMessage.text = message
def deimg(): if secimg.get() == "png": messag = lsb.reveal(fileopen) if secimg.get() == "jpeg": messag = aaa.reveal(fileopen) Label2 = Label(text=messag) Label2.place(relx=0.7, rely=0.7, height=21, width=204)
def test_with_transparent_png(self): messages_to_hide = ['🍕', 'a', 'foo', 'Hello World!', ':Python:'] for message in messages_to_hide: secret = lsb.hide("./tests/sample-files/transparent.png", message, 'UTF-32LE') secret.save("./image.png") clear_message = lsb.reveal("./image.png", 'UTF-32LE') self.assertEqual(message, clear_message)
def test_with_transparent_png(self): messages_to_hide = ['🍕', 'a', 'foo', 'Hello World!', ':Python:'] for message in messages_to_hide: secret = lsb.hide("./tests/sample-files/transparent.png", message, encoding='UTF-32LE') secret.save("./image.png") clear_message = lsb.reveal("./image.png", encoding='UTF-32LE') self.assertEqual(message, clear_message)
def test_with_bytes(self): messages_to_hide = ["a", "foo", "Hello World!", ":Python:"] for message in messages_to_hide: message = "Hello World" outputBytes = io.BytesIO() bytes_image = lsb.hide(open("./tests/sample-files/20160505T130442.jpg", 'rb'), message) bytes_image.save(outputBytes, "PNG") outputBytes.seek(0) clear_message = lsb.reveal(outputBytes) self.assertEqual(message, clear_message)
def test_with_binary_file(self): binary_file_to_hide = "./tests/sample-files/free-software-song.ogg" with open(binary_file_to_hide, "rb") as bin_file: encoded_string = base64.b64encode(bin_file.read()) message = encoded_string.decode() secret = lsb.hide("./tests/sample-files/Montenach.png", message) secret.save("./image.png") clear_message = lsb.reveal("./image.png") clear_message += '===' clear_message = base64.b64decode(clear_message) with open('file1', 'wb') as f: f.write(clear_message) with open('file1', 'rb') as bin_file: encoded_string = base64.b64encode(bin_file.read()) message1 = encoded_string.decode() self.assertEqual(message, message1) try: os.unlink('./file1') except: pass
from stegano import lsb secret = lsb.hide("./test.png", "This is a test This is a testThis is a testThis is a testThis is a testThis is a test" "This is a testThis is a testThis is a testThis is a testThis is a testThis is a test" "This is a testThis is a testThis is a testThis is a testThis is a testThis is a test") secret.save("./Lenna-secret.png") print(lsb.reveal("./Lenna-secret.png"))
def png_decode(mfile_name): return lsb.reveal(mfile_name)