-
Notifications
You must be signed in to change notification settings - Fork 0
/
RSA.java
93 lines (56 loc) · 2.59 KB
/
RSA.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.Random;
import java.math.BigInteger;
public class RSA implements Crypto {
private int keyBitLength = 1024;
private RSAKey publicKey;
private RSAKey privateKey;
public void generateKeyPair() {
Random rndm = new Random();
BigInteger p = BigInteger.probablePrime(keyBitLength, rndm);
BigInteger q = BigInteger.probablePrime(keyBitLength, rndm);
BigInteger modulus = calculateModulus(p, q);
BigInteger totient = calulateTotient(p, q);
BigInteger publicKeyExponent = generatePublicKeyExponent(totient);
BigInteger privateKeyExponent = generatePrivateKeyExponent(publicKeyExponent, totient);
publicKey = new RSAKey(publicKeyExponent, modulus);
privateKey = new RSAKey(privateKeyExponent, modulus);
System.out.println("\nKey generation successful !!");
}
private BigInteger calculateModulus(final BigInteger p, final BigInteger q) {
return p.multiply(q) ;
}
private BigInteger calulateTotient(final BigInteger p, final BigInteger q) {
return p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
}
private BigInteger generatePublicKeyExponent(final BigInteger totient) {
Random rndm = new Random();
BigInteger value;
value = BigInteger.probablePrime(keyBitLength / 2, rndm);
while (totient.gcd(value).compareTo(BigInteger.ONE) > 0 && value.compareTo(totient) < 0)
value.add(BigInteger.ONE);
return value;
}
private BigInteger generatePrivateKeyExponent(final BigInteger publicKeyExponent, final BigInteger totient) {
return publicKeyExponent.modInverse(totient);
}
public RSAKey getPublicKey() {
return publicKey;
}
public RSAKey getPrivateKey() {
return privateKey;
}
public String encrypt(String plaintext, RSAKey publicKey) {
BigInteger kp = publicKey.getExponent();
BigInteger n = publicKey.getModulus();
byte[] plaintextInBytes = plaintext.getBytes();
byte[] ciphertextInBytes = (new BigInteger(plaintextInBytes)).modPow(kp, n).toByteArray();
return Service.convertBytestoString(ciphertextInBytes);
}
public String decrypt(String ciphertext, RSAKey privateKey) {
BigInteger ks = privateKey.getExponent();
BigInteger n = privateKey.getModulus();
byte[] ciphertextInBytes = Service.convertStringtoBytes(ciphertext);
byte[] plaintextInBytes = (new BigInteger(ciphertextInBytes)).modPow(ks, n).toByteArray();
return new String(plaintextInBytes);
}
}