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.*;
021import static org.apache.juneau.commons.utils.SystemUtils.*;
022
023/**
024 * Simply XOR+Base64 encoder for obscuring passwords and other sensitive data in INI config files.
025 *
026 * <p>
027 * This is not intended to be used as strong encryption.
028 *
029 * <h5 class='section'>See Also:</h5><ul>
030 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ModdedEntries">Modded/Encoded Entries</a>
031 * </ul>
032 */
033public class XorEncodeMod extends Mod {
034
035   /** Reusable XOR-ConfigEncoder instance. */
036   public static final XorEncodeMod INSTANCE = new XorEncodeMod();
037
038   private static final String KEY = env("org.apache.juneau.marshall.config.XorEncoder.key", "nuy7og796Vh6G9O6bG230SHK0cc8QYkH");   // The super-duper-secret key
039
040   /**
041    * Constructor.
042    */
043   public XorEncodeMod() {
044      super('*', null, null, null);
045   }
046
047   @Override
048   public String apply(String value) {
049      var b = value.getBytes(UTF8);
050      for (var i = 0; i < b.length; i++) {
051         var j = i % KEY.length();
052         b[i] = (byte)(b[i] ^ KEY.charAt(j));
053      }
054      return "{" + base64Encode(b) + "}";
055   }
056
057   @Override
058   public boolean isApplied(String value) {
059      return startsWith(value, '{') && endsWith(value, '}');
060   }
061
062   @Override
063   public String remove(String value) {
064      value = value.trim();
065      value = value.substring(1, value.length() - 1);
066      var b = base64Decode(value);
067      for (var i = 0; i < b.length; i++) {
068         var j = i % KEY.length();
069         b[i] = (byte)(b[i] ^ KEY.charAt(j));
070      }
071      return new String(b, UTF8);
072   }
073}