added intentbased pg
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package com.billpaymentservice.bbps.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class EncryptionUtil {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncryptionUtil.class);
|
||||
|
||||
/**
|
||||
* Encrypts plaintext using AES/CBC/PKCS5Padding.
|
||||
* If the provided key length is not 16/24/32 bytes it will be adjusted to 16 bytes (padded/truncated).
|
||||
* NOTE: This follows the algorithm snippet provided by the user but pads/truncates the key to avoid
|
||||
* common runtime errors when key lengths are incorrect.
|
||||
*/
|
||||
public String encryptMData(String plaintext, String encryptKey) {
|
||||
try {
|
||||
// Ensure key length is 16 bytes (AES-128). If callers provide a longer key this will truncate.
|
||||
byte[] keyBytes = normalizeKey(encryptKey);
|
||||
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
|
||||
|
||||
byte[] ivBytes = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
|
||||
byte[] encryptedData = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
byte[] combinedBytes = new byte[ivBytes.length + encryptedData.length];
|
||||
System.arraycopy(ivBytes, 0, combinedBytes, 0, ivBytes.length);
|
||||
System.arraycopy(encryptedData, 0, combinedBytes, ivBytes.length, encryptedData.length);
|
||||
return Base64.getEncoder().encodeToString(combinedBytes);
|
||||
} catch (Exception e) {
|
||||
LOGGER.error("Exception in encrypt() : encryptMData- {} : Message- {}", encryptKey, e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private byte[] normalizeKey(String encryptKey) {
|
||||
if (encryptKey == null) {
|
||||
encryptKey = "";
|
||||
}
|
||||
byte[] bytes = encryptKey.getBytes(StandardCharsets.UTF_8);
|
||||
int targetLen = 16; // AES-128
|
||||
if (bytes.length == targetLen || bytes.length == 24 || bytes.length == 32) {
|
||||
return bytes;
|
||||
}
|
||||
byte[] normalized = new byte[targetLen];
|
||||
for (int i = 0; i < targetLen; i++) {
|
||||
if (i < bytes.length) {
|
||||
normalized[i] = bytes[i];
|
||||
} else {
|
||||
normalized[i] = 0; // pad with zeros
|
||||
}
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user