예제 #1
0
 def test_manual_convert_rgb(self, input):
     message_to_hide = "I love 🍕 and 🍫!"
     lsb.hide(
         "./tests/sample-files/Lenna-grayscale.png",
         message_to_hide,
         encoding="UTF-32LE",
     )
예제 #2
0
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 encode():
        if secimg.get() == "jpeg":
            inimage = fileopen
            response = messagebox.askyesno("popup", "do you want to encode")
            if response == 1:
                aaa.hide(inimage, entrysave.get() + '.jpg', entrysecmes.get())
                messagebox.showinfo(
                    "popup", "successfully encode" + entrysave.get() + ".jpeg")

            else:
                messagebox.showwarning("popup", "unsuccessful")

        if secimg.get() == "png":
            inimage = fileopen
            response = messagebox.askyesno("popup", "do you want to encode")
            if response == 1:
                lsb.hide(inimage,
                         message=entrysecmes.get()).save(entrysave.get() +
                                                         '.png')
                messagebox.showinfo(
                    "popup",
                    "successfully encode to " + entrysave.get() + ".png")

            else:
                messagebox.showwarning("popup", "unsuccessful")
예제 #4
0
def encryption():
    if request.method == 'POST':
        result = request.form
        oldpath = request.files['oldpath']
        msg = request.form['msg']
        newpath = request.form['newpath']
        newpath = newpath + '.png'
        img_upload_dir = os.path.join(os.path.dirname(app.instance_path), '')
        lsb.hide(oldpath,
                 message=msg).save(os.path.join(img_upload_dir, newpath))
        if 'username' in session:
            username = session['username']
        sql = "INSERT INTO images(username, imagepath) VALUES(%s, %s)"
        data = (username, newpath)
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute(sql, data)
        conn.commit()
        cursor.execute("SELECT imagepath from images where username='******'")
        images_data = cursor.fetchall()
        images_list = []
        for row in images_data:
            image = str(row)
            image1 = image.replace("\\\\", "\\")
            image2 = image1.replace("\\r\\n", "")
            image3 = image2.replace(
                "C:\\Users\\janvi\\PycharmProjects\\Steganography\\venv\\Lib\\static\\uploads\\",
                "")
            image4 = image3[2:-3]
            images_list.append(image4)
        flash('Encrypted Successfully')
        return render_template("home_page.html", images_list=images_list)
예제 #5
0
 def test_auto_convert_rgb(self):
     message_to_hide = "I love 🍕 and 🍫!"
     lsb.hide(
         "./tests/sample-files/Lenna-grayscale.png",
         message_to_hide,
         encoding="UTF-32LE",
         auto_convert_rgb=True,
     )
예제 #6
0
 def test_refuse_convert_rgb(self, input):
     message_to_hide = "I love 🍕 and 🍫!"
     with self.assertRaises(Exception):
         lsb.hide(
             "./tests/sample-files/Lenna-grayscale.png",
             message_to_hide,
             encoding="UTF-32LE",
         )
예제 #7
0
def ocultar_en_imgs(self, fromdir, firma, extension, usar_metadatos):
    todir = fromdir[:fromdir.rfind('_')] + '_images/'   # De la ruta del directorio, nos quedamos con el nombre y le añadimos el sufijo '_images'

    # 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)     # Generamos una lista con los fragmentos que hay en el directorio.
    parts.sort()

    firma = procesarContenido(self, firma)

    for index, part in enumerate(parts):
        content = procesarFichero(self, fromdir + part)

        part_name = part[:part.rfind('.')]

        if usar_metadatos:
            img = Image.open(self.lineEdit_3.text())
            img.save(todir + part_name + '.' + img.format.lower())
            newImage = Image.open(todir + part_name + '.' + img.format.lower())

            if 'part_001' in newImage.filename:
                Metadatos.ocultar_informacion(self, newImage.filename, 'firma', firma)
                Metadatos.ocultar_informacion(self, newImage.filename, 'extension', extension)

            Metadatos.ocultar_informacion(self, newImage.filename, 'contenido', content)
        
        else:
            img = Image.open(self.lineEdit_3.text())

            if img.format == 'JPEG':
                img.save(todir + part_name + '.png')
                newImage = Image.open(todir + part_name + '.png')
            else:
                img.save(todir + part_name + '.' + img.format.lower())
                newImage = Image.open(todir + part_name + '.' + img.format.lower())

            if 'part_001' in newImage.filename:
                secret = lsb.hide(newImage.filename, firma + "#####" + extension + "#####" + content)
                secret.save(newImage.filename)
                
            else:
                secret = lsb.hide(newImage.filename, content)
                secret.save(newImage.filename)

        os.remove(fromdir + part)
    
    os.rmdir(fromdir)

    return todir
