Im trying to encrypt and decrypt a string, and eventually a file containing plaintext, using my own RSA implementation in Java. Ive tried following countless examples here on SO and the web, where people are using either the built in Java RSA function or their own implementation of the algorithm, but cant get any of them to work, in that the decrypted text never matches the original string.
I dont know if i am doing something wrong with the encoding/decoding of text, have tried using default UTF-8 and the Base64 encoders in java.xml.* but no luck there either. Im not using any padding, i dont know if thats necessary for it work at all, and im just using an arbitrary key length, which ive tried changing the size of, and doesnt make things work either. This is just an exercise for myself, no ones information is going to be protected by this or anything. But im not sure what the issue is, so here is my code, that tries to encrypt/decrypt a simple string:
BigInteger ONE = new BigInteger("1");
SecureRandom rand = new SecureRandom();
BigInteger d;
BigInteger e;
BigInteger n;
BigInteger p = BigInteger.probablePrime(10, rand); // 10 is arbitrary, have tried different numbers
BigInteger q = BigInteger.probablePrime(10, rand);
BigInteger phi = (p.subtract(ONE)).multiply(q.subtract(ONE));
n = p.multiply(q); //10 bits * 10 bits = ??? bits for key length
e = new BigInteger("65537"); //public key exponent
d = e.modInverse(phi); //private key exponent
String string = "this is a test";
byte[] bytes = string.getBytes();
BigInteger plainText = new BigInteger(bytes);
BigInteger cipherText = plainText.modPow(e, n);
BigInteger originalMessage = cipherText.modPow(d, e);
System.out.println(string.getBytes());
System.out.println(cipherText);
System.out.println(originalMessage);
The output has different values for all three things everytime i run my program: But they are always in the same relative form:
[B@52d85409
157529
24312