Esempio n. 1
0
def extract(cover, key):
    cap = cv2.VideoCapture(cover)
    index = int(ifvm.decodeIndexHash(
        binascii.unhexlify(key)))  # <- Index at which our data is hidden

    frameCount = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    frames = ifvm.getAllFrames(cap)

    img = Image.fromarray(frames[index])
    indexData = stepic.decode(img).decode()
    print indexData
    indexData = indexData.split(';')

    media_txt_location = 'outfile.' + indexData[0]
    media_location = 'extractedMedia.' + indexData[1]

    f = open(media_txt_location, 'w')

    dataLocs = indexData[2].split('.')

    for loc in dataLocs:
        if loc == '': break
        img = Image.fromarray(frames[int(loc)])
        block = stepic.decode(img).decode()
        f.write(block)
    f.close()

    with open(media_txt_location, "rb") as res:
        str = base64.b64decode(res.read())
    fh = open(media_location, "wb")
    fh.write(str)
    fh.close()
    os.remove(media_txt_location)
Esempio n. 2
0
def decode():
    img = input("Enter image name(with extension):- ")
    image = Image.open(img)

    data1 = stepic.decode(image)

    return data1
Esempio n. 3
0
def dec():
 image=raw_input("enter url of image :")
 im=Image.open(image)
 data=stepic.decode(im)
 print data
 
  print('Thaank you')
Esempio n. 4
0
    def controlStegoImage(self):
        self.key="kaobkaob"
        im=Image.open("frames/f5.png")
        message=stepic.decode(im)
        ###########################################¶tcnumbe decode
        im=Image.open("frames/f6.png")
        tcNumStego=stepic.decode(im)

        if(message==self.key and self.tcNumber==tcNumStego):
            print("Gizlenen:"+message+" Key:"+self.key)
            print("Gizlenen Tc:"+tcNumStego+" Sonuc Tc:"+self.tcNumber)
            return True
        else:
            print("Gizlenen:"+message+" Key:"+self.key)
            print("Gizlenen Tc:"+tcNumStego+" Sonuc Tc:"+self.tcNumber)
            return False
    def __init__(self, key, image_path):
        self.image_path = image_path
        self.image = Image.open(image_path)
        self.key = key
        self.cipher = AESCipher(self.key)

        def get_md5_hash(k):
            m = hashlib.md5()
            m.update(k)
            md5_hash = m.hexdigest()
            return md5_hash

        try:
            already_encoded = stepic.decode(self.image)
            # print("already_encoded: {}".format(already_encoded))
            self.md5_hash = already_encoded[:32]
            # print("self.md5_hash: {}".format(self.md5_hash))
            self.passwords_dict = json.loads(already_encoded[32:])
        except ValueError:
            key_again = raw_input(
                "Initializing the image, please re-enter your master password: "******"\n!!!! The passwords do not match !!!!\n")
                exit(0)
            self.md5_hash = get_md5_hash(self.key)
            self.passwords_dict = {}

        if self.md5_hash != get_md5_hash(self.key):
            print("\n!!!! Wrong password !!!!\n")
            exit(0)
def decodeFromPhoto(URL):
    # Takes the Twitter photo URL as input and decode and return the text within the image as string
    url = URL
    content = urllib.request.urlopen(url).read()
    image = Image.open(io.BytesIO(content))
    data = stepic.decode(image)
    return data
Esempio n. 7
0
def decoder():
    p = input(
        "Enter the name of the file you want to decode(without extension):")
    p += ".png"
    open2 = Image.open(p)
    decoded = stepic.decode(open2)
    print("Decoded text from the image:", decoded, "\n")
Esempio n. 8
0
    def fileChooserImageButtonCallback(self):
        """
        Callback for button that launch file chooser for Image.
        Display a file chooser for image file and
        if a file is selected, extract text hidden in it with stepic module
        insert text into text editor.
        Only called if steganography is available.
        """

        from PIL import Image  # pylint: disable=import-outside-toplevel
        import stepic  # pylint: disable=import-outside-toplevel

        if self.verbose:
            print("Enter in fileChooserImageButtonCallback()")

        try:
            fileName = tkinter.filedialog.askopenfilename(
                filetypes=(("All", "*"), ("PNG Image", "*.png")),
                title=_("Select a file containing text to insert"))
            if fileName != "":
                image = Image.open(fileName)
                text = stepic.decode(image)
                if self.verbose:
                    print("Text read from " + fileName + ": " + text)
                self.textEditor.insert(tkinter.INSERT, text)
                self.root.setMessageLabel(
                    _("Text read from ") + os.path.basename(fileName))

        except IOError:
            self.root.setMessageLabel(
                _('Unable to read text file !') + ': ' +
                +os.path.basename(fileName))

        if self.verbose:
            print("Exit from fileChooserImageButtonCallback()")
def decode():
    choicedecode = askopenfilename(initialdir="/",
                                   title="Choose an Image",
                                   filetypes=(("PNG Files", "*.png"),
                                              ("All Files", "*.*")))
    cd = choicedecode
    global screen7
    screen7 = Toplevel(screen)
    screen7.title("Decode")
    screen7.geometry("450x400+500+200")

    Label(screen7,
          text="Decode",
          bg="grey",
          width="300",
          height="2",
          font=("Calibri", 13)).pack()
    Label(screen7, text="").pack()

    Label(screen7, text="Message decoded is").pack()
    im2 = Image.open(cd)
    msgImg = stepic.decode(im2)

    Label(screen7, text="").pack()
    Label(screen7, text=msgImg, fg="blue", font=("Calibri", 13)).pack()

    Label(screen7, text="").pack()
    Button(screen7, text="Exit", width=10, height=1,
           command=screen7.destroy).pack()
    def process_data(self):
        enc_im = Image.open(self.prefix + self.src)
        self.size = enc_im.size[0] * enc_im.size[1] / 3
        enc_comp_data = stepic.decode(enc_im)
        self.data = list(crypt.decode(self.key, enc_comp_data))

        self.size = len(self.data)
Esempio n. 11
0
def decode_message(file):
    """
    returns the message in the file
    """
    i = Image.open(file)
    data = stepic.decode(i)
    msg = data.decode()
    return msg
Esempio n. 12
0
    def decode_img(self, file):

        im = Image.open(file)
        data = stepic.decode(im)
        if '-----BEGIN PUBLIC KEY-----' in data:
            return data
        else:
            return False
Esempio n. 13
0
def decode_message(file):
    """
    returns the message in the file
    """
    i = Image.open(file)
    data = stepic.decode(i)
    msg = data.decode()
    return msg
Esempio n. 14
0
def DeSteganify(imagePath):#,pathToSaveTo):
    im = Image.open(imagePath)
    s = stepic.decode(im)
    output = StringIO.StringIO(s)
    #image = Image.open(output)
    #image.save(pathToSaveTo+'decoded.png')
    decodedImage = output.getvalue()
    output.close()
    return decodedImage
Esempio n. 15
0
def decode(path):
    # Open image or file in which data exists
    image = Image.open(path)

    # Decode the image to extract the text
    decodeImage = stepic.decode(image)

    # Print the text
    print(f'Decoded String From Image: {decodeImage}')
Esempio n. 16
0
	def desteg(self):
		try:
			im = Image.open(self.file)
		except:
			print "Image file is damaged, watermark has probably been tampered with."
			quit()
		ciphertext = stepic.decode(im)
		message = self.verify(ciphertext)
		print message
Esempio n. 17
0
def decode(img, key):
    desincriptador = Decryptor()
    image = Image.open(img)
    info = stepic.decode(image)
    info = desincriptador.run(key, info)
    file = open("result.txt", "w")
    file.write(info.split("*//*")[0])
    file.close()
    return info.split("*//*")[1]
Esempio n. 18
0
    def Exreceive_(self):

        Receive_().receive_all()
        # if os.path.exists(temp_) == True:
        #     pass
        # else: temp_

        if R_path.endswith('.txt'):

            f = open(R_path, "r")
            my_dict = eval(f.read())
        else:
            im1 = Image.open(R_path)
            text = stepic.decode(im1)
            rec_ = open(temp_ + "crytp.txt", "wb")
            rec_.write(bytearray(map(ord, text)))
            rec_.close()
            f = open(temp_ + "crytp.txt", "r")
            my_dict = eval(f.read())

        R = my_dict['r']
        S = my_dict['s']
        Cr = my_dict['c']
        f.close()

        R = R.split()
        r_x = int(R[1], base=16)
        r_y = int(R[3], base=16)
        R = curves.Point(r_x, r_y, cv)
        # Bank
        K_2b = (S * p) + R
        Y_K2b = (bytes(str(K_2b.y), 'utf-8'))

        K_1b = (K_2b.x * d_b) * P_c
        X_K1b = (bytes(str(K_1b.x), 'utf-8'))
        key_b = X_K1b[:16]  # Symmetric Key
        iv_b = "9B7D2C34A366BF89"
        aesd_b = aes.AESModeOfOperationOFB(key_b, iv_b)
        decrypted_b = aesd_b.decrypt(Cr)
        plaintext = open(temp_ + "plain.zip", "wb")
        plaintext.write(decrypted_b)
        plaintext.close()
        plaintext = open(temp_ + "plain.zip", "rb")
        plaintext = plaintext.read()

        h_b = hashlib.sha256()
        h_b.update(plaintext)
        h_b.update(Y_K2b)
        h_b = int(h_b.hexdigest(), 16)
        R_b = h_b * P_c
        print(temp_)
        if R == R_b:
            shutil.move(temp_ + "plain.zip", output_file_path + ".zip")
            Factory.RWin().open()
        else:
            Factory.RDefeat().open()
        shutil.rmtree(temp_, ignore_errors=True)
Esempio n. 19
0
 def desteg(self):
     try:
         im = Image.open(self.file)
     except:
         print "Image file is damaged, watermark has probably been tampered with."
         quit()
     ciphertext = stepic.decode(im)
     message = self.verify(ciphertext)
     print message
Esempio n. 20
0
def unhide(pic):
    img = Image.open(pic)
    doc = pic[:-4] + '.docx'
    file = open(doc, 'wb')
    d = stepic.decode(img)
    #info = d.decode()
    file.write(d)
    file.close()
    return
def Stegana():

    img_stegana = askopenfilename(filetypes=[("Imagem PNG", "*.png")])
    im = Image.open(img_stegana)
    s = stepic.decode(im)
    data = s.decode()
    print 'Imagem Steganalise'
    print s
    return data
def decrypt_video(filename, t0=56):
	vid = VideoFileClip(filename)

	vid.save_frame("frame.png", t=t0+0.05)

	img = Image.open("frame.png").convert(mode='RGB')
	msg = stepic.decode(img)

	return msg 
def Stegana():

       	img_stegana = askopenfilename(filetypes=[("Imagem PNG","*.png")])
        im = Image.open(img_stegana)
        s = stepic.decode(im)
	data = s.decode()
	print'Imagem Steganalise' 
	print s
	return data	
Esempio n. 24
0
def get_exif(fn):

    hsh = hashlib.md5(fn).hexdigest()
    ret = {}
    file = open("output\exif.txt", "a")
    file.write("******************************************************\n")
    file.write("Filename: " + fn + "\n")
    file.write("Hash: " + hsh + "\n")
    file.write("------------------------------------------------------\n")
    i = Image.open(fn)
    # Detecting if there is steganography
    try:
        data = stepic.decode(i)
        print "Secret Text Message: " + data
        file.write("Secret Text Message: " + data + "\n")
    except:
        print "No Steganography Found"
        file.write("\nNo Steganography Found\n")
    try:
        info = i._getexif()

        # Parsing the image and extracting EXIF info

        for tag, value in info.items():

            decoded = TAGS.get(tag, tag)
            ret[decoded] = value
            file.write(str(decoded) + ": " + str(ret[decoded]) + "\n")

            temp = str(decoded).lower()

            # Extracting GPS Related Info

            if temp == 'gpsinfo':

                lat = [float(x) / float(y) for x, y in ret['GPSInfo'][2]]
                latref = ret['GPSInfo'][1]
                lon = [float(x) / float(y) for x, y in ret['GPSInfo'][4]]
                lonref = ret['GPSInfo'][3]
                lat = lat[0] + lat[1] / 60 + lat[2] / 3600
                lon = lon[0] + lon[1] / 60 + lon[2] / 3600
                if latref == 'S':
                    lat = -lat
                if lonref == 'W':
                    lon = -lon
    # Saving GPS Cordinates as KML file
                kml = simplekml.Kml()
                kml.newpoint(name=fn, coords=[(lon, lat)])
                kml.save("output\info.kml")
    except:
        file.write("NO EXIF Tags Found\n")
        print "NO EXIF Tags Found"

    file.write("------------------------------------------------------\n")
    file.close()
