Writing a digest utility

Phobos provides a package called std.digest that offers checksum and message digest algorithms through a unified API. Here, we'll create a small MD5 utility that calculates and prints the resulting digest of a file.

How to do it…

Let's print an MD5 digest by executing the following steps:

  1. Create a digest object with the algorithm you need. Here, we'll use MD5 from std.digest.md.
  2. Call the start method.
  3. Use the put method, or the put function from std.range, to feed data to the digest object.
  4. Call the finish method.
  5. Convert hexadecimal data to string if you want.

The code is as follows:

void main(string[] args) {
    import std.digest.md;
    import std.stdio;
    import std.range;

    File file;
    if(args.length > 1)
        file = File(args[1], "rb");
    else
        file = stdin;
    MD5 digest;
    digest.start();
    put(digest, file.byChunk(1024));
    writeln(toHexString(digest.finish()));
}

How it works…

The std.digest package in Phobos defines modules that all follow a common API. The digest structures are output ranges, which means you feed data to them by calling their put method. Each digest algorithm is in a separate module, but they all follow the same pattern: you create the object, call start(), put your data into it, and then call finish() to get the result. If you want it as a printable string, call toHexString on the result.

Tip

If you pass a digest structure to a function, be sure to pass it as a reference, because they are value types. So, without a reference, data added to it inside a function won't be visible outside the function!

The put method on the structure itself offers only one form, accepting one array of data at a time. However, the std.range module includes additional helper functions to expand the capabilities of any output range. The std.range.put function can also accept input ranges. The end result is we build something very similar to a Unix pipeline; put(digest, file.byChunk(1024)) will read a file, one kilobyte chunk at a time, and feed that data into the digest algorithm. The std.range.put method looks like the following:

foreach(chunk; input) output.put(chunk);

It is a generic function that works to connect any kind of output range to any kind of input range with a matching element type.

There's more…

Phobos' digest API also provides two other ways to get digests: a convenience function if all the data is available at once, md5Of, and the OOP API (an interface and classes) if you need to swap out implementations at runtime.

writeln("The MD5 hash of 'test' is ", toHexString(md5Of("test")));

There are also other algorithms available in std.digest with the same API, including SHA1 and CRC.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.196.244