예제 #8
0
    def encode_txt_img(self):  # Fn to encode our txt to image

        sel_image = self.ids.encode_image_path.text  # getting the file location
        user_text = self.ids.user_text.text  # text to be encoded

        slash_count = sel_image.count("\\")  # getting the file location

        img_name = sel_image.split("\\", slash_count)[slash_count].split(
            ".", 1)[0]  # selecting only the file name with no extension
        img_type = sel_image.split("\\", slash_count)[slash_count].split(
            ".", 1)[1]  # selecting only the file extension

        # Checking if the required folder exists
        if os.path.exists(r"C:\Secret TXT"):
            pass
        else:  # if not creating it
            os.makedirs(r"C:\Secret TXT")

        try:
            # checking the type of file first

            # for png types
            if img_type == "png":
                secret_img = f"C:\\Secret TXT\\{img_name} [Encoded].{img_type}"  # setting the location to save the encoded images

                # lsb is used for png
                # hide is used to encode the image
                # it's parameters are selected image, the text to be encoded
                lsb.hide(sel_image, message=user_text).save(
                    secret_img
                )  # save is used to save the image to the required location

                self.ids.encode_result.text = "Encoding was successful"

            # for jpg/jpeg types
            elif img_type == "jpg" or img_type == "jpeg":
                secret_img = f"C:\\Secret TXT\\{img_name} [Encoded].{img_type}"

                # exifHeader is used for jpg/jpeg
                # hide is used to encode the image
                # it's parameters are selected image, location to be saved, and the text to be encoded
                exifHeader.hide(sel_image,
                                secret_img,
                                secret_message=user_text)

                self.ids.encode_result.text = "Encoding was successful"

            # if type is not supported
            else:
                self.ids.encode_result.text = "Type not supported"
        except:

            # fail-safe
            self.ids.encode_result.text = "Encoding has failed"
예제 #9
0
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()
예제 #10
0
def add_steg(path, bpp):
    '''
    Add steg to each image in directory

    param:
    path - str path to data folder containing .pngs
    bpp - float desired bits per pixel

    return:
    None
    '''
    filecounter = len([path for path in walk_dir(path)])

    gen = DocumentGenerator()

    if (args.generators):
        lsb_generators = [
            getattr(generators, entry) for entry in args.generators
        ]

    count = 0

    for filepath in tqdm(walk_dir(path), total=filecounter, unit='files'):
        try:
            im = Image.open(filepath)
            im_size = im.size[0] * im.size[1]
            # average sentence length is 60 bytes -> 480 bits
            message = '\n'.join(
                [gen.sentence() for i in range(int(im_size * bpp / 480))])
            # remove non-ascii characters as they mess up steganography
            message = message.encode('ascii', 'ignore').decode()

            if (args.generators):
                # + 1 to add normal lsb
                gen_index = int(count % (len(lsb_generators) + 1))

                if (gen_index == len(lsb_generators)):
                    secret = lsb.hide(filepath, message)
                    secret.save(filepath.replace('.png', '.steg.png'))
                else:
                    lsb_gen = lsb_generators[gen_index]
                    secret = lsbset.hide(filepath, message, lsb_gen())
                    secret.save(
                        filepath.replace('.png',
                                         f".{args.generators[gen_index]}.png"))
            else:
                secret = lsb.hide(filepath, message)
                secret.save(filepath.replace('.png', '.steg.png'))
            count += 1
        except Exception as e:
            print(e)
            print(filepath)
예제 #11
0
def set_signature(input_image: str, output_image: str, signature: str) -> None:
    """Signs the image at the input path with the supplied signature and saves it at the output image path.

    The output image must be of png format because lossless compression is required to sign an image.

    :param input_image: the input image path
    :param output_image: the output image path
    :param signature: the signature
    :return: None
    :raise ImageFormatException: if the output image format is not png
    """
    if not output_image or output_image.split('.')[-1] != 'png':
        raise ImageFormatException()

    lsb.hide(input_image, signature).save(output_image, 'png')
