首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

MD5 演算法 C# 完整實作(四):輸出格式、標準測試向量與完整原始碼

     編輯:關於C語言

步驟 6:輸出 128 位雜湊值

A、B、C、D 四個 32 位暫存器連續儲存,共 16 位元組。依序以十六進位輸出每個位元組 (低位在前,小端序)。

標準測試向量 (RFC 1321)

MD5("")                    = d41d8cd98f00b204e9800998ecf8427e
MD5("a")                   = 0cc175b9c0f1b6a831c399e269772661
MD5("abc")                 = 900150983cd24fb0d6963f7d28e17f72
MD5("message digest")      = f96b697d7cb7938d525a2f31aaf161d0
MD5("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b
MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") = d174ab98d277d9f5a5611c2c9f419d9f
MD5("1234567890...長字串") = 57edf4a22be3c955ac49da2e2107b67a

實作通過上述測試即視為正確。

完整 C# 實作原始碼 (md5.cs)

using System; using System.Collections; using System.IO;
public class MD5 {
    private static uint A, B, C, D;
    private const int S11=7, S12=12, S13=17, S14=22,
                      S21=5, S22=9, S23=14, S24=20,
                      S31=4, S32=11, S33=16, S34=23,
                      S41=6, S42=10, S43=15, S44=21;

    private static uint F(uint x,uint y,uint z) => (x&y)|(~x&z);
    private static uint G(uint x,uint y,uint z) => (x&z)|(y&~z);
    private static uint H(uint x,uint y,uint z) => x^y^z;
    private static uint I(uint x,uint y,uint z) => y^(x|~z);

    private static void FF(ref uint a,uint b,uint c,uint d,uint mj,int s,uint ti) {
        a = a + F(b,c,d) + mj + ti; a = (a<>(32-s)); a += b;
    }
    private static void GG(ref uint a,uint b,uint c,uint d,uint mj,int s,uint ti) {
        a = a + G(b,c,d) + mj + ti; a = (a<>(32-s)); a += b;
    }
    private static void HH(ref uint a,uint b,uint c,uint d,uint mj,int s,uint ti) {
        a = a + H(b,c,d) + mj + ti; a = (a<>(32-s)); a += b;
    }
    private static void II(ref uint a,uint b,uint c,uint d,uint mj,int s,uint ti) {
        a = a + I(b,c,d) + mj + ti; a = (a<>(32-s)); a += b;
    }
    private static void MD5_Init() { A=0x67452301; B=0xefcdab89; C=0x98badcfe; D=0x10325476; }
    // ... MD5_Append (填充)、MD5_Transform (四輪壓縮)、MD5Array、ArrayToHexString、MDString、MDFile、TestSuite 完整實作見原文
}

作者註:MD5 適合組合語言,高階語言處理位運算易出錯;C# 功能完整,花一晚調試位移、補位邏輯終通過測試。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved