001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.config.mod;
018
019import static org.apache.juneau.commons.utils.IoUtils.*;
020import static org.apache.juneau.commons.utils.StringUtils.*;
021
022/**
023 * Simply XOR+Base64 encoder for obscuring passwords and other sensitive data in INI config files.
024 *
025 * <p>
026 * This is not intended to be used as strong encryption.
027 *
028 * <h5 class='section'>See Also:</h5><ul>
029 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ModdedEntries">Modded/Encoded Entries</a>
030 * </ul>
031 */
032public class XorEncodeMod extends Mod {
033
034   /** Reusable XOR-ConfigEncoder instance. */
035   public static final XorEncodeMod INSTANCE = new XorEncodeMod();
036
037   private static final String KEY = System.getProperty("org.apache.juneau.config.XorEncoder.key", "nuy7og796Vh6G9O6bG230SHK0cc8QYkH");   // The super-duper-secret key
038
039   /**
040    * Constructor.
041    */
042   public XorEncodeMod() {
043      super('*', null, null, null);
044   }
045
046   @Override
047   public String apply(String value) {
048      var b = value.getBytes(UTF8);
049      for (var i = 0; i < b.length; i++) {
050         var j = i % KEY.length();
051         b[i] = (byte)(b[i] ^ KEY.charAt(j));
052      }
053      return "{" + base64Encode(b) + "}";
054   }
055
056   @Override
057   public boolean isApplied(String value) {
058      return startsWith(value, '{') && endsWith(value, '}');
059   }
060
061   @Override
062   public String remove(String value) {
063      value = value.trim();
064      value = value.substring(1, value.length() - 1);
065      var b = base64Decode(value);
066      for (var i = 0; i < b.length; i++) {
067         var j = i % KEY.length();
068         b[i] = (byte)(b[i] ^ KEY.charAt(j));
069      }
070      return new String(b, UTF8);
071   }
072}