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.
Let's print an MD5 digest by executing the following steps:
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())); }
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.
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.
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.
18.188.227.4