001    /*
002     * SonarQube, open source software quality management tool.
003     * Copyright (C) 2008-2014 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * SonarQube is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * SonarQube is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public License
017     * along with this program; if not, write to the Free Software Foundation,
018     * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019     */
020    
021    package org.sonar.process;
022    
023    import javax.annotation.Nullable;
024    import java.util.HashMap;
025    import java.util.Locale;
026    import java.util.Map;
027    import java.util.regex.Matcher;
028    import java.util.regex.Pattern;
029    
030    /**
031     * @since 3.0
032     */
033    public final class Encryption {
034    
035      private static final String BASE64_ALGORITHM = "b64";
036    
037      private static final String AES_ALGORITHM = "aes";
038      private final AesCipher aesCipher;
039    
040      private final Map<String, Cipher> ciphers = new HashMap<String, Cipher>();
041      private static final Pattern ENCRYPTED_PATTERN = Pattern.compile("\\{(.*?)\\}(.*)");
042    
043      public Encryption(@Nullable String pathToSecretKey) {
044        aesCipher = new AesCipher(pathToSecretKey);
045        ciphers.put(BASE64_ALGORITHM, new Base64Cipher());
046        ciphers.put(AES_ALGORITHM, aesCipher);
047      }
048    
049      public boolean isEncrypted(String value) {
050        return value.indexOf('{') == 0 && value.indexOf('}') > 1;
051      }
052    
053      public String decrypt(String encryptedText) {
054        Matcher matcher = ENCRYPTED_PATTERN.matcher(encryptedText);
055        if (matcher.matches()) {
056          Cipher cipher = ciphers.get(matcher.group(1).toLowerCase(Locale.ENGLISH));
057          if (cipher != null) {
058            return cipher.decrypt(matcher.group(2));
059          }
060        }
061        return encryptedText;
062      }
063    
064    }