rsa_bigint.java
59 linesjava
DOWNLOAD
1// Aim: Program to perform RSA encryption (RSA Encryption).
2import java.math.BigInteger;
3import java.security.SecureRandom;
4
5public class rsa_bigint {
6
7    private BigInteger p, q, n, phi, e, d;
8    private int bitLength = 1024; 
9    private SecureRandom random;
10
11    public rsa_bigint() {
12        random = new SecureRandom();
13                
14        p = BigInteger.probablePrime(bitLength / 2, random);
15        q = BigInteger.probablePrime(bitLength / 2, random);
16        
17        n = p.multiply(q);
18        
19        phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
20
21        e = BigInteger.probablePrime(bitLength / 2, random);
22        while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) {
23            e = e.add(BigInteger.ONE);
24        }
25        
26        d = e.modInverse(phi);
27    }
28
29    public BigInteger getPublicKeyE() { return e; }
30    public BigInteger getModulusN() { return n; }
31    
32    public BigInteger getPrivateKeyD() { return d; }
33
34    public byte[] encrypt(byte[] message) {
35        return (new BigInteger(message)).modPow(e, n).toByteArray();
36    }
37
38    // RSA Decryption: M = C^d mod n
39    // Where M is original message, C is ciphertext, d is private exponent, n is modulus
40    public byte[] decrypt(byte[] encryptedMessage) {
41        return (new BigInteger(encryptedMessage)).modPow(d, n).toByteArray();
42    }
43
44    public static void main(String[] args) {
45        // Create RSA instance with generated keys
46        rsa_bigint rsa = new rsa_bigint();
47        String originalMessage = "Hello, RSA!";
48        System.out.println("Original Message: " + originalMessage);
49
50        // Encrypt the message using public key (e, n)
51        byte[] encryptedBytes = rsa.encrypt(originalMessage.getBytes());
52        System.out.println("Encrypted Message (bytes): " + new BigInteger(encryptedBytes).toString());
53
54        // Decrypt the message using private key (d, n)
55        byte[] decryptedBytes = rsa.decrypt(encryptedBytes);
56        String decryptedMessage = new String(decryptedBytes);
57        System.out.println("Decrypted Message: " + decryptedMessage);
58    }
59}