Use MD5 to implement small Application Instances

Source: Internet
Author: User

The following is an example of implementing the MD5 small technology. I will show you the encryption principle in the previous article.

First, create a class: mymd5util. java. Please refer to the detailed notes above.

Package COM. zyg. security. MD5; import Java. io. unsupportedencodingexception; import Java. security. messagedigest; import Java. security. nosuchalgorithmexception; import Java. security. securerandom; import Java. util. arrays; public class mymd5util {Private Static final string hex_nums_str = "0123456789 abcdef"; Private Static final integer salt_length = 12; // control the length of the password generation/*** convert the hexadecimal string into a byte array * @ Param hex * @ return */public static byte [] hexstringtobyte (string HEX) {int Len = (hex. length ()/2); byte [] result = new byte [Len]; char [] hexchars = hex. tochararray (); For (INT I = 0; I <Len; I ++) {int Pos = I * 2; Result [I] = (byte) (hex_nums_str.indexof (hexchars [POS]) <4 | hex_nums_str.indexof (hexchars [POS + 1]);} return result ;} /*** convert the specified byte array to a hexadecimal string * @ Param B * @ return */public static string bytetohexstring (byte [] B) {stringbuffer hexstring = new stringbuffer (); For (INT I = 0; I <B. length; I ++) {string hex = integer. tohexstring (B [I] & 0xff); If (hex. length () = 1) {hex = '0' + hex;} hexstring. append (hex. touppercase ();} return hexstring. tostring ();} /*** verify that the password is valid * @ Param password * @ Param passwordindb * @ return * @ throws nosuchalgorithmexception * @ throws unsupportedencodingexception */public static Boolean validpassword (string password, string passwordindb) throws nosuchalgorithmexception, unsupportedencodingexception {// convert the hexadecimal string format password into a byte array byte [] pwdindb = hexstringtobyte (passwordindb ); // declare the salt variable byte [] salt = new byte [salt_length]; // extract the salt from the database's password byte array. arraycopy (pwdindb, 0, salt, 0, salt_length); // create a message digest object messagedigest MD = messagedigest. getinstance ("MD5"); // input the salt data to the message digest object Md. update (SALT); // send the password data to the message digest object Md. update (password. getbytes ("UTF-8"); // generate the message digest byte [] digest = md. digest (); // declare the variable byte [] digestindb = new byte [pwdindb. length-salt_length]; // gets the message digest system of the password in the database. arraycopy (pwdindb, salt_length, digestindb, 0, digestindb. length); // compare whether the message digest generated based on the input password is the same as the message digest in the database if (arrays. equals (Digest, digestindb) {// if the password is correct, return the message "Return true";} if the password is incorrect, return the message "Return false ;}} /*** obtain the encrypted hexadecimal password * @ Param password * @ return * @ throws nosuchalgorithmexception * @ throws unsupportedencodingexception */public static string getencryptedpwd (string password) throws nosuchalgorithmexception, unsupportedencodingexception {// declare the encrypted password array variable byte [] Pwd = NULL; // random number generator securerandom random = new securerandom (); // declare the salt array variable byte [] salt = new byte [salt_length]; // Add the random number to the salt variable random. nextbytes (SALT); // declare message digest object messagedigest MD = NULL; // create message digest MD = messagedigest. getinstance ("MD5"); // input the salt data to the message digest object Md. update (SALT); // send the password data to the message digest object Md. update (password. getbytes ("UTF-8"); // byte array of bytes for obtaining the message digest [] digest = md. digest (); // because salt is stored in the byte array of the password, the length of the byte Pwd = new byte [digest. length + salt_length]; // copy the byte of salt to the first 12 bytes of the generated encrypted password byte array, so that the salt system can be obtained when the password is verified. arraycopy (salt, 0, PWD, 0, salt_length); // copy the message summary to the byte system starting from 13th bytes in the encrypted password byte array. arraycopy (Digest, 0, PWD, salt_length, digest. length); // convert the encrypted password in byte array format to a hexadecimal string format return bytetohexstring (PWD );}}

Create a test class: client. Java, so that MD5 can test the instance we wrote.

Package COM. zyg. security. MD5; import Java. io. unsupportedencodingexception; import Java. security. nosuchalgorithmexception; import Java. util. hashmap; import Java. util. map; public class client {Private Static map users = new hashmap (); public static void main (string [] ARGs) {string username = "zyg "; string Password = "123"; registeruser (username, password); string loginuserid = "zyg"; string Pwd = "123 "; Try {If (loginvalid (loginuserid, PWD) {system. Out. println (" Welcome to log on !!! ");} Else {system. Out. println (" Incorrect password. Please try again !!! ") ;}} Catch (nosuchalgorithmexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (unsupportedencodingexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}/ *** registered user ** @ Param username * @ Param password */public static void registeruser (string username, string password) {string encryptedpwd = NULL; try {encryptedpwd = mymd5util. getencryptedpwd (Pass Word); users. put (username, encryptedpwd);} catch (nosuchalgorithmexception e) {// todo auto-generated Catch Block E. printstacktrace ();} catch (unsupportedencodingexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}/ *** verify logon ** @ Param username * @ Param password * @ return * @ throws unsupportedencodingexception * @ throws nosuchalgorithmexception */public static Boolean Lo Ginvalid (string username, string password) throws nosuchalgorithmexception, unsupportedencodingexception {string pwdindb = (string) users. Get (username); If (null! = Pwdindb) {// return mymd5util. validpassword (password, pwdindb);} else {system. Out. println ("this user does not exist !!! "); Return false ;}}}

Summary: The application of MD5 is still very simple. I believe you will be very clear when you look at the code. One of the two methods is encryption and the other is verification. So long as we know how to call these two methods, as for the principle, it is still a bit difficult to understand. I hope the above will help you understand the principles!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.