CRC32 and MD5 algorithms for dummies
I'd like to implement the CRC开发者_Go百科32 and MD5 algorithms on my own but I'm still trying to wrap my head around the different sources I've found on the subject. Could someone helpful point me to a ressource that explains the algorithms in a simple format or post a bullet list of the different steps so I can attempt to fill them in. TIA.
Here's the respective wikipedia pages on each. I understand part of what's being done but bitwise operations are something I have difficulty with. That and mathematics isn't my forte.
http://en.wikipedia.org/wiki/Cyclic_redundancy_check
http://en.wikipedia.org/wiki/MD5The 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:
- Guide: The Binary System
- Wikipedia: Bitwise operation
- Javaranch: Bit Shifting
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
精彩评论