001    /**
002     * Copyright (c) 2000-2013 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.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            public String[] getSupportedAlgorithmTypes() {
033                    return new String[] {PasswordEncryptorUtil.TYPE_BCRYPT};
034            }
035    
036            @Override
037            protected String doEncrypt(
038                    String algorithm, String plainTextPassword, String encryptedPassword) {
039    
040                    String salt = null;
041    
042                    if (Validator.isNull(encryptedPassword)) {
043                            int rounds = _ROUNDS;
044    
045                            Matcher matcher = _pattern.matcher(algorithm);
046    
047                            if (matcher.matches()) {
048                                    rounds = GetterUtil.getInteger(matcher.group(1), rounds);
049                            }
050    
051                            salt = BCrypt.gensalt(rounds);
052                    }
053                    else {
054                            salt = encryptedPassword.substring(0, 29);
055                    }
056    
057                    return BCrypt.hashpw(plainTextPassword, salt);
058            }
059    
060            private static final int _ROUNDS = 10;
061    
062            private static Pattern _pattern = Pattern.compile(
063                    "^BCrypt/([0-9]+)$", Pattern.CASE_INSENSITIVE);
064    
065    }