# Request Encryption Using AES

All API requests must be encrypted using **AES (ECB mode, PKCS5Padding)**

### <span style="color:#0a58ca">Required Imports</span>

```java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
```

### <span style="color:#0a58ca">Encrypt Function</span>

```java
public static String encrypt(String strToEncrypt, String secret) {
    try {
        if (CommonUtil.isEmpty(strToEncrypt)) return "";
        SecretKeySpec secretKeySpec = getKeySpec(secret);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    } catch (Exception e) {
        LOGGER.error("Error while encrypting: " + e.getMessage());
        return null;
    }
}
```
### <span style="color:#0a58ca">Generate SecretKeySpec</span>

```java
private static SecretKeySpec getKeySpec(String secretKey) throws NoSuchAlgorithmException {
    byte[] key = secretKey.getBytes(StandardCharsets.UTF_8);
    MessageDigest sha = MessageDigest.getInstance("SHA-256");
    key = sha.digest(key);
    key = Arrays.copyOf(key, 16); // Use first 128 bits for AES-128
    return new SecretKeySpec(key, "AES");
}
```

### <span style="color:#0a58ca">Decrypt Function</span>


```java
public static String decrypt(String strToDecrypt, String secret) {
    try {
        if (CommonUtil.isEmpty(strToDecrypt)) return "";
        SecretKeySpec secretKeySpec = getKeySpec(secret);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    } catch (Exception e) {
        LOGGER.error("Error while decrypting: " + e.getMessage());
        return null;
    }
}
```

### <span style="color:#0a58ca">Developer Tips</span>

<TipGood>Remove double quotes from plaintext before encrypting</TipGood> <TipGood> Avoid trailing whitespaces in the encrypted string</TipGood> <TipGood>Ensure encrypted payloads are passed in the correct request field (e.g., `payload`, `requestData`)</TipGood>


