Skip to content

Commit

Permalink
Add unit test for RSA cipher (TheAlgorithms#3664)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexandreVelloso authored Oct 26, 2022
1 parent f8897f1 commit 8c6ed9c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 23 deletions.
29 changes: 6 additions & 23 deletions src/main/java/com/thealgorithms/ciphers/RSA.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,15 @@

import java.math.BigInteger;
import java.security.SecureRandom;
import javax.swing.*;

/**
* @author Nguyen Duy Tiep on 23-Oct-17.
*/
public final class RSA {
public class RSA {

public static void main(String[] args) {
RSA rsa = new RSA(1024);
String text1 = JOptionPane.showInputDialog(
"Enter a message to encrypt :"
);

String ciphertext = rsa.encrypt(text1);
JOptionPane.showMessageDialog(
null,
"Your encrypted message : " + ciphertext
);

JOptionPane.showMessageDialog(
null,
"Your message after decrypt : " + rsa.decrypt(ciphertext)
);
}

private BigInteger modulus, privateKey, publicKey;
private BigInteger modulus;
private BigInteger privateKey;
private BigInteger publicKey;

public RSA(int bits) {
generateKeys(bits);
Expand Down Expand Up @@ -77,10 +60,10 @@ public synchronized void generateKeys(int bits) {
BigInteger m =
(p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));

publicKey = new BigInteger("3");
publicKey = BigInteger.valueOf(3L);

while (m.gcd(publicKey).intValue() > 1) {
publicKey = publicKey.add(new BigInteger("2"));
publicKey = publicKey.add(BigInteger.valueOf(2L));
}

privateKey = publicKey.modInverse(m);
Expand Down
24 changes: 24 additions & 0 deletions src/test/java/com/thealgorithms/ciphers/RSATest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.thealgorithms.ciphers;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

class RSATest {

RSA rsa = new RSA(1024);

@Test
void testRSA() {
// given
String textToEncrypt = "Such secure";

// when
String cipherText = rsa.encrypt(textToEncrypt);
String decryptedText = rsa.decrypt(cipherText);

// then
assertEquals("Such secure", decryptedText);
}

}

0 comments on commit 8c6ed9c

Please sign in to comment.