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            @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    }