| Keywords: MD5
Because the message digest is unique and irreversible, it is a simple and common encryption method. For example, you can use MD5 to encrypt the user password in your application.
-
- PackageTest;
-
- ImportJava. 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 the byte array to a hexadecimal string.
-
- * @ Param B byte array
-
- * @ Return hexadecimal string
-
- */
-
-
- Public Static StringBytearraytohexstring (Byte[] B ){
-
- StringbufferResultsb =New Stringbuffer();
-
- For(IntI = 0; I <B.Length; I ++ ){
-
- Resultsb. append (bytetohexstring (B [I]);
-
- }
- ReturnResultsb. tostring ();
-
- }
-
-
- Private Static StringBytetohexstring (ByteB ){
-
- IntN = B;
-
- If(N <0)
-
- N = 256 + N;
-
- IntD1 = N/16;
-
- IntD2 = n % 16;
-
- ReturnHexdigits [D1] + hexdigits [D2];
-
- }
-
- Public Static StringMd5encode (StringOrigin ){
-
- StringResultstring =Null;
-
-
- Try{
-
- Resultstring =New String(Origin );
-
- MessagedigestMD =Messagedigest. Getinstance ("MD5 ");
-
- Resultstring = bytearraytohexstring (Md. Digest (resultstring. getbytes ()));
-
- }
-
- Catch(ExceptionEx ){
-
- }
-
- ReturnResultstring;
-
- }
-
-
- Public Static VoidMain (String[] ARGs ){
-
- System. Err. println (md5encode (""));
-
- }
-
- }
In RFC 1321, test suite is provided to verify whether your implementation is correct:
MD5 ("") = d41d8cd98f00b204e9800998ecf8427e
MD5 ("A") = 0cc175b9c0f1b6a831c399e269772661
MD5 ("ABC") = 900150983cd24fb0d6963f7d28e17f72
MD5 ("Message Digest") = f96b697d7cb7938d525a2f31aaf161d0
MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b
reference: Java security handbook Jamie Jaworski
|