spring hibernate encrypted password
In this section, you will learn about encrypted password in spring hibernate.
In the below example, we will save the password in the encrypted format(md5).
EXAMPLE
The project structure is given below :
The jar files used are given below :
The SQL query used to create user table is given below :
CREATE TABLE `user` ( `user_id` bigint(11) NOT NULL auto_increment, `user_name` varchar(100) default NULL, `user_email` varchar(100) default NULL, `password` varchar(100) NOT NULL, `gender` varchar(1) default NULL, `phone_no` varchar(30) default NULL, `address` text, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
CODE
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringHibernateEncryptedPassword</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/user/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:property-placeholder location="classpath:jdbc.properties" /> <context:component-scan base-package="net.roseindia" /> <tx:annotation-driven transaction-manager="hibernateTransactionManager" /> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${database.driver}" /> <property name="url" value="${database.url}" /> <property name="username" value="${database.user}" /> <property name="password" value="${database.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>net.roseindia.model.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> </props> </property> </bean> <bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans>
jdbc.properties
database.driver=com.mysql.jdbc.Driver database.url=jdbc:mysql://192.168.10.13/onlineexamination_spring database.user=root database.password=root hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true
Encryption.java
package net.roseindia.Utils; import java.math.BigInteger; import java.security.MessageDigest; public class Encryption { public static String encrypt(String source) { String md5 = null; try { MessageDigest mdEnc = MessageDigest.getInstance("MD5"); // Encryption algorithm mdEnc.update(source.getBytes(), 0, source.length()); md5 = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted string } catch (Exception ex) { return null; } return md5; } }
User.java
package net.roseindia.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "user") public class User { @Id @GeneratedValue @Column(name = "user_id") private Long userId; @Column(name = "user_name") private String userName; @Column(name = "user_email") private String userEmail; @Column(name = "password") private String password; @Column(name = "gender") private String userGender; @Column(name = "phone_no") private String phoneNo; @Column(name = "address") private String address; public void setUserId(Long userId) { this.userId = userId; } public Long getUserId() { return userId; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUserEmail() { return userEmail; } public void setUserName(String userName) { this.userName = userName; } public String getUserName() { return userName; } public void setPassword(String password) { this.password = password; } public String getPassword() { return password; } public void setUserGender(String userGender) { this.userGender = userGender; } public String getUserGender() { return userGender; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getPhoneNo() { return phoneNo; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } }
LoginDao.java
package net.roseindia.dao; import java.util.List; import net.roseindia.model.User; public interface LoginDao { public List<User> validateLogin(String user, String password); public void saveUser(User user); }
LoginDaoImpl.java
package net.roseindia.dao; import java.util.List; import net.roseindia.model.User; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository("loginDao") public class LoginDaoImpl implements LoginDao{ @Autowired private SessionFactory sessionFactory; @Override @Transactional(readOnly = true) public List<User> validateLogin(String user, String password) { return sessionFactory.getCurrentSession().createQuery( "from User where userName=:user and password=:password") .setString("user", user).setString("password",password).list(); } @Override @Transactional public void saveUser(User user) { sessionFactory.getCurrentSession().saveOrUpdate(user); } }
LoginService.java
package net.roseindia.service; import java.util.List; import net.roseindia.model.User; public interface LoginService { public List<User> validateLogin(String user,String password); public void saveUser(User user); }
LoginServiceImpl.java
package net.roseindia.service; import java.util.List; import net.roseindia.dao.LoginDao; import net.roseindia.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("loginService") public class LoginServiceImpl implements LoginService{ @Autowired private LoginDao loginDao; @Override public List<User> validateLogin(String user,String password){ return loginDao.validateLogin(user, password); } @Override public void saveUser(User user) { loginDao.saveUser(user); } }
LoginController.java
package net.roseindia.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import net.roseindia.Utils.Encryption; import net.roseindia.model.User; import net.roseindia.service.LoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @Autowired LoginService loginService; @RequestMapping("loginform.html") public String ShowLogin(){ return "login"; } @RequestMapping("login.html") public String LoginAuthentication(HttpServletRequest req){ String username=req.getParameter("user"); String password=req.getParameter("pass"); List<User> loginlist=loginService.validateLogin(username, Encryption.encrypt(password)); if(loginlist.size()>0) { return "loginsuccess"; }else{ return "login"; } } @RequestMapping("logout.html") public String Logout(HttpSession session){ session.invalidate(); return "login"; } @RequestMapping("registrationform.html") public String registrationform(){ return "registration"; } @RequestMapping("registration.html") public String registration(HttpServletRequest req){ String username=req.getParameter("UserName"); String email=req.getParameter("Email"); String password=req.getParameter("Password"); String gender=req.getParameter("gender"); String phoneNumber=req.getParameter("PhoneNumber"); String address=req.getParameter("Address"); // set userForm value to user object. User user = new User(); user.setUserName(username); user.setUserEmail(email); user.setPassword(Encryption.encrypt(password)); user.setUserGender(gender); user.setPhoneNo(phoneNumber); user.setAddress(address); loginService.saveUser(user); return "login"; } }
OUTPUT
First, the welcome page will be as follows :
When you click on REGISTRATION, you will get the following page :
When click on the LOGIN, you will get the following page :
If login credential are correct, you will get the following page :
The encrypted password stored in the user table as follows :