Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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...