MD5可以加密Null对象和空字符串吗?

在软件开发中,数据的安全性和完整性至关重要。MD5加密是一种常用的数据加密技术,它可以将任意长度的数据转换成固定长度的哈希值。

然而,当处理Null对象和空字符串时,开发人员需要特别注意,以确保加密过程的正确性和安全性。

什么是MD5加密?

MD5(Message Digest Algorithm 5)是一种常用的哈希函数,用于产生128位(16字节)的哈希值。它广泛应用于数据完整性校验、数字签名等领域。

MD5加密的核心思想是将输入数据通过一系列复杂的算法转换成固定长度的哈希值,且同一输入始终产生相同的输出,但不可逆。

加密Null对象

在实际开发中,经常会遇到处理Null对象的情况。

我们来试试加密Null字符串对象:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Encryption {

    public static void main(String[] args) {
        String nullObject = null;
        String md5Hash = calculateMD5(nullObject);
        System.out.println("MD5 Hash of Null Object: " + md5Hash);
    }

    public static String calculateMD5(String input) {
        try {
            // 创建MessageDigest对象,并指定使用MD5算法
            MessageDigest md = MessageDigest.getInstance("MD5");
            
            // 将数据转换成字节数组,并进行MD5哈希计算
            byte[] byteData = md.digest(input.getBytes());

            // 将字节数组转换成十六进制字符串表示
            StringBuilder sb = new StringBuilder();
            for (byte b : byteData) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
}

眼尖的小伙伴估计已经发现了,当代码执行到input.getBytes()这里时,如果input是null,那么就会触发空异常,最终代码进入catch中,返回null。

当需要对Null对象进行MD5加密时,应该采取适当的处理策略,以避免出现空指针异常或安全漏洞。

处理Null对象

在实际开发中,经常会遇到处理Null对象的情况。当需要对Null对象进行MD5加密时,开发人员应该采取适当的处理策略,以避免出现空指针异常或安全漏洞。

使用空字符串替代Null

一种常见的处理方法是将Null对象替换为空字符串,然后再进行MD5加密。这样可以确保加密算法接收到有效的输入数据,避免了空指针异常的发生。例如,在Java中可以使用三目运算符或if语句进行处理:

String data = (nullObject != null) ? nullObject : "";
String md5Hash = calculateMD5(data);

定义默认值

另一种处理Null对象的方法是定义默认值,在加密之前先对Null对象进行检查,如果为Null,则使用预先定义的默认值。这样可以提高代码的可读性和稳定性,确保加密过程的正确性。

例如:

String data = (nullObject != null) ? nullObject : "default";
String md5Hash = calculateMD5(data);

加密空字符串

上面举例了,null对象的处理方式,其中一种就是设置为空字符串,所以这种方法是可以的。

加密后输出结果:

String data = "";
String md5Hash = calculateMD5(data);

输出:
D41D8CD98F00B204E9800998ECF8427E

处理空字符串

与处理Null对象类似,处理空字符串时也需要特别注意,以确保加密过程的准确性和安全性。

直接加密空字符串

最简单的处理方式是直接对空字符串进行MD5加密。由于MD5加密算法是确定性的,因此空字符串的哈希值也是固定的。

例如:

String data = "";
String md5Hash = calculateMD5(data);

添加额外处理逻辑

有时候,开发人员可能需要根据具体业务需求对空字符串进行特殊处理。例如,可以将空字符串转换为指定的默认值,然后再进行MD5加密。这样可以增加代码的灵活性和可定制性。

例如:

String data = (inputString.isEmpty()) ? "default" : inputString;
String md5Hash = calculateMD5(data);

总结

在使用MD5加密算法时,处理Null对象和空字符串是常见的需求。通过采取适当的处理策略,开发人员可以确保加密过程的正确性和安全性。

无论是使用空字符串替代Null对象,还是定义默认值,都可以有效地避免潜在的安全风险。

因此,在实际开发中,务必注意对Null对象和空字符串的处理,以提高系统的稳定性和安全性。

不管做什么,只要坚持下去就会不一样!

  • 27
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
package util; import java.lang.reflect.*; public class MD5 { /* 下面这些S11-S44实际上是一个4*4的矩阵,在原始的C实现中是用#define 实现的, 这里把它们实现成为static final是表示了只读,切能在同一个进程间内的多个 Instance间共享*/ static final int S11 = 7; static final int S12 = 12; static final int S13 = 17; static final int S14 = 22; static final int S21 = 5; static final int S22 = 9; static final int S23 = 14; static final int S24 = 20; static final int S31 = 4; static final int S32 = 11; static final int S33 = 16; static final int S34 = 23; static final int S41 = 6; static final int S42 = 10; static final int S43 = 15; static final int S44 = 21; static final byte[] PADDING = { -128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* 下面的三个成员是MD5计算过程中用到的3个核心数据,在原始的C实现中 被定义到MD5_CTX结构中 */ private long[] state = new long[4]; // state (ABCD) private long[] count = new long[2]; // number of bits, modulo 2^64 (lsb first) private byte[] buffer = new byte[64]; // input buffer /* digestHexStr是MD5的唯一一个公共成员,是最新一次计算结果的   16进制ASCII表示. */ public String digestHexStr; /* digest,是最新一次计算结果的2进制内部表示,表示128bit的MD5值. */ private byte[] digest = new byte[16]; /* getMD5ofStr是类MD5最主要的公共方法,入口参数是你想要进行MD5变换的字符串 返回的是变换完的结果,这个结果是从公共成员digestHexStr取得的. */ public String getMD5ofStr(String inbuf) { md5Init(); md5Update(inbuf.getBytes(), inbuf.length()); md5Final(); digestHexStr = ""; for (int i = 0; i < 16; i++) { digestHexStr += byteHEX(digest[i]); } return digestHexStr; } // 这是MD5这个类的标准构造函数,JavaBean要求有一个public的并且没有参数的构造函数 public MD5() { md5Init(); return; } /* md5Init是一个初始化函数,初始化核心变量,装入标准的幻数 */ private void md5Init() { count[0] = 0L; count[1] = 0L; ///* Load magic initialization constants. state[0] = 0x67452301L; state[1] = 0xefcdab89L; state[2] = 0x98badcfeL; state[3] = 0x10325476L; return; } /* F, G, H ,I 是4个基本的MD5函数,在原始的MD5的C实现中,由于它们是 简单的位运算,可能出于效率的考虑把它们实现成了宏,在java中,我们把它们   实现成了private方法,名字保持了原来C中的。 */ private long F(long x, long y, long z) { return (x & y) | ((~x) & z); } private long G(long x, long y, long z) { return (x & z) | (y & (~z)); } private long H(long x, long y, long z) { return x ^ y ^ z; } private long I(long x, long y, long z) { return y ^ (x | (~z)); } /* FF,GG,HH和II将调用F,G,H,I进行近一步变换 FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. Rotation is separate from addition to prevent recomputation. */ private long FF(long a, long b, long c, long d, long x, long s, long ac) { a += F (b, c, d) + x + ac; a = ((int) a << s) | ((int) a >>> (32 - s)); a += b; return a; } private long GG(long a, long b, long c, long d, long x, long s, long ac) { a += G (b, c, d) + x + ac; a = ((int) a << s) | ((int) a >>> (32 - s)); a += b; return a; } private long HH(long a, long b, long c, long d, long x, long s, long ac) { a += H (b, c, d) + x + ac; a = ((int) a << s) | ((int) a >>> (32 - s)); a += b; return a; } private long II(long a, long b, long c, long d, long x, long s, long ac) { a += I (b, c, d) + x + ac; a = ((int) a << s) | ((int) a >>> (32 - s)); a += b; return a; } /* md5Update是MD5的主计算过程,inbuf是要变换的字节串,inputlen是长度,这个 函数由getMD5ofStr调用,调用之前需要调用md5init,因此把它设计成private的 */ private void md5Update(byte[] inbuf, int inputLen) { int i, index, partLen; byte[] block = new byte[64]; index = (int)(count[0] >>> 3) & 0x3F; // /* Update number of bits */ if ((count[0] += (inputLen << 3)) < (inputLen << 3)) count[1]++; count[1] += (inputLen >>> 29); partLen = 64 - index; // Transform as many times as possible. if (inputLen >= partLen) { md5Memcpy(buffer, inbuf, index, 0, partLen); md5Transform(buffer); for (i = partLen; i + 63 < inputLen; i += 64) { md5Memcpy(block, inbuf, 0, i, 64); md5Transform (block); } index = 0; } else i = 0; ///* Buffer remaining input */ md5Memcpy(buffer, inbuf, index, i, inputLen - i); } /* md5Final整理和填写输出结果 */ private void md5Final () { byte[] bits = new byte[8]; int index, padLen; ///* Save number of bits */ Encode (bits, count, 8); ///* Pad out to 56 mod 64. index = (int)(count[0] >>> 3) & 0x3f; padLen = (index < 56) ? (56 - index) : (120 - index); md5Update (PADDING, padLen); ///* Append length (before padding) */ md5Update(bits, 8); ///* Store state in digest */ Encode (digest, state, 16); } /* md5Memcpy是一个内部使用的byte数组的块拷贝函数,从input的inpos开始把len长度的       字节拷贝到output的outpos位置开始 */ private void md5Memcpy (byte[] output, byte[] input, int outpos, int inpos, int len) { int i; for (i = 0; i < len; i++) output[outpos + i] = input[inpos + i]; } /* md5Transform是MD5核心变换程序,有md5Update调用,block是分块的原始字节 */ private void md5Transform (byte block[]) { long a = state[0], b = state[1], c = state[2], d = state[3]; long[] x = new long[16]; Decode (x, block, 64); /* Round 1 */ a = FF (a, b, c, d, x[0], S11, 0xd76aa478L); /* 1 */ d = FF (d, a, b, c, x[1], S12, 0xe8c7b756L); /* 2 */ c = FF (c, d, a, b, x[2], S13, 0x242070dbL); /* 3 */ b = FF (b, c, d, a, x[3], S14, 0xc1bdceeeL); /* 4 */ a = FF (a, b, c, d, x[4], S11, 0xf57c0fafL); /* 5 */ d = FF (d, a, b, c, x[5], S12, 0x4787c62aL); /* 6 */ c = FF (c, d, a, b, x[6], S13, 0xa8304613L); /* 7 */ b = FF (b, c, d, a, x[7], S14, 0xfd469501L); /* 8 */ a = FF (a, b, c, d, x[8], S11, 0x698098d8L); /* 9 */ d = FF (d, a, b, c, x[9], S12, 0x8b44f7afL); /* 10 */ c = FF (c, d, a, b, x[10], S13, 0xffff5bb1L); /* 11 */ b = FF (b, c, d, a, x[11], S14, 0x895cd7beL); /* 12 */ a = FF (a, b, c, d, x[12], S11, 0x6b901122L); /* 13 */ d = FF (d, a, b, c, x[13], S12, 0xfd987193L); /* 14 */ c = FF (c, d, a, b, x[14], S13, 0xa679438eL); /* 15 */ b = FF (b, c, d, a, x[15], S14, 0x49b40821L); /* 16 */ /* Round 2 */ a = GG (a, b, c, d, x[1], S21, 0xf61e2562L); /* 17 */ d = GG (d, a, b, c, x[6], S22, 0xc040b340L); /* 18 */ c = GG (c, d, a, b, x[11], S23, 0x265e5a51L); /* 19 */ b = GG (b, c, d, a, x[0], S24, 0xe9b6c7aaL); /* 20 */ a = GG (a, b, c, d, x[5], S21, 0xd62f105dL); /* 21 */ d = GG (d, a, b, c, x[10], S22, 0x2441453L); /* 22 */ c = GG (c, d, a, b, x[15], S23, 0xd8a1e681L); /* 23 */ b = GG (b, c, d, a, x[4], S24, 0xe7d3fbc8L); /* 24 */ a = GG (a, b, c, d, x[9], S21, 0x21e1cde6L); /* 25 */ d = GG (d, a, b, c, x[14], S22, 0xc33707d6L); /* 26 */ c = GG (c, d, a, b, x[3], S23, 0xf4d50d87L); /* 27 */ b = GG (b, c, d, a, x[8], S24, 0x455a14edL); /* 28 */ a = GG (a, b, c, d, x[13], S21, 0xa9e3e905L); /* 29 */ d = GG (d, a, b, c, x[2], S22, 0xfcefa3f8L); /* 30 */ c = GG (c, d, a, b, x[7], S23, 0x676f02d9L); /* 31 */ b = GG (b, c, d, a, x[12], S24, 0x8d2a4c8aL); /* 32 */ /* Round 3 */ a = HH (a, b, c, d, x[5], S31, 0xfffa3942L); /* 33 */ d = HH (d, a, b, c, x[8], S32, 0x8771f681L); /* 34 */ c = HH (c, d, a, b, x[11], S33, 0x6d9d6122L); /* 35 */ b = HH (b, c, d, a, x[14], S34, 0xfde5380cL); /* 36 */ a = HH (a, b, c, d, x[1], S31, 0xa4beea44L); /* 37 */ d = HH (d, a, b, c, x[4], S32, 0x4bdecfa9L); /* 38 */ c = HH (c, d, a, b, x[7], S33, 0xf6bb4b60L); /* 39 */ b = HH (b, c, d, a, x[10], S34, 0xbebfbc70L); /* 40 */ a = HH (a, b, c, d, x[13], S31, 0x289b7ec6L); /* 41 */ d = HH (d, a, b, c, x[0], S32, 0xeaa127faL); /* 42 */ c = HH (c, d, a, b, x[3], S33, 0xd4ef3085L); /* 43 */ b = HH (b, c, d, a, x[6], S34, 0x4881d05L); /* 44 */ a = HH (a, b, c, d, x[9], S31, 0xd9d4d039L); /* 45 */ d = HH (d, a, b, c, x[12], S32, 0xe6db99e5L); /* 46 */ c = HH (c, d, a, b, x[15], S33, 0x1fa27cf8L); /* 47 */ b = HH (b, c, d, a, x[2], S34, 0xc4ac5665L); /* 48 */ /* Round 4 */ a = II (a, b, c, d, x[0], S41, 0xf4292244L); /* 49 */ d = II (d, a, b, c, x[7], S42, 0x432aff97L); /* 50 */ c = II (c, d, a, b, x[14], S43, 0xab9423a7L); /* 51 */ b = II (b, c, d, a, x[5], S44, 0xfc93a039L); /* 52 */ a = II (a, b, c, d, x[12], S41, 0x655b59c3L); /* 53 */ d = II (d, a, b, c, x[3], S42, 0x8f0ccc92L); /* 54 */ c = II (c, d, a, b, x[10], S43, 0xffeff47dL); /* 55 */ b = II (b, c, d, a, x[1], S44, 0x85845dd1L); /* 56 */ a = II (a, b, c, d, x[8], S41, 0x6fa87e4fL); /* 57 */ d = II (d, a, b, c, x[15], S42, 0xfe2ce6e0L); /* 58 */ c = II (c, d, a, b, x[6], S43, 0xa3014314L); /* 59 */ b = II (b, c, d, a, x[13], S44, 0x4e0811a1L); /* 60 */ a = II (a, b, c, d, x[4], S41, 0xf7537e82L); /* 61 */ d = II (d, a, b, c, x[11], S42, 0xbd3af235L); /* 62 */ c = II (c, d, a, b, x[2], S43, 0x2ad7d2bbL); /* 63 */ b = II (b, c, d, a, x[9], S44, 0xeb86d391L); /* 64 */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; } /*Encode把long数组按顺序拆成byte数组,因为java的long类型是64bit的, 只拆低32bit,以适应原始C实现的用途 */ private void Encode (byte[] output, long[] input, int len) { int i, j; for (i = 0, j = 0; j < len; i++, j += 4) { output[j] = (byte)(input[i] & 0xffL); output[j + 1] = (byte)((input[i] >>> 8) & 0xffL); output[j + 2] = (byte)((input[i] >>> 16) & 0xffL); output[j + 3] = (byte)((input[i] >>> 24) & 0xffL); } } /*Decode把byte数组按顺序合成成long数组,因为java的long类型是64bit的, 只合成低32bit,高32bit清零,以适应原始C实现的用途 */ private void Decode (long[] output, byte[] input, int len) { int i, j; for (i = 0, j = 0; j < len; i++, j += 4) output[i] = b2iu(input[j]) | (b2iu(input[j + 1]) << 8) | (b2iu(input[j + 2]) << 16) | (b2iu(input[j + 3]) << 24); return; } /* b2iu是我写的一个把byte按照不考虑正负号的原则的"升位"程序,因为java没有unsigned运算 */ public static long b2iu(byte b) { return b < 0 ? b & 0x7F + 128 : b; } /*byteHEX(),用来把一个byte类型的数转换成十六进制的ASCII表示,  因为java中的byte的toString无法实现这一点,我们又没有C语言中的 sprintf(outbuf,"%02X",ib) */ public static String byteHEX(byte ib) { char[] Digit = { '0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' }; char [] ob = new char[2]; ob[0] = Digit[(ib >>> 4) & 0X0F]; ob[1] = Digit[ib & 0X0F]; String s = new String(ob); return s; } public static String toMD5(String source){ MD5 md5 = new MD5(); return md5.getMD5ofStr(source); } }
MD5加密算法(Java版) 可以运行 原理   对MD5算法简要的叙述可以为:MD5以512位分组来处理输入的信息,且每一分组又被划分为16个32位子分组,经过了一系列的处理后,算法的输出由四个32位分组组成,将这四个32位分组级联后将生成一个128位散列值。   在MD5算法中,首先需要对信息进行填充,使其位长对512求余的结果等于448。因此,信息的位长(Bits Length)将被扩展至N*512+448,N为一个非负整数,N可以是零。填充的方法如下,在信息的后面填充一个1和无数个0,直到满足上面的条件时才停止用0对信息的填充。然后,在这个结果后面附加一个以64位二进制表示的填充前信息长度。经过这两步的处理,现在的信息的位长=N*512+448+64=(N+1)*512,即长度恰好是512的整数倍。这样做的原因是为满足后面处理中对信息长度的要求。   MD5中有四个32位被称作链接变量(Chaining Variable)的整数参数,他们分别为:A=0x67452301,B=0xefcdab89,C=0x98badcfe,D=0x10325476。   当设置好这四个链接变量后,就开始进入算法的四轮循环运算。循环的次数是信息中512位信息分组的数目。   将上面四个链接变量复制到另外四个变量中:A到a,B到b,C到c,D到d。   主循环有四轮(MD4只有三轮),每轮循环都很相似。第一轮进行16次操作。每次操作对a、b、c和d中的其中三个作一次非线性函数运算,然后将所得结果加上第四个变量,文本的一个子分组和一个常数。再将所得结果向左环移一个不定的数,并加上a、b、c或d中之一。最后用该结果取代a、b、c或d中之一。   以一下是每次操作中用到的四个非线性函数(每轮一个)。   F(X,Y,Z) =(X&Y)|((~X)&Z)   G(X,Y,Z) =(X&Z)|(Y&(~Z))   H(X,Y,Z) =X^Y^Z   I(X,Y,Z)=Y^(X|(~Z))   (&是与,|是或,~是非,^是异或)   这四个函数的说明:如果X、Y和Z的对应位是独立和均匀的,那么结果的每一位也应是独立和均匀的。   F是一个逐位运算的函数。即,如果X,那么Y,否则Z。函数H是逐位奇偶操作符。   假设Mj表示消息的第j个子分组(从0到15), 常数ti是4294967296*abs(sin(i))的整数部分,i取值从1到64,单位是弧度。(4294967296等于2的32次方)   FF(a, b, c, d, Mj, s, ti)表示 a = b + ((a + F(b, c, d) + Mj + ti) << s)   GG(a, b, c, d, Mj, s, ti)表示 a = b + ((a + G(b, c, d) + Mj + ti) << s)   HH(a, b, c, d, Mj, s, ti)表示 a = b + ((a + H(b, c, d) + Mj + ti) << s)   II(a, b, c, d, Mj, s, ti)表示 a = b + ((a + I(b, c, d) + Mj + ti) << s)   这四轮(64步)是:   第一轮   FF(a, b, c, d, M0, 7, 0xd76aa478)   FF(d, a, b, c, M1, 12, 0xe8c7b756)   FF(c, d, a, b, M2, 17, 0x242070db)   FF(b, c, d, a, M3, 22, 0xc1bdceee)   FF(a, b, c, d, M4, 7, 0xf57c0faf)   FF(d, a, b, c, M5, 12, 0x4787c62a)   FF(c, d, a, b, M6, 17, 0xa8304613)   FF(b, c, d, a, M7, 22, 0xfd469501)   FF(a, b, c, d, M8, 7, 0x698098d8)   FF(d, a, b, c, M9, 12, 0x8b44f7af)   FF(c, d, a, b, M10, 17, 0xffff5bb1)   FF(b, c, d, a, M11, 22, 0x895cd7be)   FF(a, b, c, d, M12, 7, 0x6b901122)   FF(d, a, b, c, M13, 12, 0xfd987193)   FF(c, d, a, b, M14, 17, 0xa679438e)   FF(b, c, d, a, M15, 22, 0x49b40821)   第二轮   GG(a, b, c, d, M1, 5, 0xf61e2562)   GG(d, a, b, c, M6, 9, 0xc040b340)   GG(c, d, a, b, M11, 14, 0x265e5a51)   GG(b, c, d, a, M0, 20, 0xe9b6c7aa)   GG(a, b, c, d, M5, 5, 0xd62f105d)   GG(d, a, b, c, M10, 9, 0x02441453)   GG(c, d, a, b, M15, 14, 0xd8a1e681)   GG(b, c, d, a, M4, 20, 0xe7d3fbc8)   GG(a, b, c, d, M9, 5, 0x21e1cde6)   GG(d, a, b, c, M14, 9, 0xc33707d6)   GG(c, d, a, b, M3, 14, 0xf4d50d87)   GG(b, c, d, a, M8, 20, 0x455a14ed)   GG(a, b, c, d, M13, 5, 0xa9e3e905)   GG(d, a, b, c, M2, 9, 0xfcefa3f8)   GG(c, d, a, b, M7, 14, 0x676f02d9)   GG(b, c, d, a, M12, 20, 0x8d2a4c8a)   第三轮   HH(a, b, c, d, M5, 4, 0xfffa3942)   HH(d, a, b, c, M8, 11, 0x8771f681)   HH(c, d, a, b, M11, 16, 0x6d9d6122)   HH(b, c, d, a, M14, 23, 0xfde5380c)   HH(a, b, c, d, M1, 4, 0xa4beea44)   HH(d, a, b, c, M4, 11, 0x4bdecfa9)   HH(c, d, a, b, M7, 16, 0xf6bb4b60)   HH(b, c, d, a, M10, 23, 0xbebfbc70)   HH(a, b, c, d, M13, 4, 0x289b7ec6)   HH(d, a, b, c, M0, 11, 0xeaa127fa)   HH(c, d, a, b, M3, 16, 0xd4ef3085)   HH(b, c, d, a, M6, 23, 0x04881d05)   HH(a, b, c, d, M9, 4, 0xd9d4d039)   HH(d, a, b, c, M12, 11, 0xe6db99e5)   HH(c, d, a, b, M15, 16, 0x1fa27cf8)   HH(b, c, d, a, M2, 23, 0xc4ac5665)   第四轮   II(a, b, c, d, M0, 6, 0xf4292244)   II(d, a, b, c, M7, 10, 0x432aff97)   II(c, d, a, b, M14, 15, 0xab9423a7)   II(b, c, d, a, M5, 21, 0xfc93a039)   II(a, b, c, d, M12, 6, 0x655b59c3)   II(d, a, b, c, M3, 10, 0x8f0ccc92)   II(c, d, a, b, M10, 15, 0xffeff47d)   II(b, c, d, a, M1, 21, 0x85845dd1)   II(a, b, c, d, M8, 6, 0x6fa87e4f)   II(d, a, b, c, M15, 10, 0xfe2ce6e0)   II(c, d, a, b, M6, 15, 0xa3014314)   II(b, c, d, a, M13, 21, 0x4e0811a1)   II(a, b, c, d, M4, 6, 0xf7537e82)   II(d, a, b, c, M11, 10, 0xbd3af235)   II(c, d, a, b, M2, 15, 0x2ad7d2bb)   II(b, c, d, a, M9, 21, 0xeb86d391)   所有这些完成之后,将A、B、C、D分别加上a、b、c、d。然后用下一分组数据继续运行算法,最后的输出是A、B、C和D的级联。   当你按照我上面所说的方法实现MD5算法以后,你可以用以下几个信息对你做出来的程序作一个简单的测试,看看程序有没有错误。   MD5 ("") = d41d8cd98f00b204e9800998ecf8427e   MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661   MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72   MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0   MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b   MD5 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") =   f29939a25efabaef3b87e2cbfe641315 VB2010实现   Imports System   Imports System.Security.Cryptography   Imports System.Text   Module Example   ' 哈希输入字符串并返回一个32字符的十六进制字符串哈希。   Function getMd5Hash(ByVal input As String) As String   ' 创建新的一个MD5CryptoServiceProvider对象的实例。   Dim md5Hasher As New MD5CryptoServiceProvider()   ' 输入的字符串转换为字节数组,并计算哈希。   Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))   ' 创建一个新的StringBuilder收集的字节,并创建一个字符串。   Dim sBuilder As New StringBuilder()   ' 通过每个字节的哈希数据和格式为十六进制字符串的每一个循环。   Dim i As Integer   For i = 0 To data.Length - 1   sBuilder.Append(data(i).ToString("x2"))   Next i   ' 返回十六进制字符串。   Return sBuilder.ToString()   End Function   ' 验证对一个字符串的哈希值。   Function verifyMd5Hash(ByVal input As String, ByVal hash As String) As Boolean   ' 哈希的输入。   Dim hashOfInput As String = getMd5Hash(input)   ' 创建StringComparer1的哈希进行比较。   Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase   If 0 = comparer.Compare(hashOfInput, hash) Then   Return True   Else   Return False   End If   End Function   Sub Main()   Dim source As String = "Hello World!"   Dim hash As String = getMd5Hash(source)   Console.WriteLine("进行MD5加密字符串为:" + source + " 加密的结果是:" + hash + ".")   Console.WriteLine("验证哈希...")   If verifyMd5Hash(source, hash) Then   Console.WriteLine("哈希值是相同的。")   Else   Console.WriteLine("哈希值是不相同的。")   End If   End Sub   End Module   ' 此代码示例产生下面的输出:   '   ' 进行MD5加密字符串为:Hello World! 加密的结果是:ed076287532e86365e841e92bfc50d8c.   ' 验证哈希...   ' 哈希值是相同的。 伪代码实现   //Note: All variables are unsigned 32 bits and wrap modulo 2^32 when calculating   var int[64] r, k //r specifies the per-round shift amounts   r[ 0..15]:= {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22}   r[16..31]:= {5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20}   r[32..47]:= {4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23}   r[48..63]:= {6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}   //Use binary integer part of the sines of integers as constants:   for i from 0 to 63   k[i] := floor(abs(sin(i + 1)) × 2^32)   //Initialize variables:   var int h0 := 0x67452301   var int h1 := 0xEFCDAB89   var int h2 := 0x98BADCFE   var int h3 := 0x10325476   //Pre-processing:   append "1" bit to message   append "0" bits until message length in bits ≡ 448 (mod 512)   append bit length of message as 64-bit little-endian integer to message   //Process the message in successive 512-bit chunks:   for each 512-bit chunk of message   break chunk into sixteen 32-bit little-endian words w[i], 0 ≤ i ≤ 15   //Initialize hash value for this chunk:   var int a := h0   var int b := h1   var int c := h2   var int d := h3   //Main loop:   for i from 0 to 63   if 0 ≤ i ≤ 15 then   f := (b and c) or ((not b) and d)   g := i   else if 16 ≤ i ≤ 31   f := (d and b) or ((not d) and c)   g := (5×i + 1) mod 16   else if 32 ≤ i ≤ 47   f := b xor c xor d   g := (3×i + 5) mod 16   else if 48 ≤ i ≤ 63   f := c xor (b or (not d))   g := (7×i) mod 16   temp := d   d := c   c := b   b := ((a + f + k[i] + w[g]) leftrotate r[i]) + b   a := temp   //Add this chunk's hash to result so far:   h0 := h0 + a   h1 := h1 + b   h2 := h2 + c   h3 := h3 + d   var int digest := h0 append h1 append h2 append h3   //(expressed as little-endian) 标准C语言实现   具体的一个MD5实现   /*   * md5 -- compute and check MD5 message digest.   * this version only can calculate the char string.   *   * MD5 (Message-Digest algorithm 5) is a widely used, partially   * insecure cryptographic hash function with a 128-bit hash value.   *   * Author: redraiment   * Date: Aug 27, 2008   * Version: 0.1.6   */   #include <stdlib.h>   #include <string.h>   #include <stdio.h>   #include <math.h>   #define SINGLE_ONE_BIT 0x80   #define BLOCK_SIZE 512   #define MOD_SIZE 448   #define APP_SIZE 64   #define BITS 8   // MD5 Chaining Variable   #define A 0x67452301UL   #define B 0xEFCDAB89UL   #define C 0x98BADCFEUL   #define D 0x10325476UL   // Creating own types   #ifdef UINT64   # undef UINT64   #endif   #ifdef UINT32   # undef UINT32   #endif   typedef unsigned long long UINT64;   typedef unsigned long UINT32;   typedef unsigned char UINT8;   typedef struct   {   char * message;   UINT64 length;   }STRING;   const UINT32 X[4][2] = {{0, 1}, {1, 5}, {5, 3}, {0, 7}};   // Constants for MD5 transform routine.   const UINT32 S[4][4] = {   { 7, 12, 17, 22 },   { 5, 9, 14, 20 },   { 4, 11, 16, 23 },   { 6, 10, 15, 21 }   };   // F, G, H and I are basic MD5 functions.   UINT32 F( UINT32 X, UINT32 Y, UINT32 Z )   {   return ( X & Y ) | ( ~X & Z );   }   UINT32 G( UINT32 X, UINT32 Y, UINT32 Z )   {   return ( X & Z ) | ( Y & ~Z );   }   UINT32 H( UINT32 X, UINT32 Y, UINT32 Z )   {   return X ^ Y ^ Z;   }   UINT32 I( UINT32 X, UINT32 Y, UINT32 Z )   {   return Y ^ ( X | ~Z );   }   // rotates x left s bits.   UINT32 rotate_left( UINT32 x, UINT32 s )   {   return ( x << s ) | ( x >> ( 32 - s ) );   }   // Pre-processin   UINT32 count_padding_bits ( UINT32 length )   {   UINT32 div = length * BITS / BLOCK_SIZE;   UINT32 mod = length * BITS % BLOCK_SIZE;   UINT32 c_bits;   if ( mod == 0 )   c_bits = MOD_SIZE;   else   c_bits = ( MOD_SIZE + BLOCK_SIZE - mod ) % BLOCK_SIZE;   return c_bits / BITS;   }   STRING append_padding_bits ( char * argv )   {   UINT32 msg_length = strlen ( argv );   UINT32 bit_length = count_padding_bits ( msg_length );   UINT64 app_length = msg_length * BITS;   STRING string;   string.message = (char *)malloc(msg_length + bit_length + APP_SIZE / BITS);   // Save message   strncpy ( string.message, argv, msg_length );   // Pad out to mod 64.   memset ( string.message + msg_length, 0, bit_length );   string.message [ msg_length ] = SINGLE_ONE_BIT;   // Append length (before padding).   memmove ( string.message + msg_length + bit_length, (char *)&app;_length, sizeof( UINT64 ) );   string.length = msg_length + bit_length + sizeof( UINT64 );   return string;   }   int main ( int argc, char *argv[] )   {   STRING string;   UINT32 w[16];   UINT32 chain[4];   UINT32 state[4];   UINT8 r[16];   UINT32 ( *auxi[ 4 ])( UINT32, UINT32, UINT32 ) = { F, G, H, I };   int roundIdx;   int argIdx;   int sIdx;   int wIdx;   int i;   int j;   if ( argc < 2 )   {   fprintf ( stderr, "usage: %s string ...\n", argv[ 0 ] );   return EXIT_FAILURE;   }   for ( argIdx = 1; argIdx < argc; argIdx++ )   {   string = append_padding_bits ( argv[ argIdx ] );   // MD5 initialization.   chain[0] = A;   chain[1] = B;   chain[2] = C;   chain[3] = D;   for ( j = 0; j < string.length; j += BLOCK_SIZE / BITS)   {   memmove ( (char *)w, string.message + j, BLOCK_SIZE / BITS );   memmove ( state, chain, sizeof(chain) );   for ( roundIdx = 0; roundIdx < 4; roundIdx++ )   {   wIdx = X[ roundIdx ][ 0 ];   sIdx = 0;   for ( i = 0; i < 16; i++ )   {   // FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.   // Rotation is separate from addition to prevent recomputation.   state[sIdx] = state [ (sIdx + 1) % 4 ] +   rotate_left ( state[sIdx] +   ( *auxi[ roundIdx ] )   ( state[(sIdx+1) % 4], state[(sIdx+2) % 4], state[(sIdx+3) % 4]) +   w[ wIdx ] +   (UINT32)floor( (1UL << 32) * fabs(sin( roundIdx * 16 + i + 1 )) ),   S[ roundIdx ][ i % 4 ]);   sIdx = ( sIdx + 3 ) % 4;   wIdx = ( wIdx + X[ roundIdx ][ 1 ] ) & 0xF;   }   }   chain[ 0 ] += state[ 0 ];   chain[ 1 ] += state[ 1 ];   chain[ 2 ] += state[ 2 ];   chain[ 3 ] += state[ 3 ];   }   memmove ( r + 0, (char *)&chain;[0], sizeof(UINT32) );   memmove ( r + 4, (char *)&chain;[1], sizeof(UINT32) );   memmove ( r + 8, (char *)&chain;[2], sizeof(UINT32) );   memmove ( r + 12, (char *)&chain;[3], sizeof(UINT32) );   for ( i = 0; i < 16; i++ )   printf ( "x", r[i] );   putchar ( '\n' );   free(string.message);    }   return EXIT_SUCCESS;   }   /* 以上程序可以在任意一款支持ANSI C的编译器上编译通过 */   /* 直接复制粘贴,请删除多余的格,并调整格式,否则可能有编译错误 */   /* 在linux下编译,要添加链接库,命令如:gcc -o md5 md5.c -lm */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

良月柒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值