2007-08-07

md5函数的学习程序

关键字: md5 D语言
前面部分是库文件里面的例子,后面是我改的。
写起来和PHP差不多简单。呵呵,有例子就是好。

源程序里面定义编译不了:
ubyte[4 * 1024] buffer;
我改成了
ubyte[] buffer;
buffer.length = 4 * 1024;
也许下面的写法更好些,谁知道呢?
ubyte[] buffer = new ubyte[4 * 1024];

代码如下:

// This code is derived from the
// RSA Data Security, Inc. MD5 Message-Digest Algorithm.

import std.md5;

private import std.stdio;
private import std.string;
private import std.c.stdio;
private import std.c.string;

int main(char[][] args)
{
    foreach (char[] arg; args)
     MDFile(arg);

    MDString("Hello, D");

    return 0;
}

/* Digests a file and prints the result. */
void MDFile(char[] filename)
{
    FILE* file;
    MD5_CTX context;
    int len;
    //ubyte[4 * 1024] buffer;
    ubyte[] buffer;
    buffer.length = 4 * 1024;
    ubyte digest[16];

    if ((file = fopen(std.string.toStringz(filename), "rb")) == null)
    {
        writefln("%s can't be opened", filename);
    }
    else
    {
        context.start();
        while ((len = fread(cast(void*) buffer, 1, buffer.sizeof, file)) != 0)
            context.update(buffer[0 .. len]);
        context.finish(digest);
        fclose(file);

        writefln("MD5 File (%s) = %s", filename, digestToString(digest));
    }
}

/* Digest a string and prints the result. */
void MDString(char[] str)
{
    MD5_CTX context;
    ubyte digest[16];

    if (str.length)
    {
        context.start();
        context.update(str);
        context.finish(digest);

        if (str.length > 10)
            writefln("MD5 String (%s..) = %s", str[0..10], digestToString(digest));
        else
            writefln("MD5 String (%s) = %s", str, digestToString(digest));
    }
}
  • md5.zip (686 Bytes)
  • 描述:
  • 下载次数: 3
评论
发表评论

您还没有登录,请登录后发表评论

sofire
搜索本博客
最近加入圈子
存档
最新评论
评论排行榜