Skip to content

Commit 8c6ed9c

Browse files
Add unit test for RSA cipher (TheAlgorithms#3664)
1 parent f8897f1 commit 8c6ed9c

File tree

2 files changed

+30
-23
lines changed

2 files changed

+30
-23
lines changed

src/main/java/com/thealgorithms/ciphers/RSA.java

Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,15 @@
22

33
import java.math.BigInteger;
44
import java.security.SecureRandom;
5-
import javax.swing.*;
65

76
/**
87
* @author Nguyen Duy Tiep on 23-Oct-17.
98
*/
10-
public final class RSA {
9+
public class RSA {
1110

12-
public static void main(String[] args) {
13-
RSA rsa = new RSA(1024);
14-
String text1 = JOptionPane.showInputDialog(
15-
"Enter a message to encrypt :"
16-
);
17-
18-
String ciphertext = rsa.encrypt(text1);
19-
JOptionPane.showMessageDialog(
20-
null,
21-
"Your encrypted message : " + ciphertext
22-
);
23-
24-
JOptionPane.showMessageDialog(
25-
null,
26-
"Your message after decrypt : " + rsa.decrypt(ciphertext)
27-
);
28-
}
29-
30-
private BigInteger modulus, privateKey, publicKey;
11+
private BigInteger modulus;
12+
private BigInteger privateKey;
13+
private BigInteger publicKey;
3114

3215
public RSA(int bits) {
3316
generateKeys(bits);
@@ -77,10 +60,10 @@ public synchronized void generateKeys(int bits) {
7760
BigInteger m =
7861
(p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
7962

80-
publicKey = new BigInteger("3");
63+
publicKey = BigInteger.valueOf(3L);
8164

8265
while (m.gcd(publicKey).intValue() > 1) {
83-
publicKey = publicKey.add(new BigInteger("2"));
66+
publicKey = publicKey.add(BigInteger.valueOf(2L));
8467
}
8568

8669
privateKey = publicKey.modInverse(m);
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.thealgorithms.ciphers;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import static org.junit.jupiter.api.Assertions.assertEquals;
6+
7+
class RSATest {
8+
9+
RSA rsa = new RSA(1024);
10+
11+
@Test
12+
void testRSA() {
13+
// given
14+
String textToEncrypt = "Such secure";
15+
16+
// when
17+
String cipherText = rsa.encrypt(textToEncrypt);
18+
String decryptedText = rsa.decrypt(cipherText);
19+
20+
// then
21+
assertEquals("Such secure", decryptedText);
22+
}
23+
24+
}

0 commit comments

Comments
 (0)