I can't add to integers to characters variables when trying to decode an encryption key by brute force in Java

36 Views Asked by At

I have a message that is not encrypted and I am using it to fing out the encryption key. I use a random number generator to find the encryption key. I put the message into a TreeMap and the encrypted message into value(value = key + encryptionKey). bruteForceKeyDecoding is supposed to give me the key used.

Everytime I try this I get an error message. Here is my code :

public class KeyDecoding {
        private static int EncryptionKey = 12;
        private static Map<Character, Character> encryptedText = new TreeMap<>();

        public static int bruteForceKeyDecoding( String message) {

            StringBuilder sb = new StringBuilder();
            StringBuilder sb2 = new StringBuilder();

            for (int i = 0; i < message.length(); i++) {
                encryptedText.put(message.charAt(i), (char) (message.charAt(i) + EncryptionKey));
                sb2.append(encryptedText.get(message.charAt(i)));
            }
            String messageToDecode = sb2.toString();

            int realKey = 0;

            while(messageToDecode != message) {
                int randomKey = generateNewKey();
                for(int i = 0; i < message.length(); i++) {
                    encryptedText.put((char) EncryptionKey, (char) (encryptedText.get(EncryptionKey)-randomKey));
                    sb.append(encryptedText.get(EncryptionKey));
                }
                messageToDecode = sb.toString();
                realKey = randomKey;
            }
            return realKey;
        }

        public static int generateNewKey() {
            Random rand = new Random();
            int rand_int1 = rand.nextInt(30);
            return rand_int1;
        }
}

public class Main {
    public static void main(String[] args) {
        String message = "I love Java";
        System.out.println(KeyDecoding.bruteForceKeyDecoding(message));
    }
}

This is the error it gives me for this line encryptedText.put((char) EncryptionKey, (char) (encryptedText.get(EncryptionKey)-randomKey)); :

Exception in thread "main" java.lang.ClassCastException: class java.lang.Character cannot be cast to class java.lang.Integer (java.lang.Character and java.lang.Integer are in module java.base of loader 'bootstrap')
    at java.base/java.lang.Integer.compareTo(Integer.java:72)
    at java.base/java.util.TreeMap.getEntry(TreeMap.java:350)
    at java.base/java.util.TreeMap.get(TreeMap.java:279)
    at KeyDecoding.bruteForceKeyDecoding(KeyDecoding.java:25)
    at Main.main(Main.java:6)

It's telling me I can't add Integer with Characters. Please tell me how to do that. Maybe there is a better way to brute force an encryptionKey. Would you mind telling me if you know of it ? Thank you.

0

There are 0 best solutions below