Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unit test for RSA cipher #3664

Merged
merged 3 commits into from
Oct 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}

}