Files
CipherStreamJava/src/main/java/com/mattrixwv/cipherstream/polysubstitution/Trifid.java

688 lines
22 KiB
Java

//CipherStreamJava/src/main/java/com/mattrixwv/cipherstream/polysubstitution/Trifid.java
//Mattrixwv
// Created: 03-03-22
//Modified: 08-11-24
/*
Copyright (C) 2024 Mattrixwv
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.mattrixwv.cipherstream.polysubstitution;
import java.util.ArrayList;
import java.util.StringJoiner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mattrixwv.cipherstream.exceptions.InvalidBaseException;
import com.mattrixwv.cipherstream.exceptions.InvalidCharacterException;
import com.mattrixwv.cipherstream.exceptions.InvalidInputException;
import com.mattrixwv.cipherstream.exceptions.InvalidKeywordException;
/**
* The {@code Trifid} class implements the Trifid cipher, a polyalphabetic substitution cipher
* that uses a 3x3x3 grid to encode and decode messages.
*/
public class Trifid{
private static final Logger logger = LoggerFactory.getLogger(Trifid.class);
/** A class representing the location of a character in the grid */
protected class CharLocation{
/** The x location in the grid */
protected int x;
/** The y location in the grid */
protected int y;
/** The z location in the grid */
protected int z;
/**
* Constructs a CharLocation with the specified x and y coordinates.
*
* @param x the x-coordinate of the character's location
* @param y the y-coordinate of the character's location
* @param z the z-coordinate of the character's location
*/
public CharLocation(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
/**
* Returns the x-coordinate of the character's location.
*
* @return the x-coordinate
*/
public int getX(){
return x;
}
/**
* Returns the y-coordinate of the character's location.
*
* @return the y-coordinate
*/
public int getY(){
return y;
}
/**
* Returns the z-coordinate of the character's location.
*
* @return the z-coordinate
*/
public int getZ(){
return z;
}
/**
* Prints out the location in a human readable format
*/
public String toString(){
return "[" + (z + 1) + ", " + (x + 1) + ", " + (y + 1) + "]";
}
}
//?Fields
/** The message that needs to be encoded/decoded */
protected String inputString;
/** The encoded/decoded message */
protected String outputString;
/** The keyword used to create the grid */
protected String keyword;
/** The size of the groups used to break up the input */
protected int groupSize;
/** The grid used to encode/decode the message */
protected char[][][] grid;
/** The character added to the alphabet to meet the 27 character requirement */
protected char fillIn;
//?Settings
/** Persist capitals in the output string */
protected boolean preserveCapitals;
/** Persist whitespace in the output string */
protected boolean preserveWhitespace;
/** Persist symbols in the output string */
protected boolean preserveSymbols;
/**
* Sets the fill-in character used to complete the 27-character requirement for the grid.
*
* @param fillIn the fill-in character
* @throws InvalidCharacterException if the fill-in character is not a printable non-letter character
*/
protected void setFillIn(char fillIn) throws InvalidCharacterException{
//Make sure the character is a printing character
if((fillIn < ' ') || (fillIn > '~')){
throw new InvalidCharacterException("Fill in character must be a printable character");
}
//Make sure the character is not a letter
if(Character.isAlphabetic(fillIn)){
throw new InvalidCharacterException("Fill in must not be a non-letter character");
}
logger.debug("Setting fill in {}", fillIn);
//Save the fillIn character
this.fillIn = fillIn;
}
/**
* Processes the keyword to generate the 3D grid. The keyword is sanitized to include
* only capital letters and the fill-in character.
*
* @param keyword the keyword used to create the grid
* @throws InvalidKeywordException if the keyword is invalid
*/
protected void setKeyword(String keyword) throws InvalidKeywordException{
//Ensure the keyword isn't null
if(keyword == null){
throw new InvalidKeywordException("Keyword cannot be null");
}
logger.debug("Original keyword {}", keyword);
//Change everything to uppercase
logger.debug("Removing case");
keyword = keyword.toUpperCase();
//Remove everything except capital letters
logger.debug("Removing all invalid characters");
keyword = keyword.replaceAll("[^A-Z" + fillIn + "]", "");
//Add all letters in the alphabet and fillIn to the key
logger.debug("Appending entire alphabet to keyword");
keyword += "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + fillIn;
//Remove all duplicate characters
logger.debug("Removing duplicate characters");
StringBuilder uniqueKey = new StringBuilder();
keyword.chars().distinct().forEach(c -> uniqueKey.append((char)c));
this.keyword = uniqueKey.toString();
logger.debug("Cleaned keyword {}", this.keyword);
//Create the grid from the sanitized keyword
createGrid();
}
/**
* Creates the 3D grid from the processed keyword.
*/
protected void createGrid(){
logger.debug("Creating grid from keyword");
for(int layerCnt = 0;layerCnt < grid.length;++layerCnt){
for(int rowCnt = 0;rowCnt < grid[layerCnt].length;++rowCnt){
for(int colCnt = 0;colCnt < grid[layerCnt][rowCnt].length;++colCnt){
int loc = 0;
loc = colCnt + (rowCnt * grid[layerCnt][rowCnt].length) + (layerCnt * grid[layerCnt].length * grid[layerCnt][rowCnt].length);
grid[layerCnt][rowCnt][colCnt] = keyword.charAt(loc);
}
}
}
logger.debug("Completed grid\n{}", getGrid());
}
/**
* Sets the group size used for encoding and decoding the input string.
*
* @param groupSize the group size
* @throws InvalidBaseException if the group size is less than or equal to zero
*/
protected void setGroupSize(int groupSize) throws InvalidBaseException{
if(groupSize <= 0){
throw new InvalidBaseException("Group size must be > 0");
}
logger.debug("Setting group size");
this.groupSize = groupSize;
}
/**
* Prepares the input string for encoding or decoding by applying preservation settings
* and validating the input.
*
* @param inputString the input string to be processed
* @throws InvalidInputException if the input string is invalid
*/
protected void setInputString(String inputString) throws InvalidInputException{
//Ensure the input string isn't null
if(inputString == null){
throw new InvalidInputException("Input cannot be null");
}
logger.debug("Original input string '{}'", inputString);
//Apply removal options
if(!preserveCapitals){
logger.debug("Removing case");
inputString = inputString.toUpperCase();
}
if(!preserveWhitespace){
if(Character.isWhitespace(fillIn)){
throw new InvalidInputException("If fillIn is whitespace, whitespace must be preserved");
}
logger.debug("Removing whitespace");
inputString = inputString.replaceAll("\\s", "");
}
if(!preserveSymbols){
logger.debug("Removing symbols");
inputString = inputString.replaceAll("[^a-zA-Z" + fillIn + "\\s]", "");
}
//Save the string
logger.debug("Cleaned input string '{}'", inputString);
this.inputString = inputString;
//Ensure the string isn't blank
if(this.inputString.isBlank()){
throw new InvalidInputException("Input must contain at least 1 letter");
}
}
/**
* Returns the input string with only valid letters and fill-in characters.
*
* @return the cleaned input string
*/
protected String getCleanInputString(){
logger.debug("Cleaning input string for encoding");
return inputString.toUpperCase().replaceAll("[^A-Z" + fillIn + "]", "");
}
/**
* Finds the location of a given character in the 3D grid.
*
* @param letter the character to find
* @return the location of the character
* @throws InvalidCharacterException if the character is not found in the grid
*/
protected CharLocation findChar(char letter) throws InvalidCharacterException{
logger.debug("Finding character {} in grid", letter);
for(int layer = 0;layer < grid.length;++layer){
for(int row = 0;row < grid[layer].length;++row){
for(int col = 0;col < grid[layer][row].length;++col){
if(grid[layer][row][col] == letter){
logger.debug("Found at {} {} {}", layer, row, col);
return new CharLocation(row, col, layer);
}
}
}
}
//If it was not found something went wrong
throw new InvalidCharacterException("The character '" + letter + "' was not found in the grid");
}
/**
* Retrieves the character at the specified location in the 3D grid.
*
* @param location the location of the character
* @return the character at the specified location
* @throws InvalidCharacterException if the location is out of bounds
*/
protected char getChar(CharLocation location) throws InvalidCharacterException{
if(location.getX() > 2){
throw new InvalidCharacterException("x cannot be larget than 2");
}
if(location.getY() > 2){
throw new InvalidCharacterException("y cannot be larget than 2");
}
if(location.getZ() > 2){
throw new InvalidCharacterException("z cannot be larget than 2");
}
logger.debug("Getting character at {} {} {}", location.getZ(), location.getX(), location.getY());
return grid[location.getZ()][location.getX()][location.getY()];
}
/**
* Formats the output string according to the preservation settings.
*
* @param outputString the output string to format
*/
protected void formatOutput(String outputString){
logger.debug("Formatting output");
//Keep track of where you are in the output
int outputCnt = 0;
StringBuilder output = new StringBuilder();
//Check every character in the input and apply the correct rules to the output
for(char ch : inputString.toCharArray()){
logger.debug("Working character {}", ch);
if(Character.isUpperCase(ch)){
logger.debug("Formatting uppercase");
output.append(Character.toUpperCase(outputString.charAt(outputCnt++)));
}
else if(Character.isLowerCase(ch)){
logger.debug("Formatting lowercase");
output.append(Character.toLowerCase(outputString.charAt(outputCnt++)));
}
else if(ch == fillIn){
logger.debug("Adding fillIn");
if(preserveCapitals){
output.append(Character.toLowerCase(outputString.charAt(outputCnt++)));
}
else{
output.append(Character.toUpperCase(outputString.charAt(outputCnt++)));
}
}
else{
logger.debug("Appending symbol");
output.append(ch);
}
}
//Save the output
this.outputString = output.toString();
logger.debug("Formatted output '{}'", this.outputString);
}
/**
* Encodes the input string using the Trifid cipher.
*
* @throws InvalidCharacterException if an invalid character is encountered
*/
protected void encode() throws InvalidCharacterException{
logger.debug("Encoding");
//Step through every element in the sanitized inputString encoding the letters
logger.debug("Converting letters to coordinates");
ArrayList<CharLocation> locations = new ArrayList<>();
for(char ch : getCleanInputString().toCharArray()){
//Get the location of the char in the grid
CharLocation location = findChar(ch);
locations.add(location);
}
//Split the locations up by group
logger.debug("Splitting locations into groups");
int numGroups = (int)Math.ceil((double)inputString.length() / (double)groupSize);
ArrayList<ArrayList<CharLocation>> groups = new ArrayList<>(numGroups);
for(int cnt = 0;cnt < numGroups;++cnt){
groups.add(new ArrayList<>());
}
int groupCnt = -1;
for(int locCnt = 0;locCnt < locations.size();++locCnt){
//If you've reached the end of the group move to the next one
if((locCnt % groupSize) == 0){
++groupCnt;
}
groups.get(groupCnt).add(locations.get(locCnt));
}
//Split the coordinates into rows
logger.debug("Splitting groups into rows");
ArrayList<Integer> coordinates = new ArrayList<>(locations.size() * 3);
for(ArrayList<CharLocation> group : groups){
//Split the coordinates up into 3 rows
ArrayList<Integer> layers = new ArrayList<>(group.size());
ArrayList<Integer> rows = new ArrayList<>(group.size());
ArrayList<Integer> cols = new ArrayList<>(group.size());
for(CharLocation loc : group){
layers.add(loc.getZ());
rows.add(loc.getX());
cols.add(loc.getY());
}
coordinates.addAll(layers);
coordinates.addAll(rows);
coordinates.addAll(cols);
}
//Create new locations from the rows of coordinates
logger.debug("Converting split locations into new locations");
ArrayList<CharLocation> newLocations = new ArrayList<>(locations.size());
for(int cnt = 0;cnt < coordinates.size();){
int z = coordinates.get(cnt++);
int x = coordinates.get(cnt++);
int y = coordinates.get(cnt++);
newLocations.add(new CharLocation(x, y, z));
}
//Get the new letters from the grid
logger.debug("Converting new locations into characters");
StringBuilder output = new StringBuilder();
for(CharLocation loc : newLocations){
output.append(getChar(loc));
}
//Format the output
formatOutput(output.toString());
}
/**
* Decodes the input string using the Trifid cipher.
*
* @throws InvalidCharacterException if an invalid character is encountered
*/
protected void decode() throws InvalidCharacterException{
logger.debug("Decoding");
//Step through every element in the sanitized inputString encoding the letters
logger.debug("Converting letters to coordinates");
ArrayList<CharLocation> locations = new ArrayList<>();
for(char ch : getCleanInputString().toCharArray()){
//Get the location of the char in the grid
CharLocation location = findChar(ch);
locations.add(location);
}
//Split the locations up by group
logger.debug("Splitting locations into groups");
int numGroups = (int)Math.ceil((double)inputString.length() / (double)groupSize);
ArrayList<ArrayList<CharLocation>> groups = new ArrayList<>(numGroups);
for(int cnt = 0;cnt < numGroups;++cnt){
groups.add(new ArrayList<>());
}
int groupCnt = -1;
for(int locCnt = 0;locCnt < locations.size();++locCnt){
//If you've reached the end of the group move to the next one
if((locCnt % groupSize) == 0){
++groupCnt;
}
groups.get(groupCnt).add(locations.get(locCnt));
}
//Split the coordinates into rows by group and create the original grid locations
logger.debug("Putting locations into rows");
ArrayList<CharLocation> originalLocations = new ArrayList<>(locations.size());
for(ArrayList<CharLocation> group : groups){
//Read all of the coordinates from the group out into a row
ArrayList<Integer> coordinates = new ArrayList<>(group.size() * 3);
for(CharLocation loc : group){
coordinates.add(loc.getZ());
coordinates.add(loc.getX());
coordinates.add(loc.getY());
}
//Read out the coordinates into new locations
logger.debug("Converting locations into new locations");
ArrayList<CharLocation> originalGroup = new ArrayList<>(group.size());
for(int cnt = 0;cnt < group.size();++cnt){
originalGroup.add(new CharLocation(0, 0, 0));
}
int coordinateCnt = 0;
for(CharLocation loc : originalGroup){
loc.z = coordinates.get(coordinateCnt++);
}
for(CharLocation loc : originalGroup){
loc.x = coordinates.get(coordinateCnt++);
}
for(CharLocation loc : originalGroup){
loc.y = coordinates.get(coordinateCnt++);
}
originalLocations.addAll(originalGroup);
}
//Get the original letters from the grid
logger.debug("Converting new locations into letters");
StringBuilder output = new StringBuilder();
for(CharLocation loc : originalLocations){
output.append(getChar(loc));
}
//Format the output
formatOutput(output.toString());
}
//?Constructor
/**
* Constructs a Trifid object with default settings.
*/
public Trifid() throws InvalidCharacterException{
preserveCapitals = false;
preserveWhitespace = false;
preserveSymbols = false;
setFillIn('+');
reset();
}
/**
* Constructs a Trifid object with default settings.
*
* @param preserveCapitals whether to preserve capital letters
* @param preserveWhitespace whether to preserve whitespace
* @param preserveSymbols whether to preserve symbols
*/
public Trifid(boolean preserveCapitals, boolean preserveWhitespace, boolean preserveSymbols) throws InvalidCharacterException{
this.preserveCapitals = preserveCapitals;
this.preserveWhitespace = preserveWhitespace;
this.preserveSymbols = preserveSymbols;
setFillIn('+');
reset();
}
/**
* Constructs a Trifid object with default settings.
*
* @param preserveCapitals whether to preserve capital letters
* @param preserveWhitespace whether to preserve whitespace
* @param preserveSymbols whether to preserve symbols
* @param fillIn the character to use for fill-in characters
* @throws InvalidCharacterException if the fill-in character is invalid
*/
public Trifid(boolean preserveCapitals, boolean preserveWhitespace, boolean preserveSymbols, char fillIn) throws InvalidCharacterException{
this.preserveCapitals = preserveCapitals;
this.preserveWhitespace = preserveWhitespace;
this.preserveSymbols = preserveSymbols;
setFillIn(fillIn);
reset();
}
/**
* Encodes the specified input string using the provided keyword and group size.
*
* @param keyword the keyword used for encoding
* @param inputString the input string to encode
* @return the encoded string
* @throws InvalidBaseException if the group size is invalid
* @throws InvalidKeywordException if the keyword is invalid
* @throws InvalidInputException if the input string is invalid
* @throws InvalidCharacterException if an invalid character is encountered
*/
public String encode(String keyword, String inputString) throws InvalidBaseException, InvalidKeywordException, InvalidInputException, InvalidCharacterException{
return encode(keyword, inputString.length(), inputString);
}
/**
* Encodes the specified input string using the provided keyword and group size.
*
* @param keyword the keyword used for encoding
* @param groupSize the size of groups
* @param inputString the input string to encode
* @return the encoded string
* @throws InvalidBaseException if the group size is invalid
* @throws InvalidKeywordException if the keyword is invalid
* @throws InvalidInputException if the input string is invalid
* @throws InvalidCharacterException if an invalid character is encountered
*/
public String encode(String keyword, int groupSize, String inputString) throws InvalidBaseException, InvalidKeywordException, InvalidInputException, InvalidCharacterException{
//Set the parameters
reset();
setKeyword(keyword);
setGroupSize(groupSize);
setInputString(inputString);
//Encode and return the message
encode();
return outputString;
}
/**
* Decodes the specified input string using the provided keyword and group size.
*
* @param keyword the keyword used for decoding
* @param inputString the input string to decode
* @return the decoded string
* @throws InvalidBaseException if the group size is invalid
* @throws InvalidKeywordException if the keyword is invalid
* @throws InvalidInputException if the input string is invalid
* @throws InvalidCharacterException if an invalid character is encountered
*/
public String decode(String keyword, String inputString) throws InvalidBaseException, InvalidKeywordException, InvalidInputException, InvalidCharacterException{
return decode(keyword, inputString.length(), inputString);
}
/**
* Decodes the specified input string using the provided keyword and group size.
*
* @param keyword the keyword used for decoding
* @param groupSize the size of groups
* @param inputString the input string to decode
* @return the decoded string
* @throws InvalidBaseException if the group size is invalid
* @throws InvalidKeywordException if the keyword is invalid
* @throws InvalidInputException if the input string is invalid
* @throws InvalidCharacterException if an invalid character is encountered
*/
public String decode(String keyword, int groupSize, String inputString) throws InvalidBaseException, InvalidKeywordException, InvalidInputException, InvalidCharacterException{
//Set the parameters
reset();
setKeyword(keyword);
setGroupSize(groupSize);
setInputString(inputString);
//Decode and return the message
decode();
return outputString;
}
/**
* Resets all internal variables to their default values.
*/
public void reset(){
logger.debug("Resetting fields");
inputString = "";
outputString = "";
keyword = "";
groupSize = Integer.MAX_VALUE;
grid = new char[3][3][3];
}
//?Getters
/**
* Returns the current input string.
*
* @return the input string
*/
public String getInputString(){
return inputString;
}
/**
* Returns the current output string.
*
* @return the output string
*/
public String getOutputString(){
return outputString;
}
/**
* Returns the current keyword.
*
* @return the keyword
*/
public String getKeyword(){
return keyword;
}
/**
* Returns the current group size.
*
* @return the group size
*/
public int getGroupSize(){
return groupSize;
}
/**
* Returns the current fill-in character.
*
* @return the fill-in character
*/
public char getFillIn(){
return fillIn;
}
/**
* Returns a string representation of the 3D grid.
*
* @return the grid as a string
*/
public String getGrid(){
logger.debug("Creating string from grid");
StringJoiner layers = new StringJoiner("\n\n");
for(char[][] layer : grid){
StringJoiner gridJoiner = new StringJoiner("\n");
for(char[] row : layer){
StringJoiner rowJoiner = new StringJoiner(" ", "[", "]");
for(char ch : row){
rowJoiner.add(Character.toString(ch));
}
gridJoiner.add(rowJoiner.toString());
}
layers.add(gridJoiner.toString());
}
return layers.toString();
}
}