|
| 1 | +// AESCryptoUtils.kt |
| 2 | +import android.util.Base64 |
| 3 | +import java.nio.charset.Charset |
| 4 | +import java.security.SecureRandom |
| 5 | +import javax.crypto.Cipher |
| 6 | +import javax.crypto.spec.GCMParameterSpec |
| 7 | +import javax.crypto.spec.SecretKeySpec |
| 8 | +import javax.crypto.KeyGenerator |
| 9 | +import javax.crypto.SecretKey |
| 10 | + |
| 11 | +object AESCryptoUtils { |
| 12 | + |
| 13 | + private const val AES_MODE = "AES/GCM/NoPadding" |
| 14 | + private const val IV_SIZE = 12 |
| 15 | + private const val TAG_LENGTH = 128 |
| 16 | + |
| 17 | + /** |
| 18 | + * Generates an AES encryption key of specified size. |
| 19 | + * |
| 20 | + * @param keySize The size of the AES key in bits (128, 192, or 256). |
| 21 | + * @return A Base64-encoded AES key. |
| 22 | + * @throws IllegalArgumentException if the key size is invalid. |
| 23 | + * @throws Exception if key generation fails. |
| 24 | + */ |
| 25 | + @Throws(IllegalArgumentException::class) |
| 26 | + fun generateAESKey(keySize: Double): String { |
| 27 | + val validKeySizes = setOf(128, 192, 256) |
| 28 | + if (keySize.toInt() !in validKeySizes) { |
| 29 | + throw IllegalArgumentException("Invalid AES key size. Must be 128, 192, or 256 bits.") |
| 30 | + } |
| 31 | + |
| 32 | + return try { |
| 33 | + val keyGenerator = KeyGenerator.getInstance("AES") |
| 34 | + keyGenerator.init(keySize.toInt()) |
| 35 | + val secretKey: SecretKey = keyGenerator.generateKey() |
| 36 | + val keyBytes = secretKey.encoded |
| 37 | + Base64.encodeToString(keyBytes, Base64.DEFAULT) |
| 38 | + } catch (e: Exception) { |
| 39 | + throw IllegalArgumentException("Failed to generate AES key: ${e.localizedMessage}", e) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Encrypts the given plaintext using AES-GCM. |
| 45 | + * |
| 46 | + * @param data Plaintext string to encrypt. |
| 47 | + * @param key AES key in Base64 format. |
| 48 | + * @return Encrypted string in Base64 format with IV prepended. |
| 49 | + */ |
| 50 | + @Throws(IllegalArgumentException::class, Exception::class) |
| 51 | + fun encrypt(data: String, key: String): String { |
| 52 | + if (data.isEmpty() || key.isEmpty()) { |
| 53 | + throw IllegalArgumentException("Data or key cannot be empty.") |
| 54 | + } |
| 55 | + |
| 56 | + val keyBytes = |
| 57 | + try { |
| 58 | + Base64.decode(key, Base64.DEFAULT) |
| 59 | + } catch (e: Exception) { |
| 60 | + throw IllegalArgumentException("Invalid AES key format: ${e.localizedMessage}") |
| 61 | + } |
| 62 | + if (keyBytes.size !in listOf(16, 24, 32)) { |
| 63 | + throw IllegalArgumentException("Invalid AES key size. Must be 16, 24, or 32 bytes (128, 192, or 256 bits).") |
| 64 | + } |
| 65 | + |
| 66 | + // Generate Initialization Vector (IV) |
| 67 | + val iv = ByteArray(IV_SIZE) |
| 68 | + SecureRandom().nextBytes(iv) |
| 69 | + val ivSpec = GCMParameterSpec(TAG_LENGTH, iv) |
| 70 | + |
| 71 | + // Initialize Cipher |
| 72 | + val secretKey = SecretKeySpec(keyBytes, "AES") |
| 73 | + val cipher = Cipher.getInstance(AES_MODE) |
| 74 | + cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec) |
| 75 | + |
| 76 | + // Encrypt data |
| 77 | + val encryptedData = cipher.doFinal(data.toByteArray(Charsets.UTF_8)) |
| 78 | + |
| 79 | + // Combine IV and Encrypted Data |
| 80 | + val combined = iv + encryptedData |
| 81 | + |
| 82 | + // Encode as Base64 |
| 83 | + return Base64.encodeToString(combined, Base64.DEFAULT) |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Decrypts the given AES-GCM encrypted string. |
| 88 | + * |
| 89 | + * @param data Encrypted data in Base64 format (with IV prepended). |
| 90 | + * @param key AES key in Base64 format. |
| 91 | + * @return Decrypted plaintext string. |
| 92 | + */ |
| 93 | + @Throws(IllegalArgumentException::class, Exception::class) |
| 94 | + fun decrypt(data: String, key: String): String { |
| 95 | + if (data.isEmpty() || key.isEmpty()) { |
| 96 | + throw IllegalArgumentException("Data or key cannot be empty.") |
| 97 | + } |
| 98 | + |
| 99 | + val keyBytes = Base64.decode(key, Base64.DEFAULT) |
| 100 | + if (keyBytes.size !in listOf(16, 24, 32)) { |
| 101 | + throw IllegalArgumentException("Invalid AES key size. Must be 16, 24, or 32 bytes (128, 192, or 256 bits).") |
| 102 | + } |
| 103 | + |
| 104 | + val decodedData = Base64.decode(data, Base64.DEFAULT) |
| 105 | + if (decodedData.size < IV_SIZE) { |
| 106 | + throw IllegalArgumentException("Invalid encrypted data. Data too short to contain IV.") |
| 107 | + } |
| 108 | + |
| 109 | + // Extract IV and Encrypted Data |
| 110 | + val iv = decodedData.copyOfRange(0, IV_SIZE) |
| 111 | + val encryptedBytes = decodedData.copyOfRange(IV_SIZE, decodedData.size) |
| 112 | + val ivSpec = GCMParameterSpec(TAG_LENGTH, iv) |
| 113 | + |
| 114 | + // Initialize Cipher |
| 115 | + val secretKey = SecretKeySpec(keyBytes, "AES") |
| 116 | + val cipher = Cipher.getInstance(AES_MODE) |
| 117 | + cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec) |
| 118 | + |
| 119 | + // Decrypt data |
| 120 | + val decryptedData = cipher.doFinal(encryptedBytes) |
| 121 | + return String(decryptedData, Charsets.UTF_8) |
| 122 | + } |
| 123 | + |
| 124 | +/** |
| 125 | + * Encrypt ByteArray directly (e.g., for file encryption). |
| 126 | + */ |
| 127 | +@Throws(Exception::class) |
| 128 | +fun encryptBytes(data: ByteArray, key: String): ByteArray { |
| 129 | + val keyBytes = Base64.decode(key, Base64.DEFAULT) |
| 130 | + val secretKey = SecretKeySpec(keyBytes, "AES") |
| 131 | + val iv = ByteArray(12) |
| 132 | + SecureRandom().nextBytes(iv) |
| 133 | + |
| 134 | + val cipher = Cipher.getInstance("AES/GCM/NoPadding") |
| 135 | + cipher.init(Cipher.ENCRYPT_MODE, secretKey, GCMParameterSpec(128, iv)) |
| 136 | + |
| 137 | + val encryptedData = cipher.doFinal(data) |
| 138 | + return iv + encryptedData |
| 139 | +} |
| 140 | + |
| 141 | +/** |
| 142 | + * Decrypt ByteArray directly (e.g., for file decryption). |
| 143 | + */ |
| 144 | +@Throws(Exception::class) |
| 145 | +fun decryptBytes(data: ByteArray, key: String): ByteArray { |
| 146 | + val keyBytes = Base64.decode(key, Base64.DEFAULT) |
| 147 | + val secretKey = SecretKeySpec(keyBytes, "AES") |
| 148 | + |
| 149 | + val iv = data.copyOfRange(0, 12) |
| 150 | + val encryptedData = data.copyOfRange(12, data.size) |
| 151 | + |
| 152 | + val cipher = Cipher.getInstance("AES/GCM/NoPadding") |
| 153 | + cipher.init(Cipher.DECRYPT_MODE, secretKey, GCMParameterSpec(128, iv)) |
| 154 | + |
| 155 | + return cipher.doFinal(encryptedData) |
| 156 | +} |
| 157 | +} |
0 commit comments