001
014
015 package com.liferay.portal.security.pwd;
016
017 import com.liferay.portal.PwdEncryptorException;
018 import com.liferay.portal.kernel.util.ArrayUtil;
019 import com.liferay.portal.kernel.util.Base64;
020 import com.liferay.portal.kernel.util.Digester;
021 import com.liferay.portal.kernel.util.Validator;
022
023 import java.io.UnsupportedEncodingException;
024
025 import java.security.MessageDigest;
026 import java.security.NoSuchAlgorithmException;
027 import java.security.SecureRandom;
028
029 import java.util.Random;
030
031
035 public class SSHAPasswordEncryptor
036 extends BasePasswordEncryptor implements PasswordEncryptor {
037
038 public String[] getSupportedAlgorithmTypes() {
039 return new String[] {PasswordEncryptorUtil.TYPE_SSHA};
040 }
041
042 @Override
043 protected String doEncrypt(
044 String algorithm, String plainTextPassword,
045 String encryptedPassword)
046 throws PwdEncryptorException {
047
048 byte[] saltBytes = getSaltBytes(encryptedPassword);
049
050 try {
051 MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
052
053 byte[] plainTextPasswordBytes = plainTextPassword.getBytes(
054 Digester.ENCODING);
055
056 byte[] messageDigestBytes = messageDigest.digest(
057 ArrayUtil.append(plainTextPasswordBytes, saltBytes));
058
059 return Base64.encode(
060 ArrayUtil.append(messageDigestBytes, saltBytes));
061 }
062 catch (NoSuchAlgorithmException nsae) {
063 throw new PwdEncryptorException(nsae.getMessage(), nsae);
064 }
065 catch (UnsupportedEncodingException uee) {
066 throw new PwdEncryptorException(uee.getMessage(), uee);
067 }
068 }
069
070 protected byte[] getSaltBytes(String encryptedPassword)
071 throws PwdEncryptorException {
072
073 byte[] saltBytes = new byte[8];
074
075 if (Validator.isNull(encryptedPassword)) {
076 Random random = new SecureRandom();
077
078 random.nextBytes(saltBytes);
079 }
080 else {
081 try {
082 byte[] encryptedPasswordBytes = Base64.decode(
083 encryptedPassword);
084
085 System.arraycopy(
086 encryptedPasswordBytes, encryptedPasswordBytes.length - 8,
087 saltBytes, 0, saltBytes.length);
088 }
089 catch (Exception e) {
090 throw new PwdEncryptorException(
091 "Unable to extract salt from encrypted password " +
092 e.getMessage(),
093 e);
094 }
095 }
096
097 return saltBytes;
098 }
099
100 }