# SymmetricEncryption.java

    /*
    ** Module   : SymmetricEncryption.java
    ** Abstract : A symmetric algorithm used for making strings (passwords) not so easy readable.
    **
    ** Copyright (c) 2015-2023, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------Description---------------------------------
    ** 001 OM  20151113 Initial implementation.
    ** 002 EVL 20160406 Javadoc fix.
    ** 003 GBB 20230512 Logging methods replaced by CentralLogger/ConversionStatus.
    */
    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.security;

    import com.goldencode.p2j.util.logging.*;

    /**
     * Utility class that mimics the symmetric encryption of Progress' {@code genpassword} utility.
     * The algorithm used is quite naive, each byte of the message is XOR-ed with the corresponding
     * byte of a <i>secret</i> key. If the key is shorter, its pointer is restarted from the beginning
     * and the process continues until the entire message is processed. Evidently, applying this
     * algorithm twice using the same password/key we obtain the original message:
     *                          <pre>(a XOR b) XOR b = a</pre>
     * <p>
     * The difference between the format of encrypted and plain message occurs because the encrypted
     * message, in the initial form can contain non-printable ascii codes. So it is converted to a
     * hexadecimal representation, which uses twice as many characters but they are limited to
     * hexadecimal digits.
     */
    public class SymmetricEncryption
    {
       /** The key used for encrypting and decrypting the message. */
       private static final String SYM_KEY = "PROGRESS";

       /** Logger */
       private static final CentralLogger LOG = CentralLogger.get(SymmetricEncryption.class);

       /**
        * The command-line utility. The syntax is:
        * <pre>
        *    &gt; java SymmetricEncryption plain [coded]
        * </pre>
        * If only {@code plain} is provided, then the argument is encrypted with symmetric algorithm
        * and the result is printed to STDOUT.
        * <p>
        * If the 2nd parameter is also provided ({@code coded}) then it is used for verification
        * (against the encrypted {@code plain}). On success, the application returns normally without
        * printing anything. Otherwise a message is printed to STDERR and -2 is returned to OS.
        *
        * @param   args
        *          The parameters passed in by OS.
        */
       public static void main(String[] args)
       {
          if (args.length == 0)
          {
             LOG.severe("At least a parameter must be provided.");
             System.exit(-1);
          }

          if (args.length == 1)
          {
             LOG.info(encrypt(args[0]));
             return;
          }

          if (args.length == 2)
          {
             if (encrypt(args[0]).equalsIgnoreCase(args[1]))
             {
                // 1st argument encrypted equals 2nd one
                return;
             }

             // if testing fails, return an error level to OS
             LOG.severe("The plain and coded do not match.");
             System.exit(-2);
          }

          // max 2 parameter may be passed in
          LOG.severe("Too many parameters.");
          System.exit(-3);
       }

       /**
        * Encryption method. The symmetric encryption is performed on input string and the result is
        * returned. Because the intermediary code is not usually printable, the final result is
        * passed through a hex encoder.
        *
        * @param   plainMessage
        *          The message to be encoded in plain ASCII.
        *
        * @return  The encrypted message. It is always twice as long and the characters are
        *          hexadecimal digits.
        */
       public static String encrypt(String plainMessage)
       {
          if (plainMessage == null || plainMessage.length() == 0)
          {
             return plainMessage;
          }
          return toHexString(process(SYM_KEY, plainMessage.getBytes()));
       }

       /**
        * Decryption method. The symmetric crypt algorithm is applied again so the original message
        * is obtained.
        *
        * @param   codedMessage
        *          The encoded message. Since it is hex-encoded, its size must be even and each
        *          character a hexadecimal digit.
        *
        * @return  The original message.
        */
       public static String decrypt(String codedMessage)
       {
          if (codedMessage == null || codedMessage.length() == 0)
          {
             return codedMessage;
          }
          return new String(process(SYM_KEY, asBytes(codedMessage)));
       }

       /**
        * Utility method. Converts a byte array to its ASCII printable string representation using
        * hexadecimal encoding of each byte.
        *
        * @param   code
        *          An array of bytes to be processed. In this case this is the encrypted message.
        *
        * @return  Hexadecimal representation of the {@code code}.
        */
       private static String toHexString(byte[] code)
       {
          // allocate the exact space for hexadecimal representation of the code array
          StringBuilder sb = new StringBuilder(code.length * 2);

          for (byte aByte : code)
          {
             // insert a leading 0 to keep the 2 digits per byte for 1 digit representation
             if ((aByte & 255) < 16)
             {
                sb.append("0");
             }

             sb.append(Long.toString((long) (aByte & 255), 16));
          }

          return sb.toString();
       }

       /**
        * Converts a hexadecimal representation to initial bytes array.
        *
        * @param   hexString
        *          The input string. Must have an even length and all characters be valid hexadecimal
        *          digits.
        *
        * @return  The original byte array.
        */
       private static byte[] asBytes(String hexString)
       {
          int len = hexString.length();
          byte[] bytes = new byte[((len & 1) == 0) ? (len / 2) : len];

          int i = 0;

          for (int j = 0; i < len; ++j)
          {
             // take 2 hex digits and generate a single byte
             short var7 = Short.parseShort(hexString.substring(i, i + 2), 16);
             bytes[j] = (byte)(var7 & 255);
             i += 2;
          }

          return bytes;
       }

       /**
        * This is the core algorithm. It is applied for both encrypting and decrypting the message.
        * The {@code passwd} is transformed into a byte array, then the message is linearly processed:
        * each byte is XOR-ed with the corresponding byte from the key.
        *
        * @param   passwd
        *          The password / key used for coding.
        * @param   data
        *          The data to be processed.
        *
        * @return  The processed array.
        */
       private static byte[] process(String passwd, byte[] data)
       {
          byte[] kData = passwd.getBytes();
          byte[] pData = new byte[data.length];

          for (int i = 0, j = 0; i < data.length; ++j)
          {
             if (j >= kData.length)
             {
                // if we got to end of key, we roll it back from the beginning
                j = 0;
             }

             pData[i] = (byte)(data[i] ^ kData[j]);
             ++i;
          }

          return pData;
       }
    }