Encryption / Decryption of API requests / Response
Encryption of Request
Make an encryption class and follow the below steps.
Encryption using AES Algorithm with ECB Mode and PKCS5 padding:
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;
Create an Encryption Function:
try {
if (CommonUtil.isEmpty(strToEncrypt))
return "";
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
} catch (Exception e) {
LOGGER.error("Error while encrypting: " + e.getMessage());
}
return null;
}
Generate a SecretKeySpec
byte[] key = secretKey.getBytes(StandardCharsets.UTF_8);
MessageDigest sha = MessageDigest.getInstance("SHA-256");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); // Use only the first 128 bits for AES-128
return new SecretKeySpec(key, "AES");
}
String stringToEncrypt = "This is a confidential message.";
String secretKey = "YourSecretKey123";
Now pass the above encryptedData in the API request, It will return an encrypted Response. To Decrypt the response, make a method for decrypt logic like this:-
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)));
LOGGER.error("Error while decrypting: " + e.getMessage());
}
return null;
}
To get the decrypted response, execute the below operation.
String secretKey = "YourSecretKey123";
Modified at 2025-01-24 09:21:11