Esempio n. 25
0
def get_exif(fn):

    hsh =  hashlib.md5(fn).hexdigest()
    ret = {}
    file=open("output\exif.txt","a")
    file.write("******************************************************\n")
    file.write("Filename: " + fn + "\n")
    file.write("Hash: " + hsh + "\n")
    file.write("------------------------------------------------------\n")
    i = Image.open(fn)
    # Detecting if there is steganography
    try:
        data=stepic.decode(i)
        print "Secret Text Message: " + data
        file.write("Secret Text Message: " + data +"\n")
    except:
        print "No Steganography Found"
        file.write("\nNo Steganography Found\n")
    try:
        info = i._getexif()
        
    # Parsing the image and extracting EXIF info

        for tag, value in info.items():
        
            decoded = TAGS.get(tag, tag)
            ret[decoded] = value
            file.write(str(decoded)+": " + str(ret[decoded]) + "\n")
            
            temp=str(decoded).lower()
            
     # Extracting GPS Related Info

            if temp == 'gpsinfo':
                
                lat = [float(x)/float(y) for x, y in ret['GPSInfo'][2]]
                latref = ret['GPSInfo'][1]
                lon = [float(x)/float(y) for x, y in ret['GPSInfo'][4]]
                lonref = ret['GPSInfo'][3]
                lat = lat[0] + lat[1]/60 + lat[2]/3600
                lon = lon[0] + lon[1]/60 + lon[2]/3600
                if latref == 'S':
                    lat = -lat
                if lonref == 'W':
                    lon = -lon
     # Saving GPS Cordinates as KML file
                kml = simplekml.Kml()
                kml.newpoint(name=fn, coords=[(lon,lat)])
                kml.save("output\info.kml")
    except:
        file.write("NO EXIF Tags Found\n")
        print "NO EXIF Tags Found"

    file.write("------------------------------------------------------\n")
    file.close()
    def save_to_image(self):
        try:
            data = self.md5_hash + json.dumps(self.passwords_dict)
        except ValueError:
            print('password_dict not a valid json')
            exit(0)
        stepic.encode_inplace(self.image, data)
        assert stepic.decode(self.image) == data

        self.image.save(self.image_path)
        print("\nChanges saved in the image!\n")
Esempio n. 27
0
  def process_data(self):
    """ Decrypts and decompressed the data. May raise exception on Image.open """

    enc_im = Image.open(self.prefix+self.src)

    self.size = enc_im.size[0] * enc_im.size[1] / 3

    enc_comp_data = stepic.decode(enc_im)
    self.data = list(crypt.decode(self.key, enc_comp_data))

    self.size = len(self.data)
def stegano_decode(decode_key, ci):
    global decrypted
    #open the fake image and start the decrypting
    new_img = Image.open("{}_d.png".format(ci))
    data_decode = stepic.decode(new_img).rstrip('\n')
    #turning data out form ascci
    encrypted = binascii.a2b_base64(data_decode)
    # DECRYPTION
    # CRT mode decryption requires a new instance be created
    aes = pyaes.AESModeOfOperationCTR(decode_key)
    # decrypted data is always binary, need to decode to plaintext
    decrypted = aes.decrypt(encrypted).decode('utf-8')
Esempio n. 29
0
	def denusumustepic(self):
		try:
			import stepic
			from PIL import Image
			pictureLoc = raw_input("Type name of file:")
			openPic= Image.open(pictureLoc)
			stepicdecode = stepic.decode(openPic)
			text =  stepicdecode.decode()
			print "\n\033[31mEncrypted Data:\033[0m\n\n" + text
		except:
			print("Decoding Failed!!")
			raw_input("Press Enter to continue...")
			pass
Esempio n. 30
0
    def displayString(self, srcPath, isDisplay=True):
        try:
            im_src = Image.open(srcPath)
        except IOError:
            print 'can not open the %s' % srcPath
            exit(0)

        # im_src.show()

        str_dest = stepic.decode(im_src)
        data = str_dest.decode()
        if isDisplay:
            print data
        return data
