Simple Substitution Cipher Alphabet Generator in Java..


Give me a unique key and the plain alphabet, and I shall return you the Cipher Alphabet!

Very good explanation can be found in The Code Book. Basically, you have a plain alphabet, a key where each character is unique and the algorithm goes like this:
  • Use the unique key as the beginning of the cipher alphabet.
  • Remainder of the cipher alphabet is the remaining letters of the alphabet, in their correct order, starting where the key ends.


Code Please?

SubstitutionCipherAlphabetGenerator.java
import java.util.*;
 
 
class SubstitutionCipherAlphabetGenerator {
 
    LinkedHashSet<Character> getCipherAlphabet(final char[] plainAlphabet, final char[] key) {
        final LinkedHashSet<Character> cipherAlphabet = new LinkedHashSet<>();
 
        for (final char character : key) {
            cipherAlphabet.add(character);
        }
 
        int loopStart = 0;
        for (final char character : plainAlphabet) {
            if (character == key[key.length - 1]) {
                break;
            }
            loopStart++;
        }
 
        for (int i = loopStart; i < plainAlphabet.length; i++) {
            if (!cipherAlphabet.contains(plainAlphabet[i])) {
                cipherAlphabet.add(plainAlphabet[i]);
            }
        }
 
        for (final char character : plainAlphabet) {
            if (!cipherAlphabet.contains(character)) {
                cipherAlphabet.add(character);
            }
        }
 
        return cipherAlphabet;
    }
}

and just to make sure all is fine, SubstitutionCipherAlphabetGeneratorTest.java
import java.util.LinkedHashSet;
 
public class CipherAlphabetFromKeyGeneratorTest {
 
    public static void main(String[] args) {
        test01();
    }
 
    static void test01() {
        final SubstitutionCipherAlphabetGenerator generator = new SubstitutionCipherAlphabetGenerator();
        char[] plainAlphabet = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        char[] key = {'J', 'U', 'L', 'I', 'S', 'C', 'A', 'E', 'R'};
 
        final LinkedHashSet<Character> cipherAlphabet = generator.getCipherAlphabet(plainAlphabet, key);
 
        StringBuilder stringBuilder = new StringBuilder();
        for (Character character : cipherAlphabet) {
            stringBuilder.append(character);
        }
 
        assert stringBuilder.toString().equals("JULISCAERTVWXYZBDFGHKMNOPQ");
    }
}