MD5 Message-Digest Algorithm for C#

C#MD5ハッシュ値を計算するには,普通はMD5CryptoServiceProviderクラスを使えば簡単にできるんだけど,C#ハッシュ値を直接計算するプログラムは無いみたいだったので作ってみた.コードはSOURCE CODE FOR MD5のページにある C のコードをベースに作ってある.ただし機能は大幅に削ってあって,与えた文字列のハッシュ値を表示する機能だけになっている.

もし何かに利用する場合は,私自身は特に利用制限はしないけど,動作の保証はできない点と,元のコードのライセンスには注意.

/*
 **********************************************************************
 ** md5.cs                                                           **
 ** RSA Data Security, Inc. MD5 Message Digest Algorithm             **
 ** Created: 2/17/90 RLR (md5.c)                                     **
 ** Revised: 1/91 (md5.c) SRD,AJ,BSK,JT Reference C Version          **
 ** Ported: 11/19/2010 royalcrab/hypercrab                           **
 **********************************************************************
 */

/*
 **********************************************************************
 ** Copyright (C) 1990, RSA Data Security, Inc. All rights reserved. **
 **                                                                  **
 ** License to copy and use this software is granted provided that   **
 ** it is identified as the "RSA Data Security, Inc. MD5 Message     **
 ** Digest Algorithm" in all material mentioning or referencing this **
 ** software or this function.                                       **
 **                                                                  **
 ** License is also granted to make and use derivative works         **
 ** provided that such works are identified as "derived from the RSA **
 ** Data Security, Inc. MD5 Message Digest Algorithm" in all         **
 ** material mentioning or referencing the derived work.             **
 **                                                                  **
 ** RSA Data Security, Inc. makes no representations concerning      **
 ** either the merchantability of this software or the suitability   **
 ** of this software for any particular purpose.  It is provided "as **
 ** is" without express or implied warranty of any kind.             **
 **                                                                  **
 ** These notices must be retained in any copies of any part of this **
 ** documentation and/or software.                                   **
 **********************************************************************
 */

using System;
using System.Text;

/* Data structure for MD5 (Message Digest) computation */
public class MD5_CTX {
    public uint [] i;                   /* number of _bits_ handled mod 2^64 */
    public uint [] buf;                                    /* scratch buffer */
    public byte [] inx;                              /* input buffer */
    public byte [] digest;     /* actual digest after MD5Final call */
    
    public MD5_CTX(){
	i = new uint[2];
	buf = new uint[4];
	inx = new byte[64];
	digest = new byte[16];
    }

}


public class MD5 {

    byte [] PADDING = new byte[64];

    const byte S11 = 7;
    const byte S12 = 12;
    const byte S13 = 17;
    const byte S14 = 22;
	
    const byte S21 = 5;
    const byte S22 = 9;
    const byte S23 = 14;
    const byte S24 = 20;
	
    const byte S31 = 4;
    const byte S32 = 11;
    const byte S33 = 16;
    const byte S34 = 23;

    const byte S41 = 6;
    const byte S42 = 10;
    const byte S43 = 15;
    const byte S44 = 21;

    MD5_CTX mdContext;

    public MD5()
    {
	PADDING[0] = 0x80;
	mdContext = new MD5_CTX();

	mdContext.i[0] = mdContext.i[1] = (uint)0;
	
	/* Load magic initialization constants.
	 */
	mdContext.buf[0] = (uint)0x67452301;
	mdContext.buf[1] = (uint)0xefcdab89;
	mdContext.buf[2] = (uint)0x98badcfe;
	mdContext.buf[3] = (uint)0x10325476;
    }