Esempio n. 31
0
def decode_image(file_location="./images/encoded_image.png",
                 dest_location="./images/encoded_image.png"):
    """Decodes the hidden message in an image
    file_location: the location of the image file to decode. By default is the provided encoded image in the images folder
    """
    print(file_location)
    print(dest_location)
    encoded_image = Image.open(file_location)
    # red_channel = encoded_image.split()[0]

    # x_size = encoded_image.size[0]
    # y_size = encoded_image.size[1]

    decoded_msg = stepic.decode(encoded_image)
    return decoded_msg
def extract(frames, index):
	img = Image.fromarray(frames[index])
	indexData = stepic.decode(img).decode()
	indexData = indexData.split('.')
	metaData = indexData[0].split(';')
	secret_img_size = (int(metaData[0]), int(metaData[1]))
	noOfTiles = int(metaData[2])
	slice_size = (int(metaData[3]), int(metaData[4]))
	t = []
	for i in range(1,len(indexData)):
		temp = frames[int(i)]
		res = ioi.extract_image(Image.fromarray(temp)).resize((slice_size[0], slice_size[1]))
		t.append(res)
	extracted_image = reassemble_image(t, slice_size, secret_img_size[0]/slice_size[0], secret_img_size[1]/slice_size[1])
	return extracted_image
	def decryption(self,key):

		location = 'static/userImage1.png'
		key = int(key)
		image = Image.open(location)
		info = stepic.decode(image)

		original_text = self.decrypt(info,key)
		return original_text




# encryption('vikash23.jpeg','image','My name is Vikash',2)

# decryption('vikash23.jpeg',2)
Esempio n. 34
0
def extract(frames, index):
    img = Image.fromarray(frames[index])
    indexData = stepic.decode(img).decode()
    indexData = indexData.split('.')
    metaData = indexData[0].split(';')
    secret_img_size = (int(metaData[0]), int(metaData[1]))
    noOfTiles = int(metaData[2])
    slice_size = (int(metaData[3]), int(metaData[4]))
    t = []
    for i in indexData[1:len(indexData) - 1]:
        temp = frames[int(i)]
        # Image.fromarray(temp).save('recvd'+i+'.png')
        res = ioi.extract_image(Image.fromarray(temp)).resize(
            (slice_size[0], slice_size[1]))
        t.append(res)
    extracted_image = reassemble_image(t, slice_size,
                                       secret_img_size[0] / slice_size[0],
                                       secret_img_size[1] / slice_size[1])
    return extracted_image
Esempio n. 35
0
def extractMSG(path2Image, path2Video):
    # Extract from picture
    im = Image.open(path2Image)
    s = stepic.decode(im)

    tmpFile = open("tmp/PositionsList.txt", "w")
    tmpFile.write(s)
    tmpFile.close()

    #Read Video file frames
    absPath = path2Video
    vidcap = cv2.VideoCapture(absPath)

    count = 0
    success, image = vidcap.read()
    while success:
        success, image = vidcap.read()
        cv2.imwrite("tmp/frame%d.jpg" % count,
                    image)  # save frame as JPEG file
        count += 1

    # extract message from frames
    fNum = 0
    secMSG = ""
    for line in open("tmp/PositionsList.txt"):
        word = int(line.strip())
        #print "The word is now: ", word
        if word != -1:
            cPos = word - fNum
            imgName = "tmp/frame%d.jpg" % fNum
            try:
                imageFile = imgName
                data = open(imageFile, "rb").read()
            except IOError:
                print "Image file %s not found" % imageFile
                raise SystemExit

            msgOrd = data[cPos]
            secMSG = secMSG + msgOrd
        fNum = (fNum + 1) % count

    #shutil.rmtree('tmp')
    return secMSG
Esempio n. 36
0
def extractMSG(path2Image, path2Video):
    # Extract from picture
    im = Image.open(path2Image)
    s = stepic.decode(im)

    tmpFile = open("tmp/PositionsList.txt", "w")
    tmpFile.write(s)
    tmpFile.close()

    #Read Video file frames
    absPath = path2Video
    vidcap = cv2.VideoCapture(absPath)

    count = 0
    success, image = vidcap.read()
    while success:
        success, image = vidcap.read()
        cv2.imwrite("tmp/frame%d.jpg" % count, image)     # save frame as JPEG file
        count += 1

    # extract message from frames
    fNum = 0
    secMSG = ""
    for line in open("tmp/PositionsList.txt"):
        word = int(line.strip())
        #print "The word is now: ", word
        if word != -1:
            cPos = word - fNum
            imgName = "tmp/frame%d.jpg" % fNum
            try:
                imageFile = imgName
                data = open(imageFile, "rb").read()
            except IOError:
                print "Image file %s not found" % imageFile
                raise SystemExit

            msgOrd = data[cPos]
            secMSG = secMSG + msgOrd
        fNum = (fNum + 1) % count

    #shutil.rmtree('tmp')
    return secMSG
