Lukas Grygar's

Personal enterprise Java web development blog.

Liferay: How to encrypt (hash) password

In case you’re creating your own registration portlet for Liferay, you need (in case you care about security, and I do) to encrypt password submitted by user. You need PasswordEncryptorUtil.encrypt() method to do that, but for calling this method you need to use PortalClassInvoker.

First of all necessary imports:

1 import com.liferay.portal.kernel.util.ClassResolverUtil;
2 import com.liferay.portal.kernel.util.MethodKey;
3 import com.liferay.portal.kernel.util.PortalClassInvoker;
 1 MethodKey methodKey = new MethodKey(ClassResolverUtil.resolveByPortalClassLoader(""), "encrypt", String.class);
 2 String encryptedPassword = null;
 3 try {
 4 	encryptedPassword = (String) PortalClassInvoker.invoke(false, methodKey, model.getPassword());
 5 } catch (Exception e) {
 6 	log.error("process():: Unexpected exception ", e);
 7 	return error();
 8 }
10 user.setPassword(encryptedPassword);
12 String remoteAddr = BeanUtil.getHttpServletRequest(requestContext).getRemoteAddr();
14 // Liferay stuff to make new user login works
15 user.setPasswordEncrypted(true);
16 user.setPasswordModified(true);
17 user.setPasswordModifiedDate(new Date());
18 user.setPasswordReset(false);
19 user.setModifiedDate(new Date());
20 user.setDigest(null);
21 user.setLoginDate(new Date());
22 user.setLoginIP(remoteAddr);
23 user.setLastLoginDate(new Date());
24 user.setLastLoginIP(remoteAddr);

requestContext is Spring Web Flow’s RequestContext instance and user is Liferay’s User model.

Saved password hash could be found in table USER_ in column PASSWORD_.

This code is tested with Liferay 6.2 CE GA3.

Tags: liferay  liferay-portal 

Share on: Twitter  Facebook  Google+ 

Previous post: Thymeleaf: Tips and Tricks

Next post: Spring Web Flow: Exception does not get logged while using 'transition on-exception'

Related posts: