Because of the uniqueness and irreversibility of message digest, it is a simple and commonly used encryption method, for example, you can use MD5 to encrypt the user password in your application.
- Package test;
- Import Java.security.MessageDigest;
- /**
- * <p>title: </p>
- * <p>description: </p>
- * <p>copyright:copyright (c) 2003</p>
- * <p>company: </p>
- * @author unascribed
- * @version 1.0
- */
- public class Stringutil {
- Private final static string[] Hexdigits = {
- "0", "1", "2", "3", "4", "5", "6", "7",
- "8", "9", "a", "B", "C", "D", "E", "F"};
- /**
- * Convert byte array to 16 string
- * @param B-byte array
- * @return 16 string
- */
- public static String bytearraytohexstring (byte[] b) {
- StringBuffer RESULTSB = new StringBuffer ();
- for (int i = 0; i < b.length; i++) {
- Resultsb.append (bytetohexstring (b[i));
- }
- return resultsb.tostring ();
- }
- private static String bytetohexstring (Byte b) {
- int n = b;
- if (n < 0)
- n = 256 + N;
- int D1 = N/16;
- int d2 = n% 16;
- return HEXDIGITS[D1] + HEXDIGITS[D2];
- }
- public static string Md5encode (string origin) {
- String resultstring = null;
- try {
- Resultstring=new String (origin);
- MessageDigest MD = messagedigest.getinstance ("MD5");
- Resultstring=bytearraytohexstring (Md.digest (Resultstring.getbytes ()));
- }
- catch (Exception ex) {
- }
- return resultstring;
- }
- public static void Main (string[] args) {
- System.err.println (Md5encode ("a"));
- }
- }
In RFC 1321, the test suite is given to verify that your implementation is correct:
MD5 ("") = d41d8cd98f00b204e9800998ecf8427e
MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661
MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72
MD5 ("message digest") = F96b697d7cb7938d525a2f31aaf161d0
MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b