Esempio n. 37
0
def video(filename, username, t0):
	# Orignal Video
	original = VideoFileClip("static/videos/"+filename+".mp4")

	first_half = VideoFileClip("static/videos/"+filename+".mp4").subclip(0, t0)
	second_half = VideoFileClip("static/videos/"+filename+".mp4").subclip(t0+1, original.duration)

	original.save_frame("static/videos/frame.png", t=t0)

	img = Image.open("static/videos/frame.png").convert(mode='RGB')
	stepic.encode_inplace(img, username)
	msg = stepic.decode(img)
	print(msg)
	img.save("static/videos/frame.png")

	encoded_clip = ImageClip('static/videos/frame.png', duration=1)

	new_mov = CompositeVideoClip([first_half.set_start(0),
								  encoded_clip.set_start(t0),
								  second_half.set_start(t0+1)])

	# Write the result to a file (many options available !)
	new_mov.write_videofile("static/"+username+"_"+filename+".avi", codec='png')
Esempio n. 38
0
def Main():
	username=getpass.getuser()	
	f = open("/home/"+username+"/Documents/hashed.txt", "ro")
	data = f.read()
	f.close()

	parser = argparse.ArgumentParser()	
	parser.add_argument('-p','--password', help="enter password to get the secret message",required=True)
	parser.add_argument("-i", "--input", help="specify image to have secret message",required=True)
	
	args = parser.parse_args()
	
	if args.password:
	
		if hashlib.md5(args.password).hexdigest() == data:
			im1=Image.open(args.input)
			s=stepic.decode(im1)
			data=s.decode()
			print data

		else:
			print "Wrong Password"
	else:
		print parser.usage
Esempio n. 39
0
def decryptor():
   
   target = open('privkey.txt', 'r')
   key = target.read()
   target.close()
   
   #Create new SHA256 Hash
   h = SHA256.new()
   
   #RSA 2048 wrapped with PKCS1 as recommended by documentation 
   rsakey = RSA.importKey(key)
   rsakey = PKCS1_OAEP.new(rsakey , h)

   # target = open('testrun.txt' , 'rb') - For reading encrypted string from file
  
   #Open and decode Image to extract encrypted String 
   im = Image.open('encodedcat.png')
   encoded = stepic.decode(im)
   encoded = encoded.decode()
   # encoded = target.read()
   # target.close()
   
   #Undo B64 encoding on top of string
   encrypted = base64.b64decode(encoded)
   
   #Decompress string
   encrypted = zlib.decompress(encrypted)
   decrypted = ''
   #Chunks must be RSA modulus size
   chunks = splitter(encrypted, 256)   
   
   for chunk in chunks: 
      decrypted += rsakey.decrypt(chunk)   
   
   print decrypted
   print len(decrypted)
Esempio n. 40
0
def extractTextFromImage(fileNameInput, verbose):
    """
    Extract text hidden in an image.
    return :
            cr : 0 if ok, 1 if problem with fileNameInput,
                 2 if io problem
            resultText : text extracted from image

    parameters :
    - fileNameInput : path of the image file
    - resultText : text string extracted from image
    - verbose : True if message can be written on stdout file
    """

    cr = 0
    resultText = None

    if verbose:
        print("Enter in extractTextFromImage()")
        print("fileNameInput=", fileNameInput)

    try:
        if fileNameInput:
            image = Image.open(fileNameInput)
            resultText = stepic.decode(image)
        else:
            cr = 1
    except IOError as exc:
        print("exception =", exc)
        cr = 2

    if verbose:
        print("Exit from extractTextFromImage(), cr=", cr, "resultText=",
              resultText)

    return cr, resultText
Esempio n. 41
0
def decode(file):
    # This Function Will get data from picture
    img = Image.open(file)
    decoded = stepic.decode(img)
    return decoded
Esempio n. 42
0
def decode(img):
    image = Image.open(img, 'r')
    data = stepic.decode(image)

    with open("extracted_text.enc", 'wb') as fo:
        fo.write(bytes(base64.b64decode(bytes(data, encoding='utf-8'))))
#coding: utf-8
import stepic
from PIL import Image

img = Image.open('output/zip/00000186/share1.png')
res = stepic.decode(img)
print(res)
Esempio n. 44
0
import cv2
import stepic
import numpy as np
from PIL import Image

# code to test if steganography was successful
cap = cv2.VideoCapture("output.avi")
index = 42  # <- Index at which our data is hidden
frames = []
while True:
    ret, temp = cap.read()
    if not ret:
        break
    frames += [temp]

print "Length of frames read from output: ", len(frames)
img = Image.fromarray(frames[index])
hiddenmsg = stepic.decode(img).decode()
print hiddenmsg
Esempio n. 45
0
    ed = input("\nPress: 1) E for Encryption 2) D for Decryption ")
    if (ed == "E" or ed == "e"):
        ip = input("\nEnter the image filename: ")  #Image filename
        i = ip.find('.')
        ext = ip[-(len(ip) - i - 1):].upper()  #Getting extension
        text = input("\nEnter the text to encode: ")  #Getting text to encode
        im = Image.open(ip)
        tx = bytes(text, "utf-8")
        im1 = sp.encode(im, tx)  #Encoding text into image
        im1.save(ip, 'PNG')  #Saving image with the same name

        #im1 = Image.open(ip)
        #im1.show()
        #im.show()

    elif (ed == "D" or ed == "d"):  #Decoding
        ip = input("\nEnter the image filename: ")  #Iamge file
        im = Image.open(ip)
        text = sp.decode(im)  #Decoding text
        print("\nDecoded Text: ", text)

    else:
        print("\nPress valid key\n")
        ans = "Y"
        continue

    ans = input("\nWant to continue ? (Y/N): ")
    if ans == "Y":
        continue
    else:
        break
# need pycrypto package
from Crypto.Cipher import AES
# need PIL and stepic packages
import Image, stepic
import binascii

# key has to be 16, 24 or 32 bytes long
cryptObj = AES.new("This is my key42", AES.MODE_CBC, "16 character vec")
#  notice the spaces -- that's to pad it out to a multiple of 16 bytes
plaintext = "This is some text we need to encrypt because it's very secret   "
ciphertext = cryptObj.encrypt(plaintext)

#  we need to convert to ASCII to store it nicely
binval = binascii.b2a_base64(ciphertext)
i = Image.open("bullpuppies.jpg")

print("ASCII: ", binval)
stego = stepic.encode(i, binval)
stego.save("stegencrypt.bmp", "BMP")

newim = Image.open("stegencrypt.bmp")
data = stepic.decode(newim).rstrip('\n')

print("What we have out: ", data)
#  convert from ASCII back to binary
encrypted = binascii.a2b_base64(data)

newcryptObj = AES.new("This is my key42", AES.MODE_CBC, "16 character vec")
result = newcryptObj.decrypt(encrypted)

print(result)
Esempio n. 47
0
def decode():
    img_url = request.form['img_url']
    raw_img = Image.open(StringIO(r.get(img_url).content))
    return stepic.decode(raw_img)
Esempio n. 48
0
def decode_files(image_in, data_out):
    image = Image.open(image_in)
    if not hasattr(data_out, 'write'):
        data_out = open(data_out, 'wb')
    data_out.write(stepic.decode(image))
	# code to test if steganography was successful
	cap = cv2.VideoCapture('output.avi')

	input_hash = raw_input('Enter the key for your data: ')
	index = int(decodeIndexHash(binascii.unhexlify(input_hash))) # <- Index at which our data is hidden

	frames = []

	while True:
		ret, temp = cap.read()
		if not ret:
			break
		frames += [temp]

	img = Image.fromarray(frames[index])
	indexData = stepic.decode(img).decode()

	indexData = indexData.split(';')

	f = open('outfile.' + indexData[0], 'w')

	print 'File extension: ', indexData[0]

	dataLocs = indexData[2].split('.')

	for loc in dataLocs:
		if loc == '': break
		img = Image.fromarray(frames[int(loc)])
		block = stepic.decode(img).decode()
		f.write(block)