예제 #12
0
    def start_operation(self):
        key_box = self.textbox_key.toPlainText()
        message = self.textbox_message.toPlainText()
        image = self.path_textBox.text()
        path_save = self.output_textBox.text()

        #Start Encryption
        if (key_box != '') and (message != '') and (path_save != '') and (image != ''):
            try:
                cipher_text_byte = PrpCrypt(key_box).encrypt(message)  #Encrypted Message
                cipher_text_str = cipher_text_byte.decode()     #Covert Byte to String
                    
                cipher_image = lsb.hide(image, cipher_text_str)
                cipher_image.save(path_save)
                    
                time.sleep(1)
                QMessageBox.about(self, 'Completed', 'Done!')

                #Clear All The Input Boxes.
                self.clear_all()

            except:
                QMessageBox.about(self, 'Error',  'Operation Failed, try again.')
        
        else:
            QMessageBox.about(self, 'Error', 'Please enter all the fields to continue..')
예제 #13
0
def watermark_text(input_image_path, output_image_path, text):
    photo = Image.open(input_image_path)
    origin_x, origin_y, width, height = photo.getbbox()
    xPos = width - 400
    yPos = height - 50

    # make the image editable
    drawing = ImageDraw.Draw(photo)
    shadow_color = (0, 0, 0)
    text_color = (255, 255, 255)
    font = ImageFont.truetype("/Library/Fonts/Futura.ttc", 40)

    # draw thin border
    drawing.text((xPos - 2, yPos), text, font=font, fill=shadow_color)
    drawing.text((xPos + 2, yPos), text, font=font, fill=shadow_color)
    drawing.text((xPos, yPos - 2), text, font=font, fill=shadow_color)
    drawing.text((xPos, yPos + 2), text, font=font, fill=shadow_color)

    # draw true text
    drawing.text((xPos, yPos), text, fill=text_color, font=font)

    # preview and save image
    photo.show()
    photo.save(output_image_path)
    secret = lsb.hide(output_image_path,
                      '© ' + time.strftime("%Y") + ' Owen Pierce')
    secret.save(output_image_path)
예제 #14
0
def upload_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 file selected", 'danger')
                    return redirect(request.url)

                if allowed_image(image.filename):
                    filename = secure_filename(image.filename)
                    image.save(
                        os.path.join(app.config["IMAGE_UPLOADS"], filename))
                    secret = lsb.hide(app.config["IMAGE_UPLOADS"] + filename,
                                      form.plaintext.data.encode("utf-8"))
                    secret.save(
                        os.path.join(app.config["IMAGE_UPLOADS"],
                                     'secret-' + filename))
                    return send_file(app.config["IMAGE_UPLOADS"] + 'secret-' +
                                     filename,
                                     as_attachment=True)
                    flash('Hiding message successful', 'success')
                    return redirect(request.url)

                else:
                    flash("That file extension is not allowed", 'danger')
                    return redirect(request.url)

    return render_template("upload_new.html", title="Stegano", form=form)
예제 #15
0
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'):
        sec = lsb.hide('files/' + fileds.filename, data['message'].value)
        sec.save('files/' + fileds.filename)
    if fileds.filename.endswith('.jpg') or fileds.filename.endswith('.jpeg'):
        secret = exifHeader.hide('files/' + fileds.filename,
                                 'files/' + fileds.filename,
                                 secret_message=data['message'].value)
    print "Successfully generated."
    print '<a href="http://jonathanwong.koding.io/bstego/files/' + fileds.filename + '">Link here</a>'
    print END
예제 #16
0
def encrypt():
    if request.method == "GET":
        return render_template("encrypt.html")

    else:
        if not (request.form.get("text") or request.form.get("key1")):
            return apology("Missing Message/Key")

        elif request.form.get("key1").isdigit() == False:
            return apology("Enter a secret  key between 1 and 26.")

        elif (int(request.form.get("key1")) < 1
              or int(request.form.get("key1")) > MAX_KEY_SIZE):
            return apology("Enter a secret  key between 1 and 26.")

        else:
            f = request.files['pic']
            f.save("./static/Input.png")
            plaintext1 = request.form.get("text")
            key1 = int(request.form.get("key1"))
            ciphertext1 = ciphertexter(plaintext1, key1)
            secret = lsb.hide(
                f, ciphertext1)  # or secret = lsb.hide("./Input.png", text)
            secret.save("./static/Stego.png")
            return render_template("encrypted.html")
예제 #17
0
def encode_string(input_string, root="./tmp/"):
    split_string_list = split_string(input_string)
    for i in range(0, len(split_string_list)):
        f_name = "{}{}.png".format(root, i)
        secret_enc = lsb.hide(f_name, split_string_list[i])
        secret_enc.save(f_name)
        print("[INFO] frame {} holds {}".format(f_name, split_string_list[i]))
