15th Chapter Encryption Algorithm example registration login (Message digest algorithm)

Source: Internet
Author: User
Tags sha256 algorithm

15.1. Principle Steps

    • Registration: When registering, encrypt the user password into the database
    • Login: When logged in, the user password is encrypted using the same algorithm as above, and then compared with the information in the database, if the same, the login

15.2, implementation (here using the SHA256 algorithm, the other digest algorithm md5/sha1/mac similar)

Note: The program here is in my previous write a maven+spring+springmvc+mybatis+velocity integrated article on the changes, concrete framework and database table structure, etc. will no longer wordy, their own reference to the following blog:

Http://www.cnblogs.com/java-zhao/p/5096811.html

Only Java classes are listed here. The entire code structure is as follows:

Usercontroller

 PackageCom.xxx.web;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Controller;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestParam;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportOrg.springframework.web.servlet.ModelAndView;ImportCom.xxx.model.User;ImportCom.xxx.service.UserService, @Controller @requestmapping ("User") Public classUsercontroller {@AutowiredPrivateUserService UserService; @ResponseBody @RequestMapping ("Register")     Public BooleanRegister (@RequestParam ("username") String username, @RequestParam ("Password") String password) {returnuserservice.register (username, password); } @RequestMapping ("Login")     PublicModelandview Login (@RequestParam ("username") String username, @RequestParam ("Password") String password) {User User=userservice.login (username, password); Modelandview Modelandview=NewModelandview (); if(User = =NULL) {Modelandview.addobject ("Message", "the user does not exist or the password is wrong!" Please re-enter "); Modelandview.setviewname ("Error"); }Else{modelandview.addobject ("User", user); Modelandview.setviewname ("UserInfo"); }                returnModelandview; }}
View Code

UserService (This is the main battlefield of the addition and decryption)

 PackageCom.xxx.service;Importjava.io.UnsupportedEncodingException;Importjava.security.NoSuchAlgorithmException;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service;ImportCom.util.encoder.ShaEncoder;ImportCom.xxx.dao.UserDAO;ImportCom.xxx.model.User; @Service Public classUserService {@AutowiredPrivateUserdao Userdao;  Public BooleanRegister (string Username, string password) {User User=NewUser ();        User.setusername (username); Try{user.setpassword (shaencoder.encodeshahex (password));//sha256 Encryption of passwords}Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }        returnuserdao.register (user); }         PublicUser Login (string username, string password) {User User=NULL; Try{User= Userdao.login (username, shaencoder.encodeshahex (password));//sha256 Encryption of passwords}Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }        returnuser; }}
View Code

Userdao

 PackageCom.xxx.dao;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.stereotype.Repository;ImportCom.xxx.mapper.UserMapper;ImportCom.xxx.model.User; @Repository Public classUserdao {@AutowiredPrivateUsermapper Usermapper;  Public BooleanRegister (user user) {returnUsermapper.insertuser (user) ==1?true:false; }         PublicUser Login (string username, string password) {returnusermapper.selectbyusernameandpwd (username, password); }}
View Code

Usermapper

 PackageCom.xxx.mapper;ImportOrg.apache.ibatis.annotations.Insert;ImportOrg.apache.ibatis.annotations.Param;ImportOrg.apache.ibatis.annotations.Result;ImportOrg.apache.ibatis.annotations.Results;ImportOrg.apache.ibatis.annotations.Select;ImportCom.xxx.model.User; Public Interfaceusermapper {@Insert ("INSERT into userinfo (username, password) VALUES (#{username},#{password})")     Public intinsertuser (user user); @Select ("SELECT * from userinfo WHERE username = #{username} and password = #{password}") @Results (value= {@Result (id =true, column = "id", property = "id"), @Result (column= "Username", property = "username"), @Result (column= "Password", property = "Password")})     PublicUser selectbyusernameandpwd (@Param ("username") String username, @Param ("Password") String password);}
View Code

Shaencoder (here based on Commons Codec, the Sha256 tool class implemented by CC)

 PackageCom.util.encoder;Importjava.io.UnsupportedEncodingException;Importjava.security.NoSuchAlgorithmException;Importorg.apache.commons.codec.digest.DigestUtils; Public classShaencoder {Private Static FinalString ENCODING = "UTF-8";  Public StaticString Encodeshahex (String data)throwsnosuchalgorithmexception,unsupportedencodingexception {return NewString (Digestutils.sha256hex (Data.getbytes (ENCODING))); }}
View Code

The code is easy to understand, see the logic yourself, and then test it.

Of course, we can add a bit of salt to the password (that is, a string to the password), and then encrypt the salt-added string, based on the above code. The code is as follows:

 PackageCom.xxx.service;Importjava.io.UnsupportedEncodingException;Importjava.security.NoSuchAlgorithmException;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.stereotype.Service;ImportCom.util.encoder.ShaEncoder;ImportCom.xxx.dao.UserDAO;ImportCom.xxx.model.User; @Service Public classUserService {Private Static FinalString SALT = "Nana";//Salt@AutowiredPrivateUserdao Userdao;  Public BooleanRegister (string Username, string password) {User User=NewUser ();        User.setusername (username); Try{User.setpassword (Shaencoder.encodeshahex (SALT+password));//sha256 encryption of salt-added passwords}Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }        returnuserdao.register (user); }         PublicUser Login (string username, string password) {User User=NULL; Try{User= Userdao.login (username, Shaencoder.encodeshahex (salt+password));//sha256 encryption of salt-added passwords}Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }        returnuser; }}
View Code

Of course, the salt here is a fixed string (which is most common in practice), and we can also use his own name as salt for each logged-in user (so that everyone's salt is different).

15th Chapter Encryption Algorithm example registration login (Message digest algorithm)

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.