Skip to content

Commit bc0f787

Browse files
authored
Merge pull request #230 from sairamreddy3048/patch-1
Added RSA algorithm in Java
2 parents bcbd283 + b4f6de7 commit bc0f787

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

encryption_algorithms/RSA.java

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package com.sanfoundry.setandstring;
2+
3+
import java.io.DataInputStream;
4+
import java.io.IOException;
5+
import java.math.BigInteger;
6+
import java.util.Random;
7+
8+
public class RSA
9+
{
10+
private BigInteger p;
11+
private BigInteger q;
12+
private BigInteger N;
13+
private BigInteger phi;
14+
private BigInteger e;
15+
private BigInteger d;
16+
private int bitlength = 1024;
17+
private Random r;
18+
19+
public RSA()
20+
{
21+
r = new Random();
22+
p = BigInteger.probablePrime(bitlength, r);
23+
q = BigInteger.probablePrime(bitlength, r);
24+
N = p.multiply(q);
25+
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
26+
e = BigInteger.probablePrime(bitlength / 2, r);
27+
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
28+
{
29+
e.add(BigInteger.ONE);
30+
}
31+
d = e.modInverse(phi);
32+
}
33+
34+
public RSA(BigInteger e, BigInteger d, BigInteger N)
35+
{
36+
this.e = e;
37+
this.d = d;
38+
this.N = N;
39+
}
40+
41+
@SuppressWarnings("deprecation")
42+
public static void main(String[] args) throws IOException
43+
{
44+
RSA rsa = new RSA();
45+
DataInputStream in = new DataInputStream(System.in);
46+
String teststring;
47+
System.out.println("Enter the plain text:");
48+
teststring = in.readLine();
49+
System.out.println("Encrypting String: " + teststring);
50+
System.out.println("String in Bytes: "
51+
+ bytesToString(teststring.getBytes()));
52+
// encrypt
53+
byte[] encrypted = rsa.encrypt(teststring.getBytes());
54+
// decrypt
55+
byte[] decrypted = rsa.decrypt(encrypted);
56+
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
57+
System.out.println("Decrypted String: " + new String(decrypted));
58+
}
59+
60+
private static String bytesToString(byte[] encrypted)
61+
{
62+
String test = "";
63+
for (byte b : encrypted)
64+
{
65+
test += Byte.toString(b);
66+
}
67+
return test;
68+
}
69+
70+
// Encrypt message
71+
public byte[] encrypt(byte[] message)
72+
{
73+
return (new BigInteger(message)).modPow(e, N).toByteArray();
74+
}
75+
76+
// Decrypt message
77+
public byte[] decrypt(byte[] message)
78+
{
79+
return (new BigInteger(message)).modPow(d, N).toByteArray();
80+
}
81+
}

0 commit comments

Comments
 (0)