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:
Create a digest object with the algorithm you need. Here, we'll use MD5 from
std.digest.md
.Call the
start
method.Use the
put
method, or theput
function fromstd.range
, to feed data to the digest object.Call the
finish
method.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...