예제 #18
0
파일: main.py 프로젝트: sanattaori/SpyChat
def send_msg():
    ch = select_a_friend()
    text = input("What do you want to say? ")

    secret = lsb.hide("./input.png", text)
    output = input('Name of output file: \n (Press enter for default name)')
    if len(output) == 0:
        secret.save("./secret.png")
        print(
            bcolors.BOLD +
            "Your secret message image is ready! with file name 'secret.png' ")
    else:
        try:
            secret.save(output)
            print(bcolors.BOLD +
                  "Your secret message image is ready! with file name " +
                  output)
        except Exception:
            print(bcolors.WARNING + 'Please Enter valid extension')

    # Append chat to friend
    new_chat = ChatMessage(text, True)
    friends[ch].chats.append(new_chat)

    start_chat(spy_name, spy_age, spy_rating)
예제 #19
0
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
예제 #20
0
def embed(img, saveas, password, inp, offset, pic_num, tps):
    # encrypt & embed a data string into an image
    salt = get_random_bytes(32)  # generate something salty..
    key = PBKDF2(password, salt,
                 dkLen=32)  # encryption key generated from the password

    cipher = AES.new(key, AES.MODE_CBC)  # let's get encrypting...
    data = inp.encode()  # encode input to a bytes object
    pd = str(":" + str(pic_num) + "," +
             str(tps)).encode()  # encode sequence position
    ct_bytes = cipher.encrypt(pad(
        data + pd, AES.block_size))  # cipher text bytes + sequence
    iv = b64encode(cipher.iv).decode('utf-8')  # base64 encoded IV
    ct = b64encode(ct_bytes).decode('utf-8')  # base64 encoded Cipher Text
    salt_s = b64encode(salt).decode('utf-8')  # base64 encoded Salt

    enc_string = lukefuscate(salt_s + iv +
                             ct)  # obfuscation/substitution cipher

    steg_it = lsb.hide(img,
                       enc_string,
                       encoding="UTF-8",
                       shift=offset,
                       auto_convert_rgb=True)

    steg_it.save(saveas)  # save the image
    return "SAVED AS:  " + str(saveas)
    def hide(self, input_filename, output_filename, data):
        """
        Encrypt and save the data inside the image.
        :param input_filename: Input image file path
        :param output_filename: Output image file path
        :param data: Information to be encrypted and saved
        :return:
        """
        # Generate a random initialization vector
        iv = Random.new().read(AES.block_size)
        encryption_suite = AES.new(self.key, AES.MODE_CBC, iv)

        # If it is string convert to byte string before use it
        if isinstance(data, str):
            data = data.encode()

        # Encrypt the random initialization vector concatenated
        # with the padded data
        cypher_data = encryption_suite.encrypt(iv + pad(data, self.block_size))

        # Convert the cypher byte string to a base64 string to avoid
        # decode padding error
        cypher_data = base64.b64encode(cypher_data).decode()

        # Hide the encrypted message in the image with the LSB
        # (Least Significant Bit) technique.
        secret = lsb.hide(input_filename, cypher_data)
        # Save the image file
        secret.save(output_filename)
예제 #22
0
def add_image_steganography(image_file):
    #print(image_file)

    try:
        key = ''
        if "tree" in image_file:
            key = 'tree'
        elif "mountain" in image_file:
            key = 'mountain'
        elif "sea" in image_file:
            key = 'sea'
        elif "hotel" in image_file:
            key = 'hotel'

        #print(lookup[key])
        if ".jpg" in image_file.lower():
            #print(image_file)
            img = Image.open(image_file)
            img1 = img.convert("RGB")
            secret = lsb.hide(img1, lookup[key])
            secret.save("./valid_data/" + key + "/" +
                        os.path.basename(image_file))

    except:
        print(" Error in processing the file ")

    return True
예제 #23
0
def final_encryption(path, message):
    p = path
    m = message
    secret_message = lsb.hide(p, m)
    secret_message.save("C:/Users/User/Desktop/tour/secret_message.png")
    messagebox.showinfo(
        "Saved",
        "Encryped file stored in C:/Users/User/Desktop/encrypted_images")
예제 #24
0
    def encodePng(self, path, string):
#        if ".png" not in path:
#            path = path + ".png"
#        if "./" not in path:
#            path = "./" + path

        newImage = lsb.hide(path, string)
        newImage.save("./Steganography/steganized/"+os.path.basename(path))
예제 #25
0
    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)
