Dongbae
Dongbae

Reputation: 31

RSA Encrypting and Decrypting JAVA

I've been trying to decrypt my encrypted message for a while now, but it isn't working as I'd like it to. I have my outputs for encryption working, but I can't decrypt the encrypted message!

Here are my values: P: 67 Q: 71 PQ: 4757 PhiPQ: 4620 E: 13 D: 1777

Here is my output for the encrypted message (when 'hello' is entered): ???? (Which is working fine)

Here is my output for the decrypted message (when 'hello' is entered): 1109 314 2309 2309 4015 (Which is working, but does not give me back the characters 'hello')

We're supposed to implement this formula into the code (C^D)%PQ but I'm not entirely sure how to implement it when decrypting the encrypted message.

I'm not sure what the problem is, here is my code below:

ENCRYPTION

    String encryptedMessage = "";

    String message = JOptionPane.showInputDialog(null, "Enter a message: ");

    int c = 0;
    for (int i = 0; message.length() > i; i++) {
        char l = message.charAt(i);
        int m = l;
        c = 1;
        int newE = e;

        while (newE > 0) {
            if (newE % 2 != 0) {
                c = ((c * m) % (pq));
            }
            newE = newE / 2;
            m = (((m * m)) % (pq));
        }
        encryptedMessage = encryptedMessage + (char) c;
    }

    System.out.println("Encrypted Message is: " + encryptedMessage);

DECRYPTION

    String decryptedMessage = "";

    c = 0;
    for (int i = 0; encryptedMessage.length() > i; i++) {
        char l = encryptedMessage.charAt(i);
        int m = l;
        c = 1;
        int newE = e;

        while (newE > 0) {
            if (newE % 2 != 0) {
                c = ((c * m) % (pq));
            }
            newE = newE / 2;
            m = (((m * m)) % (pq));
        }
        decryptedMessage = decryptedMessage + " " + (c);
    }

    // prints out 'decryptedMessage' value
    System.out.println("Decrypted Message is: " + decryptedMessage);
}
}

Upvotes: 0

Views: 533

Answers (2)

Dongbae
Dongbae

Reputation: 31

@EJP was right.

I put in the decryption key and it worked perfectly! So, instead of my encryption key being newE, I switched it with newD and it finally works now. It was a stupid, small mistake on my part. Thanks for the hints!

Upvotes: 0

avh
avh

Reputation: 188

Your code for encryption and decryption look, well, symmetric. That's not the trick with RSA. In RSA, you have the public key e for encryption and the private key d for decryption. I don't even see d in your decryption code?!

Upvotes: 1

Related Questions