001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.security.pwd;
016    
017    import com.liferay.portal.kernel.util.GetterUtil;
018    import com.liferay.portal.kernel.util.Validator;
019    
020    import java.util.regex.Matcher;
021    import java.util.regex.Pattern;
022    
023    import jodd.util.BCrypt;
024    
025    /**
026     * @author Michael C. Han
027     * @author Tomas Polesovsky
028     */
029    public class BCryptPasswordEncryptor
030            extends BasePasswordEncryptor implements PasswordEncryptor {
031    
032            @Override
033            public String[] getSupportedAlgorithmTypes() {
034                    return new String[] {PasswordEncryptorUtil.TYPE_BCRYPT};
035            }
036    
037            @Override
038            protected String doEncrypt(
039                    String algorithm, String plainTextPassword, String encryptedPassword) {
040    
041                    String salt = null;
042    
043                    if (Validator.isNull(encryptedPassword)) {
044                            int rounds = _ROUNDS;
045    
046                            Matcher matcher = _pattern.matcher(algorithm);
047    
048                            if (matcher.matches()) {
049                                    rounds = GetterUtil.getInteger(matcher.group(1), rounds);
050                            }
051    
052                            salt = BCrypt.gensalt(rounds);
053                    }
054                    else {
055                            salt = encryptedPassword.substring(0, 29);
056                    }
057    
058                    return BCrypt.hashpw(plainTextPassword, salt);
059            }
060    
061            private static final int _ROUNDS = 10;
062    
063            private static Pattern _pattern = Pattern.compile(
064                    "^BCrypt/([0-9]+)$", Pattern.CASE_INSENSITIVE);
065    
066    }