|
| 1 | +package ciphers; |
| 2 | + |
| 3 | +import java.math.BigInteger; |
| 4 | +import java.security.SecureRandom; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by Nguyen Duy Tiep on 23-Oct-17. |
| 8 | + */ |
| 9 | +public class RSA { |
| 10 | + private BigInteger modulus, privateKey, publicKey; |
| 11 | + |
| 12 | + public RSA(int bits) { |
| 13 | + generateKeys(bits); |
| 14 | + } |
| 15 | + |
| 16 | + public synchronized String encrypt(String message) { |
| 17 | + return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString(); |
| 18 | + } |
| 19 | + |
| 20 | + public synchronized BigInteger encrypt(BigInteger message) { |
| 21 | + return message.modPow(publicKey, modulus); |
| 22 | + } |
| 23 | + |
| 24 | + public synchronized String decrypt(String message) { |
| 25 | + return new String((new BigInteger(message)).modPow(privateKey, modulus).toByteArray()); |
| 26 | + } |
| 27 | + |
| 28 | + public synchronized BigInteger decrypt(BigInteger message) { |
| 29 | + return message.modPow(privateKey, modulus); |
| 30 | + } |
| 31 | + |
| 32 | + /** Generate a new public and private key set. */ |
| 33 | + public synchronized void generateKeys(int bits) { |
| 34 | + SecureRandom r = new SecureRandom(); |
| 35 | + BigInteger p = new BigInteger(bits / 2, 100, r); |
| 36 | + BigInteger q = new BigInteger(bits / 2, 100, r); |
| 37 | + modulus = p.multiply(q); |
| 38 | + |
| 39 | + BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); |
| 40 | + |
| 41 | + publicKey = new BigInteger("3"); |
| 42 | + |
| 43 | + while (m.gcd(publicKey).intValue() > 1) { |
| 44 | + publicKey = publicKey.add(new BigInteger("2")); |
| 45 | + } |
| 46 | + |
| 47 | + privateKey = publicKey.modInverse(m); |
| 48 | + } |
| 49 | + |
| 50 | + /** Trivial test program. */ |
| 51 | + public static void main(String[] args) { |
| 52 | + RSA rsa = new RSA(1024); |
| 53 | + |
| 54 | + String text1 = "This is a message"; |
| 55 | + System.out.println("Plaintext: " + text1); |
| 56 | + |
| 57 | + String ciphertext = rsa.encrypt(text1); |
| 58 | + System.out.println("Ciphertext: " + ciphertext); |
| 59 | + |
| 60 | + System.out.println("Plaintext: " + rsa.decrypt(ciphertext)); |
| 61 | + } |
| 62 | +} |
0 commit comments