07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

192 Chapter 6 ■ Using Cryptography with Images

Storing a Binary File Inside an Image

For our next example, we will take a media file and hide it in an image. The file I

am using for this example was retrieved from file-examples.com. The file is 747

KB in size. If you would like to use the same file, you can find it here: https://

file-examples.com/index.php/sample-audio-files/sample-mp3-download/.

Our goal here is to use the CryptoSteganography module to take a secret message

and hide it in an image. The first thing that you need to do is reference the

CryptoSteganography library. The larger the media file, the longer it will take

to encrypt and decrypt. In this next example, I will also be using a much larger

image file because the media file I’ve selected is too large for the secret image I

used in the previous example. As you work through this example, you may be

attempting to store more data than the image will support. In those cases, you

will see an exception that states: The message you want to hide is too long. Here we

will start breaking down the code you need:

>>> from cryptosteganography import CryptoSteganography

The next step is to open the file and assign the binary data to a variable; here

we use 'message':

>>> mediafile = “file_example_MP3_700KB.mp3”

>>> message = None

>>> with open(mediafile, "rb") as f:

>>> message = f.read()

Next, create a key and pass it into the CryptoSteganography object. The key

is critical in order to extract the messages you conceal; the key you select can

be a passphrase or any selected password:

>>> key = "1111222233334444!"

>>> crypto_steganography = CryptoSteganography(key)

You can now store the encrypted file inside the image. Assign the original

file and modified file variables:

>>> origfile = "dogs.png"

>>> modfile = "steg_audio_dogs.png "

>>> crypto_steganography.hide(origfile, modfile, message)

Now that we have our media hidden, it is time to extract it. You can use the

previous crypto_steganography object, but the code here will instantiate a new

object. This will allow you to change or modify the key if you like. Here, we

will use the same key. In addition, specify the steganography image and the

name of the file you wish to store the MP3 as:

>>> key = "1111222233334444!"

>>> crypto_steganography = CryptoSteganography(key)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!