Esempio n. 50
0
def  decode(filepath):
	img = Image.open(filepath)
	if(img.mode!='L'):
		message = stepic.decode(img)
		return message
	return "  "
Esempio n. 51
0
from PIL import Image
import stepic

im=Image.open('I:/FYP/Lenna.png');
im1=stepic.encode(im,'Hello world')
im1.save('StegoLenna.jpg','JPEG')
im.show()
im1.show()

s=stepic.decode(im1)
data=s.decode()
print data
Esempio n. 52
0
 def extract_from_image(self, image_file, out):
     file = open(out, 'w')
     file.write(stepic.decode(image.open(image_file)))
Esempio n. 53
0
def  decode(filepath):
	img = Image.open(filepath)
	message = stepic.decode(img)
	return message
Esempio n. 54
0
    ed = input("\nPress: 1) E for Encryption 2) D for Decryption ")
    if (ed == "E" or ed == "e"):
        ip = input("\nEnter the image filename: ")
        i = ip.find('.')
        ext = ip[-(len(ip) - i - 1):].upper()
        text = input("\nEnter the text to encode: ")
        im = Image.open(ip)
        tx = bytes(text, "utf-8")
        im1 = sp.encode(im, tx)
        im1.save(ip, 'PNG')

        im1 = Image.open(ip)
        im1.show()
        im.show()

    elif (ed == "D" or ed == "d"):
        ip = input("\nEnter the image filename: ")
        im = Image.open(ip)
        text = sp.decode(im)
        print("\nDecoded Text: ", text)

    else:
        print("\nPress valid key\n")
        ans = "Y"
        continue

    ans = input("\nWant to continue ? (Y/N): ")
    if ans == "Y":
        continue
    else:
        break
# code to test if steganography was successful
cap = cv2.VideoCapture('output.avi')

inputNo = raw_input('Enter the frame no: ')
index = int(inputNo) # <- Index at which our data is hidden

frames = []

while True:
	ret, temp = cap.read()
	if not ret:
		break
	frames += [temp]

img = Image.fromarray(frames[index])
indexData = stepic.decode(img).decode()

indexData = indexData.split(';')
print 'File extension: ', indexData[0]

dataLocs = indexData[2].split(',')
data1Loc = int(dataLocs[0])
data2Loc = int(dataLocs[1])

img = Image.fromarray(frames[data1Loc])
data1 = stepic.decode(img).decode()
print 'Data 1: ' , data1

img = Image.fromarray(frames[data2Loc])
data2 = stepic.decode(img).decode()
print 'Data 2: ' , data2
def decrypt_image(path):
    im = Image.open(path)
    data = stepic.decode(im)
    passwd = base64.b64decode(data)
    return passwd
Esempio n. 57
0
def decode(pic):
    im1=Image.open(pic)
    s=stepic.decode(im1)
    data=s.decode()
    print data
    return data
Esempio n. 58
0
from PIL import Image
import stepic

# encryption
im = Image.open("Lenna.png")
im1 = stepic.encode(im, "hi friends")
im1.save("StegoLenna.jpg", "JPEG")
im.show()
im1.show()

# decryption
s = stepic.decode()
data = s.decode()
print data
Esempio n. 59
0
    modulename = opt.CRYPT + "def"  # [modulename]def.py
    globals()["crypt"] = __import__(modulename)

imagem = opt.IMAGE
file_in = opt.FILE
file_out = opt.FILEOUT

#main
image_obj = Image.open(imagem)
stepic._validate_image(image_obj)
if opt.encode:
    if not file_out:
        file_out = "%s.hd" % (imagem)
    data = open(file_in, "r").read()
    data = crypt.main_encrypt(data)
    stepic.encode_inplace(image_obj, data)
    image_obj.save(file_out, image_obj.format)

elif opt.decode:
    data = stepic.decode(image_obj)
    data = crypt.main_decrypt(data)
    if not file_out:
        print "------------BEGIN-----------\n", data, "------------END-------------"
    else:
        fileo = open(opt.FILEOUT, "w")
        fileo.write(data)
        fileo.close()
else:
    parser.print_usage()
image_obj.close()
Esempio n. 60
0
def get_and_decode_image(img_link):
    resp = urllib2.urlopen(img_link)
    #print resp.content
    img = Image.open(StringIO(resp.read()))
    return decompress(stepic.decode(img))