I am using SpongyCastle for a project on android. I have used RSA to encrypt the data and then decrypt it in another activity, the keys are stored in the shared preferences. I discovered a thing I cannot explain.
My keys are generated only once and stored for future use without being changed. On encrypting the same plain text, I get two different outputs.
I encrypted the plaintext a
and got the following outputs :
"G4srxAxUnoikOIQdlj30rmyUiGz3P0R0VE6BflSTo4UQqJVSBpQtyFSB6tt73Z693D0LMkykDEPB
lPg0IEH/R6tOJCyCU8HxKQ8nfo5OGUYFgkup3aGPkRqb+gCLpc5YGSmLztaynKq1H6kplryx0q1+
KTCchc6PswAMpaMwMTk="
"j2r5MsaGRNazElAxG4BIBgZYtrjdxaErbs+19ObsCyOuVwTiu0cvKcKTOPuUOOjcGVaDup53wdEk
AHHsy8zA1gR29uSdW4C2JIDnQVGCcfzqOcbzeS4WgV+2WpLTahBj6Df8pya2YksIp3KSLSnhH3nn
B2kf/Wi53SQmJJWSf84="
"Yz3xhiObUI5C8UA31VNH3VqUXGmotGpTz9A3U2n81lJ7p1//x4CI15r4JUZGJlN1aPnSayIuk6D8
hMIp32o53YEmm69gve91+dCVDQkZOUE9UuA2nEcjR21nUgWPQJdwqQ7P4XFeWsBaokpwNCA6j2qb
b1Glfp+AVpUNm7syiUY="
...
I know that RSA is $Y = X^e \pmod{n}$
Since neither $X$ (plaintext) nor $e$ (public key) changes, I'm guessing $n$ changes each time.
The decryption works just fine for each case.
So, if $n$ changes each time, for decryption to know the value of $n$ it has to be passed on with the message itself.
My questions:
Am I correct in assuming the above? If yes, where is $n$, and what is the format for storing the message? If No, what is the correct method?
The output is 172 characters each time? How does that work out?
P.S. : I am following this.
Edit:
I can conclude that from the answers that padding is responsible for this. If padding is different each time, shouldn't it be mentioned or the length of the actual message be mentioned with the ciphertext so that deciphering code can differentiate the padding from the actual message? If it is the same, wouldn't it give the same result each time, we would still need to pass the length of the actual message encrypted as it may be. (I think it's random)
I also found out that I can't encrypt more than 86 characters. Why? Is there a limit on the number of characters by RSA?
Giving me this:
06-12 18:09:37.192 9217-9217/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.chatr, PID: 9217
java.lang.RuntimeException: java.lang.RuntimeException: java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block
at crypto.RSA.encryptWithKey(RSA.java:87)
at crypto.RSA.encryptWithStoredKey(RSA.java:93)
Also, the same error comes when I try to decrypt the ciphertext when I replace =
with something else, and obviously hash fails when I change some other character. What does =
signify. I'm assuming padding.
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", "SC");
so it's certain that it is OAEP. Lucky you. $\endgroup$