|
| 1 | +package com.thealgorithms.ciphers; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 5 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 6 | + |
| 7 | +import javax.crypto.SecretKey; |
| 8 | +import org.junit.jupiter.api.Test; |
| 9 | + |
| 10 | +public class AESEncryptionTest { |
| 11 | + |
| 12 | + @Test |
| 13 | + public void testGetSecretEncryptionKey() throws Exception { |
| 14 | + SecretKey key = AESEncryption.getSecretEncryptionKey(); |
| 15 | + assertNotNull(key, "Secret key should not be null"); |
| 16 | + assertEquals(128, key.getEncoded().length * 8, "Key size should be 128 bits"); |
| 17 | + } |
| 18 | + |
| 19 | + @Test |
| 20 | + public void testEncryptText() throws Exception { |
| 21 | + String plainText = "Hello World"; |
| 22 | + SecretKey secKey = AESEncryption.getSecretEncryptionKey(); |
| 23 | + byte[] cipherText = AESEncryption.encryptText(plainText, secKey); |
| 24 | + |
| 25 | + assertNotNull(cipherText, "Ciphertext should not be null"); |
| 26 | + assertTrue(cipherText.length > 0, "Ciphertext should not be empty"); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + public void testDecryptText() throws Exception { |
| 31 | + String plainText = "Hello World"; |
| 32 | + SecretKey secKey = AESEncryption.getSecretEncryptionKey(); |
| 33 | + byte[] cipherText = AESEncryption.encryptText(plainText, secKey); |
| 34 | + |
| 35 | + // Decrypt the ciphertext |
| 36 | + String decryptedText = AESEncryption.decryptText(cipherText, secKey); |
| 37 | + |
| 38 | + assertNotNull(decryptedText, "Decrypted text should not be null"); |
| 39 | + assertEquals(plainText, decryptedText, "Decrypted text should match the original plain text"); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + public void testEncryptDecrypt() throws Exception { |
| 44 | + String plainText = "Hello AES!"; |
| 45 | + SecretKey secKey = AESEncryption.getSecretEncryptionKey(); |
| 46 | + |
| 47 | + // Encrypt the plaintext |
| 48 | + byte[] cipherText = AESEncryption.encryptText(plainText, secKey); |
| 49 | + |
| 50 | + // Decrypt the ciphertext |
| 51 | + String decryptedText = AESEncryption.decryptText(cipherText, secKey); |
| 52 | + |
| 53 | + assertEquals(plainText, decryptedText, "Decrypted text should match the original plain text"); |
| 54 | + } |
| 55 | + |
| 56 | + @Test |
| 57 | + public void testBytesToHex() { |
| 58 | + byte[] bytes = new byte[] {0, 1, 15, 16, (byte) 255}; // Test with diverse byte values |
| 59 | + String hex = AESEncryption.bytesToHex(bytes); |
| 60 | + assertEquals("00010F10FF", hex, "Hex representation should match the expected value"); |
| 61 | + } |
| 62 | +} |
0 commit comments