.
This commit is contained in:
@@ -10,6 +10,7 @@ import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
@@ -27,13 +28,25 @@ public class EncryptionService {
|
||||
if (secretKeyBase64 != null && !secretKeyBase64.isEmpty()) {
|
||||
try {
|
||||
byte[] keyBytes = Base64.getDecoder().decode(secretKeyBase64);
|
||||
key = new SecretKeySpec(keyBytes, ALGORITHM);
|
||||
// If decoded key is exactly 32 bytes (256 bits), use it directly
|
||||
// Otherwise, derive a 32-byte key using SHA-256
|
||||
if (keyBytes.length == 32) {
|
||||
key = new SecretKeySpec(keyBytes, ALGORITHM);
|
||||
} else {
|
||||
// Derive a proper 32-byte key using SHA-256
|
||||
MessageDigest sha = MessageDigest.getInstance("SHA-256");
|
||||
byte[] derivedKey = sha.digest(keyBytes);
|
||||
key = new SecretKeySpec(derivedKey, ALGORITHM);
|
||||
logger.info("Derived AES-256 key from provided secret (original length: {} bytes)",
|
||||
keyBytes.length);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("Failed to decode encryption key from config, generating new one", e);
|
||||
key = generateKey();
|
||||
}
|
||||
} else {
|
||||
logger.warn("Encryption secret key not configured, generating temporary key. This should be configured in production!");
|
||||
logger.warn(
|
||||
"Encryption secret key not configured, generating temporary key. This should be configured in production!");
|
||||
key = generateKey();
|
||||
}
|
||||
this.secretKey = key;
|
||||
@@ -82,4 +95,3 @@ public class EncryptionService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user