file_hash

Table of Contents

Prototype: file_hash(file, algorithm)

Return type: string

Description: Return the hash of file using the hash algorithm.

This function is much more efficient that calling hash() on a string with the contents of file.

Hash functions are extremely sensitive to input. You should not expect to get the same answer from this function as you would from every other tool, since it depends on how whitespace and end of file characters are handled.

Arguments:

  • file: string, in the range: "?(/.*)
  • algorithm: one of
    • md5
    • sha1
    • sha256
    • sha384
    • sha512

Example:

Prepare:

echo 1234567890 > FILE.txt
chmod 0755 FILE.txt
chown 0 FILE.txt
chgrp 0 FILE.txt

Run:

body common control
{
      bundlesequence => { "example" };
}

bundle agent example

{
  vars:

      "md5" string => file_hash("/tmp/1","md5");
      "sha256" string => file_hash("/tmp/2","sha256");
      "sha384" string => hash("/tmp/3","sha384");
      "sha512" string => hash("/tmp/3","sha512");

  reports:

      "'1\n' hashed to: md5 $(md5)";
      "'2\n' hashed to: sha256 $(sha256)";
      "'3\n' hashed to: sha384 $(sha384)";
      "'3\n' hashed to: sha512 $(sha512)";

}

Output:

R: '1\n' hashed to: md5 b026324c6904b2a9cb4b88d6d61c81d1
R: '2\n' hashed to: sha256 53c234e5e8472b6ac51c1ae1cab3fe06fad053beb8ebfd8977b010655bfdd3c3
R: '3\n' hashed to: sha384 54f7379844b41bf513c0557a7195ca96a8ac90d0f8cc87d3607ef7ab593a7c61732759387afaabaf72ca2c0bd599373e
R: '3\n' hashed to: sha512 48b3c46b24db82059b5c87603066cf8d2165837d66e268286feb384644c808c06edf99aeaca0d879f4ee6ec70ebfaa0b98d5b77c12f7c0a68de3f7302dec6e21

History: Introduced in CFEngine 3.7.0

See also: hash()