import java.math.BigInteger;
import java.util.Random;
import java.io.*;
class RSA {
private int bitlength = 1024;
private int blocksize = 256;
//blocksize in byte
public RSA() {
N = p.multiply(q);
while (phi.
gcd(e
).
compareTo(biginteger.
ONE) >
0 && e.
compareTo(phi
) <
0 ) {
}
d = e.modInverse(phi);
}
this.e = e;
this.d = d;
this.N = N;
}
RSA rsa = new RSA();
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());
system.
out.
println("Encrypted String in Bytes: " + bytesToString
(encrypted
));
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
system.
out.
println("Decrypted String in Bytes: " + bytesToString
(decrypted
));
system.
out.
println("Decrypted String: " +
new string(decrypted
));
}
private static string bytesToString
(byte[] encrypted
) {
for (byte b : encrypted) {
test +=
byte.
toString(b
);
}
return test;
}
//Encrypt message
public byte[] encrypt(byte[] message) {
return (new biginteger(message
)).
modPow(e, N
).
toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message) {
return (new biginteger(message
)).
modPow(d, N
).
toByteArray();
}
}