JavaAlgorithms/ciphers/RSA.java

99 lines
2.5 KiB
Java
Raw Normal View History

2017-10-24 20:39:11 +08:00
package ciphers;
import java.math.BigInteger;
import java.security.SecureRandom;
2018-04-14 11:39:16 +08:00
import javax.swing.JOptionPane;
2017-10-24 20:39:11 +08:00
/**
2018-04-14 11:39:16 +08:00
* @author Nguyen Duy Tiep on 23-Oct-17.
2017-10-24 20:39:11 +08:00
*/
2018-04-14 11:39:16 +08:00
public final class RSA {
/**
* Trivial test program.
*
* @param args
* @deprecated TODO remove main and make JUnit Testing or any other
* methodology
*/
public static void main(String[] args) {
RSA rsa = new RSA(1024);
String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :");
String ciphertext = rsa.encrypt(text1);
JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext);
JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext));
}
2017-10-24 20:39:11 +08:00
private BigInteger modulus, privateKey, publicKey;
2018-04-14 11:39:16 +08:00
/**
*
* @param bits
*/
2017-10-24 20:39:11 +08:00
public RSA(int bits) {
generateKeys(bits);
}
2018-04-14 11:39:16 +08:00
/**
*
* @param message
* @return encrypted message
*/
2017-10-24 20:39:11 +08:00
public synchronized String encrypt(String message) {
return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
}
2018-04-14 11:39:16 +08:00
/**
*
* @param message
* @return encrypted message as big integer
*/
2017-10-24 20:39:11 +08:00
public synchronized BigInteger encrypt(BigInteger message) {
return message.modPow(publicKey, modulus);
}
2018-04-14 11:39:16 +08:00
/**
*
* @param encryptedMessage
* @return plain message
*/
public synchronized String decrypt(String encryptedMessage) {
return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
2017-10-24 20:39:11 +08:00
}
2018-04-14 11:39:16 +08:00
/**
*
* @param encryptedMessage
* @return plain message as big integer
*/
public synchronized BigInteger decrypt(BigInteger encryptedMessage) {
return encryptedMessage.modPow(privateKey, modulus);
2017-10-24 20:39:11 +08:00
}
2018-04-14 11:39:16 +08:00
/**
* Generate a new public and private key set.
*
* @param bits
*/
2017-10-24 20:39:11 +08:00
public synchronized void generateKeys(int bits) {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bits / 2, 100, r);
BigInteger q = new BigInteger(bits / 2, 100, r);
modulus = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = new BigInteger("3");
while (m.gcd(publicKey).intValue() > 1) {
publicKey = publicKey.add(new BigInteger("2"));
}
privateKey = publicKey.modInverse(m);
}
}