From 8c6ed9c24061b15693705857e16f270275030ff2 Mon Sep 17 00:00:00 2001 From: Alexandre Velloso <4320811+AlexandreVelloso@users.noreply.github.com> Date: Wed, 26 Oct 2022 02:10:27 +0100 Subject: [PATCH] Add unit test for RSA cipher (#3664) --- .../java/com/thealgorithms/ciphers/RSA.java | 29 ++++--------------- .../com/thealgorithms/ciphers/RSATest.java | 24 +++++++++++++++ 2 files changed, 30 insertions(+), 23 deletions(-) create mode 100644 src/test/java/com/thealgorithms/ciphers/RSATest.java diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java index abab01361..fcce53cbd 100644 --- a/src/main/java/com/thealgorithms/ciphers/RSA.java +++ b/src/main/java/com/thealgorithms/ciphers/RSA.java @@ -2,32 +2,15 @@ package com.thealgorithms.ciphers; 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); @@ -77,10 +60,10 @@ public final class RSA { 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); diff --git a/src/test/java/com/thealgorithms/ciphers/RSATest.java b/src/test/java/com/thealgorithms/ciphers/RSATest.java new file mode 100644 index 000000000..46fff7963 --- /dev/null +++ b/src/test/java/com/thealgorithms/ciphers/RSATest.java @@ -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); + } + +}