    public void MD5Update(byte [] inBuf, uint inLen)
    {
	uint [] inx = new uint[16];
	int mdi;
	uint i, ii;
	int bufcount = 0;

	/* compute number of bytes mod 64 */
	mdi = (int)((mdContext.i[0] >> 3) & 0x3F);
	
	/* update number of bits */
	if ((mdContext.i[0] + ((uint)inLen << 3)) < mdContext.i[0])
	    mdContext.i[1]++;
	mdContext.i[0] += ((uint)inLen << 3);
	mdContext.i[1] += ((uint)inLen >> 29);
	
	while ((inLen--) > 0) {
	    /* add new character to buffer, increment mdi */
	    mdContext.inx[mdi++] = inBuf[bufcount];
	    bufcount ++;
	    
	    /* transform if necessary */
	    if (mdi == 0x40) {
		for (i = 0, ii = 0; i < 16; i++, ii += 4)
		    inx[i] = (((uint)mdContext.inx[ii+3]) << 24) |
			(((uint)mdContext.inx[ii+2]) << 16) |
			(((uint)mdContext.inx[ii+1]) << 8) |
			((uint)mdContext.inx[ii]);
		Transform(mdContext.buf, inx);
		mdi = 0;
	    }
	}
    }

/* F, G and H are basic MD5 functions: selection, majority, parity */
    uint F(uint x, uint y, uint z){
	return (((x) & (y)) | ((~x) & (z)));
    }
    uint G(uint x, uint y, uint z){
	return (((x) & (z)) | ((y) & (~z)));
    }
    uint H(uint x, uint y, uint z){
	return ((x) ^ (y) ^ (z));
    }
    uint I(uint x, uint y, uint z){
	return ((y) ^ ((x) | (~z)));
    }

/* ROTATE_LEFT rotates x left n bits */
    uint ROTATE_LEFT(uint x, byte n){
	return (((x) << (n)) | ((x) >> (32-(n))));
    }

/* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4 */
/* Rotation is separate from addition to prevent recomputation */
    uint FF(uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
    {
	(a) += F ((b), (c), (d)) + (x) + (uint)(ac); 
	(a) = ROTATE_LEFT ((a), (s)); 
	(a) += (b); 
	return a;
    }

    uint GG(uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
    {
	(a) += G ((b), (c), (d)) + (x) + (uint)(ac);
	(a) = ROTATE_LEFT ((a), (s));
	(a) += (b);
	return a;
    }

    uint HH(uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
    {
	(a) += H ((b), (c), (d)) + (x) + (uint)(ac);
	(a) = ROTATE_LEFT ((a), (s));
	(a) += (b);
	return a;
    }

    uint II(uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
    {
	(a) += I ((b), (c), (d)) + (x) + (uint)(ac);
	(a) = ROTATE_LEFT ((a), (s));
	(a) += (b);
	return a;
    }

    void Transform (uint [] buf, uint [] inx)
    {
	uint a = buf[0], b = buf[1], c = buf[2], d = buf[3];
	
	/* Round 1 */
	a = FF ( a, b, c, d, inx[ 0], S11, 3614090360); /* 1 */
	d = FF ( d, a, b, c, inx[ 1], S12, 3905402710); /* 2 */
	c = FF ( c, d, a, b, inx[ 2], S13,  606105819); /* 3 */
	b = FF ( b, c, d, a, inx[ 3], S14, 3250441966); /* 4 */
	a = FF ( a, b, c, d, inx[ 4], S11, 4118548399); /* 5 */
	d = FF ( d, a, b, c, inx[ 5], S12, 1200080426); /* 6 */
	c = FF ( c, d, a, b, inx[ 6], S13, 2821735955); /* 7 */
	b = FF ( b, c, d, a, inx[ 7], S14, 4249261313); /* 8 */
	a = FF ( a, b, c, d, inx[ 8], S11, 1770035416); /* 9 */
	d = FF ( d, a, b, c, inx[ 9], S12, 2336552879); /* 10 */
	c = FF ( c, d, a, b, inx[10], S13, 4294925233); /* 11 */
	b = FF ( b, c, d, a, inx[11], S14, 2304563134); /* 12 */
	a = FF ( a, b, c, d, inx[12], S11, 1804603682); /* 13 */
	d = FF ( d, a, b, c, inx[13], S12, 4254626195); /* 14 */
	c = FF ( c, d, a, b, inx[14], S13, 2792965006); /* 15 */
	b = FF ( b, c, d, a, inx[15], S14, 1236535329); /* 16 */

	/* Round 2 */
	a = GG ( a, b, c, d, inx[ 1], S21, 4129170786); /* 17 */
	d = GG ( d, a, b, c, inx[ 6], S22, 3225465664); /* 18 */
	c = GG ( c, d, a, b, inx[11], S23,  643717713); /* 19 */
	b = GG ( b, c, d, a, inx[ 0], S24, 3921069994); /* 20 */
	a = GG ( a, b, c, d, inx[ 5], S21, 3593408605); /* 21 */
	d = GG ( d, a, b, c, inx[10], S22,   38016083); /* 22 */
	c = GG ( c, d, a, b, inx[15], S23, 3634488961); /* 23 */
	b = GG ( b, c, d, a, inx[ 4], S24, 3889429448); /* 24 */
	a = GG ( a, b, c, d, inx[ 9], S21,  568446438); /* 25 */
	d = GG ( d, a, b, c, inx[14], S22, 3275163606); /* 26 */
	c = GG ( c, d, a, b, inx[ 3], S23, 4107603335); /* 27 */
	b = GG ( b, c, d, a, inx[ 8], S24, 1163531501); /* 28 */
	a = GG ( a, b, c, d, inx[13], S21, 2850285829); /* 29 */
	d = GG ( d, a, b, c, inx[ 2], S22, 4243563512); /* 30 */
	c = GG ( c, d, a, b, inx[ 7], S23, 1735328473); /* 31 */
	b = GG ( b, c, d, a, inx[12], S24, 2368359562); /* 32 */

	/* Round 3 */
	a = HH ( a, b, c, d, inx[ 5], S31, 4294588738); /* 33 */
	d = HH ( d, a, b, c, inx[ 8], S32, 2272392833); /* 34 */
	c = HH ( c, d, a, b, inx[11], S33, 1839030562); /* 35 */
	b = HH ( b, c, d, a, inx[14], S34, 4259657740); /* 36 */
	a = HH ( a, b, c, d, inx[ 1], S31, 2763975236); /* 37 */
	d = HH ( d, a, b, c, inx[ 4], S32, 1272893353); /* 38 */
	c = HH ( c, d, a, b, inx[ 7], S33, 4139469664); /* 39 */
	b = HH ( b, c, d, a, inx[10], S34, 3200236656); /* 40 */
	a = HH ( a, b, c, d, inx[13], S31,  681279174); /* 41 */
	d = HH ( d, a, b, c, inx[ 0], S32, 3936430074); /* 42 */
	c = HH ( c, d, a, b, inx[ 3], S33, 3572445317); /* 43 */
	b = HH ( b, c, d, a, inx[ 6], S34,   76029189); /* 44 */
	a = HH ( a, b, c, d, inx[ 9], S31, 3654602809); /* 45 */
	d = HH ( d, a, b, c, inx[12], S32, 3873151461); /* 46 */
	c = HH ( c, d, a, b, inx[15], S33,  530742520); /* 47 */
	b = HH ( b, c, d, a, inx[ 2], S34, 3299628645); /* 48 */

	/* Round 4 */
	a = II ( a, b, c, d, inx[ 0], S41, 4096336452); /* 49 */
	d = II ( d, a, b, c, inx[ 7], S42, 1126891415); /* 50 */
	c = II ( c, d, a, b, inx[14], S43, 2878612391); /* 51 */
	b = II ( b, c, d, a, inx[ 5], S44, 4237533241); /* 52 */
	a = II ( a, b, c, d, inx[12], S41, 1700485571); /* 53 */
	d = II ( d, a, b, c, inx[ 3], S42, 2399980690); /* 54 */
	c = II ( c, d, a, b, inx[10], S43, 4293915773); /* 55 */
	b = II ( b, c, d, a, inx[ 1], S44, 2240044497); /* 56 */
	a = II ( a, b, c, d, inx[ 8], S41, 1873313359); /* 57 */
	d = II ( d, a, b, c, inx[15], S42, 4264355552); /* 58 */
	c = II ( c, d, a, b, inx[ 6], S43, 2734768916); /* 59 */
	b = II ( b, c, d, a, inx[13], S44, 1309151649); /* 60 */
	a = II ( a, b, c, d, inx[ 4], S41, 4149444226); /* 61 */
	d = II ( d, a, b, c, inx[11], S42, 3174756917); /* 62 */
	c = II ( c, d, a, b, inx[ 2], S43,  718787259); /* 63 */
	b = II ( b, c, d, a, inx[ 9], S44, 3951481745); /* 64 */

	buf[0] += a;
	buf[1] += b;
	buf[2] += c;
	buf[3] += d;
    }

    void MD5Final()
    {
	uint [] inx = new uint[16];
	int mdi;
	uint i, ii;
	uint padLen;
	
	/* save number of bits */
	inx[14] = mdContext.i[0];
	inx[15] = mdContext.i[1];
	
	/* compute number of bytes mod 64 */
	mdi = (int)((mdContext.i[0] >> 3) & 0x3F);
	
	/* pad out to 56 mod 64 */
	padLen = (uint)((mdi < 56) ? (56 - mdi) : (120 - mdi));
	MD5Update(PADDING, padLen);
	
	/* append length in bits and transform */
	for (i = 0, ii = 0; i < 14; i++, ii += 4)
	    inx[i] = (((uint)mdContext.inx[ii+3]) << 24) |
		(((uint)mdContext.inx[ii+2]) << 16) |
		(((uint)mdContext.inx[ii+1]) << 8) |
		((uint)mdContext.inx[ii]);
	Transform(mdContext.buf, inx);
	
	/* store buffer in digest */
	for (i = 0, ii = 0; i < 4; i++, ii += 4) {
	    mdContext.digest[ii] = (byte)(mdContext.buf[i] & 0xFF);
	    mdContext.digest[ii+1] =
		(byte)((mdContext.buf[i] >> 8) & 0xFF);
	    mdContext.digest[ii+2] =
		(byte)((mdContext.buf[i] >> 16) & 0xFF);
	    mdContext.digest[ii+3] =
		(byte)((mdContext.buf[i] >> 24) & 0xFF);
	}
    }

    void MDPrint ()
    {
	for (int i = 0; i < 16; i++)
	    System.Console.Write(mdContext.digest[i].ToString("X2"));
	System.Console.Write("\n");
    }

    public static void MDString (string str )
    {
	byte [] buf = Encoding.Unicode.GetBytes(str);
	uint len = (uint)str.Length;
	
	MD5 md5 = new MD5();
	md5.MD5Update(buf, len);
	md5.MD5Final();
	md5.MDPrint();

    }
}

public class Md5Test {
    static public void Main ()
    {
	string str = "hypercrab";
	MD5.MDString( str );
    }
}

Windowsコンパイルする場合は,上記を md5.cs とかの名前で保存しておいて,Visual Studio のコンソールで(または自力で csc.exe にパスを通して),

> csc.exe md5.cs

とする.実行すると,

> md5.exe
5AB839F6DB69CFE9B738AABC895F833D
>

こうなるはず.