Search code examples
shaexiftool

Calculating hashes of raw image data and writing it to the image file


I am trying to write hashes to the metadata part of my image files. In the Exiftool Forum I saw this

exiftool FILE -rawimagedigest=`exiftool FILE -all= -o - | md5`

However, I would rather not run it manually for each file, and I do prefer SHA.

I tried this

find . -name "*" -exec sh -c '
    md5hash=$(exiftool "$1" -all= -m -o - | md5)
    sha256hash=$(exiftool "$1" -all= -m -o - | shasum -a 256)
    exiftool -overwrite_original "$1" -FileImageMd5=$md5hash;
    exiftool -overwrite_original "$1" -FileImageSha256=$sha256hash
    ' _ {} \;

Using the example file I created a config making it possibly to write to FileImageMd5 and FileImageSha256. However, the script only works without the line

exiftool -overwrite_original "$1" -FileImageSha256=$sha256hash

If I substitute the variable in the end with $md5hash it runs as expected.

The config file is named .ExifTool_config and placed in $HOME. It consist of the following

%Image::ExifTool::UserDefined = (
    'Image::ExifTool::XMP::Main' => {
        rlp => {
            SubDirectory => {
                TagTable => 'Image::ExifTool::UserDefined::rlp',
            },
        },
    },
);

%Image::ExifTool::UserDefined::rlp = (
    GROUPS => { 0 => 'XMP', 1 => 'XMP-rlp', 2 => 'Image' },
    NAMESPACE => { 'rlp' => 'http://ns.ladekjaer.org/rlp/1.0/' },
    WRITABLE => 'string',
    FileUniqueId => { Writable => 'lang-alt' },
    FileImageSha256 => { Writable => 'lang-alt' },
    FileImageMd5 => { Writable => 'lang-alt' },
);

1;  #end

Solution

  • Apparently the script failed due to

    shasum -a 256
    

    ending its output with

      -
    

    Since a SHA256 written in hex is always 64 characters, can this be solved by adding

     | head -c 64
    

    Thus making the script

    find . -name "*" -exec sh -c '
        md5hash=$(exiftool "$1" -q -all= -m -o - | md5)
        sha256hash=$(exiftool "$1" -q -all= -m -o - | shasum -a 256 | head -c 64)
        exiftool -overwrite_original -q "$1" -FileImageMd5=$md5hash;
        exiftool -overwrite_original -q "$1" -FileImageSha256=$sha256hash
        ' _ {} \;