Obtaining Hash as a Part of 11ty Build

Last week I stated in post that I’m not singing my software anymore. So someone might be wondering how do I check I have executable coming from you. Well, together with that post I also added SHA-256 to every file that gets downloaded from my site. If you don’t know how, I even created Summae in order to bring this information into the context menu. And, to make the whole task of generating SHA-256 easier on myself, I added it as part of the build process.

First, I had to add crypto-js package to my 11ty package:

npm install crypto-js

Then, in eleventy.config.mjs, I added an import:

import cryptojs from "crypto-js";

Lastly, into eleventy.config.mjs default function I added the sha256 shortcode:

eleventyConfig.addShortcode("sha256", async function (file) {
  const filePath = path.join(eleventyConfig.directories.output, file);
  if (fs.existsSync(filePath)) {
    const fileContent = fs.readFileSync(filePath, 'binary')
    const sha256hash = crypto.createHash('sha256').update(fileContent, 'binary').digest('hex');
    return sha256hash;
  } else {
    console.error(`File not found: ${filePath}`);
    process.exit(1);
    return "";
  }
});

Whenever I want to use the shortcode, I just add a call to it using the file name as an argument.

{% sha256 "/download/file.zip" %}

Now, in reality, there is a bit more code - especially in the templating area. But that code is just to read data from variables, style the output, etc.

So, how does this help?

Well, it allows the end user to check file validity. If hash code matches you know that download was successful and you got the file I was intending to provide. And I can offer this at no cost to myself.