예제 #26
0
def keygenerate(data, id):  #Regenerate the key file on user request
    ipath = 'https://source.unsplash.com/random/200x200'
    fname = id + '.png'
    path = os.path.join(MEDIA_ROOT + '/keys/', fname)
    r = requests.get(ipath, allow_redirects=True)
    open(path, 'wb').write(r.content)
    secret = lsb.hide(path, data)  # Stegano library hiding the data
    secret.save(path)
예제 #27
0
    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)
예제 #28
0
def encode_string(input_string, root):
    # for file in os.listdir(root):
    #     if file.endswith(".jpg"):
    split_string_list = split_string(input_string)
    for i in range(1, len(split_string_list)):
        secret_enc = lsb.hide("{}{}.png".format(root, i), split_string_list[i])
        secret_enc.save("{}{}.png".format(root, i))
        print("[INFO] frame {} holds {}".format(i, split_string_list[i]))
예제 #29
0
    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)
예제 #30
0
파일: cmdline.py 프로젝트: reale/kalipto
def send(msg):
    secret = lsb.hide("example.png", msg)
    secret.save("example-steg.png")
    with open("example-steg.png", "rb") as imagefile:
        imagedata = imagefile.read()
    id_img = twitter_upload.media.upload(
        media=imagedata, media_category="tweet_image")["media_id_string"]
    results = twitter.statuses.update(media_ids=id_img)
예제 #31
0
def encode_message(image, message):
    image_with_secret = lsb.hide(image, message)
    filename = f"{uuid.uuid4().hex}.png"  # giving a random name to the file
    image_path = os.path.join(
        app.root_path, "static/images",
        filename)  # to work with stegano, the image will be saved as a png
    image_with_secret.save(image_path)  # save the processed image
    return filename
예제 #32
0
    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)
예제 #33
0
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()
예제 #34
0
    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)
예제 #35
0
    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)
예제 #36
0
    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)
예제 #37
0
파일: stego.py 프로젝트: JonW27/bStego
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'):
            sec = lsb.hide('files/'+fileds.filename, data['message'].value)
            sec.save('files/'+fileds.filename)
        if fileds.filename.endswith('.jpg') or fileds.filename.endswith('.jpeg'):
            secret = exifHeader.hide('files/'+fileds.filename, 'files/'+fileds.filename, secret_message=data['message'].value)
        print "Successfully generated."
        print '<a href="http://jonathanwong.koding.io/bstego/files/'+fileds.filename+'">Link here</a>'
	print END
예제 #38
0
    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
예제 #39
0
파일: app.py 프로젝트: JonW27/bstego2.0
	def POST(self):
		input = web.input(file={})
		filename = input['file'].filename
		fileds = input['file'].value
		message = input.message
		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'):
				sec = lsb.hide('static/files/' + filename, message)
				sec.save('static/files/' + filename)
			if filename.endswith('.jpg') or filename.endswith('.jpeg'):
				secret = exifHeader.hide('static/files/' + filename, 'static/files/' + filename, secret_message = message)
			return '''
			<!DOCTYPE html>
			<html lang="en">
				<head>
					<title>
						Your image
					</title>
					<style>
						img {
							width: 500px;
							height: 500px;
						}
					</style>	
				</head>
				<body>
					<h1>
						Right click on the image and click <i>Save As</i> to save it.
					</h1>
					<img src="static/files/'''+filename+'''" />
				</body>
			</html>	
			'''		
		else:
			return
예제 #40
0
 def test_refuse_convert_rgb(self, input):
     message_to_hide = 'I love 🍕 and 🍫!'
     with self.assertRaises(Exception):
         secret = lsb.hide("./tests/sample-files/Lenna-grayscale.png",
                                 message_to_hide, 'UTF-32LE')
예제 #41
0
 def test_auto_convert_rgb(self):
     message_to_hide = 'I love 🍕 and 🍫!'
     secret = lsb.hide("./tests/sample-files/Lenna-grayscale.png",
                         message_to_hide, 'UTF-32LE', True)
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"))
예제 #43
0
 def test_hide_empty_message(self):
     """
     Test hiding the empty string.
     """
     with self.assertRaises(AssertionError):
         secret = lsb.hide("./tests/sample-files/Lenna.png", "")
예제 #44
0
def png_encode(file_name, message, mfile_name):
	secret = lsb.hide(file_name, message)
	secret.save(mfile_name)
예제 #45
0
 def test_with_too_long_message(self):
     with open("./tests/sample-files/lorem_ipsum.txt") as f:
         message = f.read()
     message += message*2
     with self.assertRaises(Exception):
         lsb.hide("./tests/sample-files/Lenna.png", message)