001/*
002 * JPPF.
003 * Copyright (C) 2005-2019 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.jppf.ssl;
020
021import static org.jppf.utils.StringUtils.maskPassword;
022
023import java.nio.charset.StandardCharsets;
024import java.util.*;
025import java.util.concurrent.Callable;
026
027import org.jppf.utils.FileUtils;
028import org.slf4j.*;
029
030/**
031 * A password source which uses a base64-encoded string stored in a file
032 * @author Laurent Cohen
033 */
034public class PasswordInFile implements Callable<char[]> {
035  /**
036   * Logger for this class.
037   */
038  private static final Logger log = LoggerFactory.getLogger(PasswordInFile.class);
039  /**
040   * Determines whether the debug level is enabled in the log configuration, without the cost of a method call.
041   */
042  private static final boolean debugEnabled = log.isDebugEnabled();
043  /**
044   * Plain text format.
045   */
046  private static final int FORMAT_PLAIN = 1;
047  /**
048   * Plain text format.
049   */
050  private static final int FORMAT_BASE64 = 2;
051  /**
052   * Optional arguments that may be specified in the configuration.
053   */
054  private final String path;
055  /**
056   * 
057   */
058  private final int format;
059
060  /**
061   * Initialize this password source with a plain text password.
062   * @param args the first argument represents the path to a text file.
063   * @throws Exception if any error occurs.
064   */
065  public PasswordInFile(final String... args) throws Exception {
066    if ((args == null) || (args.length == 0)) throw new SSLConfigurationException("missing password file path");
067    this.path = args[0];
068    int fmt = FORMAT_PLAIN;
069    if ((args.length >= 2) && "base64".equalsIgnoreCase(args[1])) fmt = FORMAT_BASE64;
070    this.format = fmt;
071  }
072
073  @Override
074  public char[] call() throws Exception {
075    String pwd = FileUtils.readTextFile(path).trim();
076    if (debugEnabled) log.debug("got '{}' from file {}", maskPassword(pwd), path);
077    if (format == FORMAT_BASE64) {
078      final byte[] bytes = Base64.getDecoder().decode(pwd);
079      if (debugEnabled) log.debug("decoded bytes length={}", bytes.length);
080      pwd = new String(bytes, StandardCharsets.ISO_8859_1);
081    }
082    return pwd.toCharArray();
083  }
084}