Skip to content

Instantly share code, notes, and snippets.

@i3inary
Created March 17, 2023 21:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save i3inary/61f512da60bc006ff37d40652e10932b to your computer and use it in GitHub Desktop.
Save i3inary/61f512da60bc006ff37d40652e10932b to your computer and use it in GitHub Desktop.
embed image hash in image using stegno
import hashlib
from stegano import lsb
from stegano.lsbset import generators
def generate_hash(image_path):
with open(image_path, 'rb') as f:
img_data = f.read()
hash_object = hashlib.sha256(img_data)
hash_hex = hash_object.hexdigest()
return hash_hex
def embed_hash_in_image(image_path, hash_hex):
img = lsb.hide(image_path, hash_hex, generators.eratosthenes())
img.save('output_image.png')
def extract_hash_from_image(image_path):
extracted_hash = lsb.reveal(image_path, generators.eratosthenes())
return extracted_hash
def main():
image_path = 'input_image.jpg'
hash_hex = generate_hash(image_path)
print(f"Image hash: {hash_hex}")
embed_hash_in_image(image_path, hash_hex)
print(f"Image hash embedded in output_image.png")
extracted_hash = extract_hash_from_image('output_image.png')
print(f"Extracted hash from output_image.png: {extracted_hash}")
if __name__ == "__main__":
main()
@i3inary
Copy link
Author

i3inary commented Mar 17, 2023

For a completely invisible and more robust method of embedding a hash in an image, you can use steganography techniques. A popular Python library for steganography is stegano. To use it, first install the library:
pip install stegano

This script uses the stegano library to hide the hash in the least significant bits of the image's pixels, making it completely invisible to the human eye. It also provides a function to extract the hash from the image for verification purposes.

Keep in mind that while this method is more robust and invisible than the previous example, it is still not immune to image compression, resizing, or other modifications. If the image is changed, the embedded hash might be lost or corrupted, making it impossible to verify the original image. To minimize the risk of losing the hash due to image modifications, save the image in a lossless format like PNG.

For even more robust and secure methods, consider using digital watermarking techniques or exploring more advanced steganography methods.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment