CRC32 and MD5 algorithms for dummies

跟風遠走 提交于 2019-12-04 16:58:04

The RFC-1321 spec about MD5 also contains a detailed explanation of the algo. The Wiki article about CRC is pretty clear enough.

After all, your major problem is apparently actually the ignorance about the binary system and the bitwise operators. Here are several excellent guides about the binary system and the involved operators:

This must get you started.

Edit: if the actual reason that you wanted to homegrow a MD5 function is that you actually can't seem to find an existing function in Java, then you may find this snippet useful:

/**
 * Generate MD5 hash for the given String.
 * @param string The String to generate the MD5 hash for.
 * @return The 32-char hexadecimal MD5 hash of the given String.
 */
public static String hashMD5(String string) {
    byte[] hash;

    try {
        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException e) {
        // Unexpected exception. "MD5" is just hardcoded and supported.
        throw new RuntimeException("MD5 should be supported?", e);
    } catch (UnsupportedEncodingException e) {
        // Unexpected exception. "UTF-8" is just hardcoded and supported.
        throw new RuntimeException("UTF-8 should be supported?", e);
    }

    StringBuilder hex = new StringBuilder(hash.length * 2);
    for (byte b : hash) {
        if ((b & 0xff) < 0x10) hex.append("0");
        hex.append(Integer.toHexString(b & 0xff));
    }
    return hex.toString();
}

According to DRY you should do

final public class Security {

    synchronized public static String MD5(String msg) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(msg.getBytes());
            byte[] digest = md.digest();
            return new BigInteger(1, digest).toString(16);
        } catch (NoSuchAlgorithmException ex) {
            return "" + msg.hashCode();
        }
    }
}

but if you really wanna figure out what is going on with md5 / sha1 etc, you should probably take a security course, which i tried but failed :( good luck to you!

For those that are interested, the first link is an rfc document on md5. The second is a link to download an implementation for Java:

http://www.ietf.org/rfc/rfc1321.txt

http://www.freevbcode.com/ShowCode.Asp?ID=741

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!