简体   繁体   English

如何在Python中更改图片的MD5哈希?

[英]How can I change an image's MD5 hash in Python?

I have an image file, and would like to use Python to edit the image without visibly modifying the picture, while still changing the file's MD5 hash. 我有一个图像文件,并且想使用Python编辑图像而无需明显修改图片,同时仍然更改文件的MD5哈希值。

What's the best way to do this? 最好的方法是什么?

Use @Martijn Pieters' solution: just change one bit in the headers or somewhere safe. 使用@Martijn Pieters的解决方案:只需更改标题中的一位或某个安全的位置。

Or more easy, if you may change the file size: Append a '\\0' (well, any character will do) to the file. 如果您可以更改文件大小,或更简单:将'\\0' (好吧,任何字符都可以)添加到文件中。 It will still be a valid JPEG file, and there will be no visible change. 它将仍然是有效的JPEG文件,并且没有可见的更改。

echo -n ' ' >> my_image.jpeg

One crude solution is 一种粗略的解决方案是

  • to convert (one color plane of) the image into the Fourier space (using dft/fft), 将图像(的一个彩色平面)转换为傅立叶空间(使用dft / fft),
  • changing some pixel values in the low frequencies (mostly stored in the bottom-right of the 2-d array), 更改低频中的某些像素值(主要存储在2维数组的右下角),
  • and convert the image back into the image space (using ifft). 并将图像转换回图像空间(使用ifft)。

All pixels will be different with little to no optical change. 所有像素都将有所不同,几乎没有光学变化。

import hashlib
hashlib.md5(open('image.png','rb').read()).hexdigest() # rb = readbyte ,so it will work for text as well as media (image,video) files

output >>> '724c6d87452c3a137ef1499c2d4b6576' # md5 hash value 输出>>>'724c6d87452c3a137ef1499c2d4b6576'#md5哈希值

file = open('image.png', 'rb').read()
with open('new_image.png', 'wb') as new_file:
  new_file.write(file+'\0')  #here we are adding a null to change the file content

hashlib.md5(open('new_image.png','rb').read()).hexdigest()

output >>> 'a345838e8af07b65344e19989c7c5d85' # new md5 hash value of the same media file 输出>>>'a345838e8af07b65344e19989c7c5d85'#同一媒体文件的新md5哈希值

I ended up using pyexiv2 to modify the image's metadata, like this: 我最终使用pyexiv2修改了图像的元数据,如下所示:

>>> md5sum('photo.jpg')
'89dd603a0ce14750799a5144a56fbc12'
>>> image = pyexiv2.ImageMetadata('photo.jpg')
>>> image.read()
>>> image['Exif.Image.ImageDescription'] = '%030x' % random.randrange(256**15)
>>> image.write()
>>> md5sum('photo.jpg')
'426cc91835e7f4f5e92c5a48850adc05'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM