[Practice Puzzle] Encryption/Decryption of Enigma Machine


#1

I have a problem reversing the Caesar cipher for this puzzle. My code passes all encoding tests but fails at decoding. I suspect there is an error at the last step where I try to decrypt the message. My logic is:

  • Find the index of the current letter of the encrypted message in the alphabet (eg. A = 0, B = 1, etc.)

  • Subtract the same offset and shift that would have been added to the original letter to produce the current one

  • If the result is negative that means the letter was produced via modulo 26, i.e. it exceeded the maximum index of ā€˜Zā€™, thus I add 26 to counteract the circular flow

  • Finally I add 65 to convert the index to the actual letter it represents.

      private static void encCeasar() {
              int offset = 0;
              char[] result = msg.toCharArray();
              for (int i = 0; i < msg.length(); i++) {
                  result[i] = (char)((msg.charAt(i) + rng + offset - 65) % 26 + 65);
                  offset++;
              }
              msg = String.valueOf(result);
          }
      
      private static void decCeasar() {
          int offset = 0;
          char[] result = msg.toCharArray();
          for (int i = 0; i < msg.length(); i++) {
              int index = (msg.charAt(i) - rng - offset - 65);
              while (index < 0) {
                  index += 26;    
              }
              result[i] = (char)(index + 65);
              offset++;
          }
          msg = String.valueOf(result);
      }

#2

Please note that there is already a long thread about this puzzle.