forked from TheAlgorithms/Java
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSA.java
More file actions
Latest commit
98 lines (80 loc) · 2.46 KB
/
Copy pathRSA.java
File metadata and controls
98 lines (80 loc) · 2.46 KB
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
94
95
96
97
98
packageciphers;
importjava.math.BigInteger;
importjava.security.SecureRandom;
importjavax.swing.JOptionPane;
/**
* @author Nguyen Duy Tiep on 23-Oct-17.
*/
publicfinalclassRSA {
/**
* Trivial test program.
*
* @param args
* @deprecated TODO remove main and make JUnit Testing or any other
* methodology
*/
publicstaticvoidmain(String[] args) {
RSArsa = newRSA(1024);
Stringtext1 = JOptionPane.showInputDialog("Enter a message to encrypt :");
Stringciphertext = rsa.encrypt(text1);
JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext);
JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext));
}
privateBigIntegermodulus, privateKey, publicKey;
/**
*
* @param bits
*/
publicRSA(intbits) {
generateKeys(bits);
}
/**
*
* @param message
* @return encrypted message
*/
publicsynchronizedStringencrypt(Stringmessage) {
return (newBigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
}
/**
*
* @param message
* @return encrypted message as big integer
*/
publicsynchronizedBigIntegerencrypt(BigIntegermessage) {
returnmessage.modPow(publicKey, modulus);
}
/**
*
* @param encryptedMessage
* @return plain message
*/
publicsynchronizedStringdecrypt(StringencryptedMessage) {
returnnewString((newBigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
}
/**
*
* @param encryptedMessage
* @return plain message as big integer
*/
publicsynchronizedBigIntegerdecrypt(BigIntegerencryptedMessage) {
returnencryptedMessage.modPow(privateKey, modulus);
}
/**
* Generate a new public and private key set.
*
* @param bits
*/
publicsynchronizedvoidgenerateKeys(intbits) {
SecureRandomr = newSecureRandom();
BigIntegerp = newBigInteger(bits / 2, 100, r);
BigIntegerq = newBigInteger(bits / 2, 100, r);
modulus = p.multiply(q);
BigIntegerm = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = newBigInteger("3");
while (m.gcd(publicKey).intValue() > 1) {
publicKey = publicKey.add(newBigInteger("2"));
}
privateKey = publicKey.modInverse(m);
}
}