001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.security.pwd;
016    
017    import com.liferay.portal.kernel.security.pwd.PasswordEncryptor;
018    import com.liferay.portal.kernel.security.pwd.PasswordEncryptorUtil;
019    import com.liferay.portal.kernel.util.GetterUtil;
020    import com.liferay.portal.kernel.util.Validator;
021    
022    import java.util.regex.Matcher;
023    import java.util.regex.Pattern;
024    
025    import jodd.util.BCrypt;
026    
027    /**
028     * @author Michael C. Han
029     * @author Tomas Polesovsky
030     */
031    public class BCryptPasswordEncryptor
032            extends BasePasswordEncryptor implements PasswordEncryptor {
033    
034            @Override
035            public String[] getSupportedAlgorithmTypes() {
036                    return new String[] {PasswordEncryptorUtil.TYPE_BCRYPT};
037            }
038    
039            @Override
040            protected String doEncrypt(
041                    String algorithm, String plainTextPassword, String encryptedPassword) {
042    
043                    String salt = null;
044    
045                    if (Validator.isNull(encryptedPassword)) {
046                            int rounds = _ROUNDS;
047    
048                            Matcher matcher = _pattern.matcher(algorithm);
049    
050                            if (matcher.matches()) {
051                                    rounds = GetterUtil.getInteger(matcher.group(1), rounds);
052                            }
053    
054                            salt = BCrypt.gensalt(rounds);
055                    }
056                    else {
057                            salt = encryptedPassword.substring(0, 29);
058                    }
059    
060                    return BCrypt.hashpw(plainTextPassword, salt);
061            }
062    
063            private static final int _ROUNDS = 10;
064    
065            private static final Pattern _pattern = Pattern.compile(
066                    "^BCrypt/([0-9]+)$", Pattern.CASE_INSENSITIVE);
067    
068    }