Created
December 28, 2024 07:45
-
-
Save jinhoyim/e887e50678d261960607c52d87737419 to your computer and use it in GitHub Desktop.
RSA in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class KeyPairTest { | |
@Test | |
void sut_correctly_encrypt_message() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { | |
KeyPair keyPair = getKeyPair(); | |
PublicKey publicKey = keyPair.getPublic(); | |
Cipher encryptCipher = Cipher.getInstance("RSA"); | |
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey); | |
String message = "Hello World!"; | |
byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8); | |
byte[] encrypedMessageBytes = encryptCipher.doFinal(messageBytes); | |
String encodedMessage = new String(messageBytes, StandardCharsets.UTF_8); | |
String encryptedMessage = new String(encrypedMessageBytes, StandardCharsets.UTF_8); | |
assertThat(encodedMessage).isEqualTo(message); | |
assertThat(encryptedMessage).isNotEqualTo(message); | |
} | |
@Test | |
void sut_correctly_decrypt_message() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { | |
KeyPair keyPair = getKeyPair(); | |
PublicKey publicKey = keyPair.getPublic(); | |
PrivateKey privateKey = keyPair.getPrivate(); | |
Cipher encryptCipher = Cipher.getInstance("RSA"); | |
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey); | |
String message = "Hello World!"; | |
byte[] messageBytes = message.getBytes(StandardCharsets.UTF_8); | |
byte[] encrypedMessageBytes = encryptCipher.doFinal(messageBytes); | |
Cipher decryptCipher = Cipher.getInstance("RSA"); | |
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey); | |
byte[] decryptedMessageBytes = decryptCipher.doFinal(encrypedMessageBytes); | |
String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8); | |
assertThat(decryptedMessage).isEqualTo(message); | |
} | |
private static KeyPair getKeyPair() throws NoSuchAlgorithmException { | |
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); | |
generator.initialize(2048); | |
KeyPair keyPair = generator.generateKeyPair(); | |
return keyPair; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment