import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
//import java.util.Base64;
// P = 137
// Q = 131
// E = 3
// Public keys (n,e) = (17947, 3) and private keys (n, d) = (17947, 11787).
public class RSAMoreTest {
//private int bitlength = 1024;
//private SecureRandom r;
private RSAMoreTest()
{
n = p.multiply(q); // modulus, n = pq
while (phi.
gcd(e
).
compareTo(BigInteger.
ONE) > 0 && e.
compareTo(phi
) < 0) {
}
d = e.modInverse(phi);
}
@SuppressWarnings("deprecation")
{
RSAMoreTest rsa = new RSAMoreTest();
System.
out.
println("Enter the plain text:"); teststring = in.readLine();
System.
out.
println("Encrypting String: " + teststring
); System.
out.
println("String in Bytes: " + bytesToString(teststring.getBytes()));
//Encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
//Decryption
byte[] decrypted = rsa.decrypt(encrypted);
System.
out.
println("Decrypting Bytes: " + bytesToString
(decrypted
)); System.
out.
println("Decrypting String: " + new String(decrypted
));
//System.out.println("Encrypting Numbers: " + rsa.e.toString() + ", " + rsa.n.toString());
//System.out.println("Decrypting Numbers: " + rsa.d.toString() + ", " + rsa.n.toString());
}
private static String bytesToString
(byte[] encrypted
) {
for (byte b : encrypted)
{
test
+= Byte.
toString(b
); }
return test;
}
// Encrypt message
private byte[] encrypt(byte[] message)
{
return (new BigInteger(message
)).
modPow(e, n
).
toByteArray(); }
// Decrypt message
private byte[] decrypt(byte[] message)
{
return (new BigInteger(message
)).
modPow(d, n
).
toByteArray(); }
}
aW1wb3J0IGphdmEuaW8uRGF0YUlucHV0U3RyZWFtOwppbXBvcnQgamF2YS5pby5JT0V4Y2VwdGlvbjsKaW1wb3J0IGphdmEubWF0aC5CaWdJbnRlZ2VyOwovL2ltcG9ydCBqYXZhLnV0aWwuQmFzZTY0OwoKLy8gUCA9IDEzNwovLyBRID0gMTMxCi8vIEUgPSAzCi8vIFB1YmxpYyBrZXlzIChuLGUpID0gKDE3OTQ3LCAzKSBhbmQgcHJpdmF0ZSBrZXlzIChuLCB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