476 lines
16 KiB
Java
476 lines
16 KiB
Java
//CipherStreamJava/src/main/java/com/mattrixwv/CipherStreamJava/polySubstitution/Trifid.java
|
|
//Mattrixwv
|
|
// Created: 03-03-22
|
|
//Modified: 03-03-22
|
|
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.InvalidCharacterException;
|
|
import com.mattrixwv.cipherstream.exceptions.InvalidInputException;
|
|
import com.mattrixwv.cipherstream.exceptions.InvalidKeywordException;
|
|
import com.mattrixwv.cipherstream.exceptions.InvalidBaseException;
|
|
|
|
|
|
public class Trifid{
|
|
private static final Logger logger = LoggerFactory.getLogger(Trifid.class);
|
|
|
|
//A class representing the location of a character in the grid
|
|
private class CharLocation{
|
|
private int x;
|
|
private int y;
|
|
private int z;
|
|
public CharLocation(int x, int y, int z){
|
|
this.x = x;
|
|
this.y = y;
|
|
this.z = z;
|
|
}
|
|
public int getX(){
|
|
return x;
|
|
}
|
|
public int getY(){
|
|
return y;
|
|
}
|
|
public int getZ(){
|
|
return z;
|
|
}
|
|
public String toString(){
|
|
return "[" + (z + 1) + ", " + (x + 1) + ", " + (y + 1) + "]";
|
|
}
|
|
}
|
|
|
|
//Fields
|
|
private String inputString; //The message that needs to be encoded/decoded
|
|
private String outputString; //The encoded/decoded message
|
|
private String keyword; //The keyword used to create the grid
|
|
private int groupSize; //The size of the groups used to break up the input
|
|
private char[][][] grid; //The grid used to encode/decode the message
|
|
private char fillIn; //The character added to the alphabet to meet the 27 character requirement
|
|
private boolean preserveCapitals; //Persist capitals in the output string
|
|
private boolean preserveWhitespace; //Persist whitespace in the output string
|
|
private boolean preserveSymbols; //Persist symbols in the output string
|
|
|
|
//Makes sure the fillIn is a valid character
|
|
private 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 printing character");
|
|
}
|
|
//Make sure the character is not a letter
|
|
if(Character.isAlphabetic(fillIn)){
|
|
throw new InvalidCharacterException("Fill in must not be a letter");
|
|
}
|
|
|
|
logger.debug("Setting fill in {}", fillIn);
|
|
|
|
//Save the fillIn character
|
|
this.fillIn = fillIn;
|
|
}
|
|
//Strips invalid characters from the keyword and creates the grid
|
|
private 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 duplicated 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 grid from the keyword
|
|
private 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());
|
|
}
|
|
//Ensures groupSize constraints
|
|
private 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;
|
|
}
|
|
//Ensures inputString constraints
|
|
private 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 inputString with only letters
|
|
private String getCleanInputString(){
|
|
logger.debug("Cleaning input string for encoding");
|
|
return inputString.toUpperCase().replaceAll("[^A-Z" + fillIn + "]", "");
|
|
}
|
|
//Returns the location of the given character in the grid
|
|
private 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");
|
|
}
|
|
//Return the character from the location provided
|
|
private 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()];
|
|
}
|
|
//Adds all non-letter characters back to the output string
|
|
private 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{
|
|
logger.debug("Appending symbol");
|
|
output.append(ch);
|
|
}
|
|
}
|
|
|
|
//Save the output
|
|
logger.debug("Formatted output '{}'", output);
|
|
this.outputString = output.toString();
|
|
}
|
|
//Encodes inputString using a polybius square and stores the result in outputString
|
|
private void encode() throws InvalidCharacterException{
|
|
logger.debug("Encoding");
|
|
|
|
//Step through every element in the sanitized inputString encoding the letters
|
|
logger.debug("Conveting 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 = inputString.length() / groupSize;
|
|
if(numGroups == 0){
|
|
numGroups = 1;
|
|
}
|
|
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 inputString using a polybius square and stores the result in outputString
|
|
private 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 = inputString.length() / groupSize;
|
|
if(numGroups == 0){
|
|
numGroups = 1;
|
|
}
|
|
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
|
|
public Trifid() throws InvalidCharacterException{
|
|
preserveCapitals = false;
|
|
preserveWhitespace = false;
|
|
preserveSymbols = false;
|
|
setFillIn('+');
|
|
}
|
|
public Trifid(boolean preserveCapitals, boolean preserveWhitespace, boolean preserveSymbols) throws InvalidCharacterException{
|
|
this.preserveCapitals = preserveCapitals;
|
|
this.preserveWhitespace = preserveWhitespace;
|
|
this.preserveSymbols = preserveSymbols;
|
|
setFillIn('+');
|
|
}
|
|
public Trifid(boolean preserveCapitals, boolean preserveWhitespace, boolean preserveSymbols, char fillIn) throws InvalidCharacterException{
|
|
this.preserveCapitals = preserveCapitals;
|
|
this.preserveWhitespace = preserveWhitespace;
|
|
this.preserveSymbols = preserveSymbols;
|
|
setFillIn(fillIn);
|
|
}
|
|
|
|
//Encodes inputString using keyword and groupSize and returns the result
|
|
public String encode(String keyword, String inputString) throws InvalidBaseException, InvalidKeywordException, InvalidInputException, InvalidCharacterException{
|
|
return encode(keyword, inputString.length(), inputString);
|
|
}
|
|
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 inputString using keyword and groupSize and returns the result
|
|
public String decode(String keyword, String inputString) throws InvalidBaseException, InvalidKeywordException, InvalidInputException, InvalidCharacterException{
|
|
return decode(keyword, inputString.length(), inputString);
|
|
}
|
|
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;
|
|
}
|
|
|
|
//Makes sure all variables are empty
|
|
public void reset(){
|
|
logger.debug("Resetting fields");
|
|
|
|
inputString = "";
|
|
outputString = "";
|
|
keyword = "";
|
|
groupSize = Integer.MAX_VALUE;
|
|
grid = new char[3][3][3];
|
|
}
|
|
//Gets
|
|
public String getInputString(){
|
|
return inputString;
|
|
}
|
|
public String getOutputString(){
|
|
return outputString;
|
|
}
|
|
public String getKeyword(){
|
|
return keyword;
|
|
}
|
|
public int getGroupSize(){
|
|
return groupSize;
|
|
}
|
|
public char getFillIn(){
|
|
return fillIn;
|
|
}
|
|
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();
|
|
}
|
|
}
|