feat: add card number encryption utility
This commit is contained in:
@@ -12,6 +12,26 @@ services:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
app:
|
||||
build: .
|
||||
container_name: bankcards-app
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
SPRING_DATASOURCE_URL: jdbc:postgresql://postgres:5432/bankcards
|
||||
SPRING_DATASOURCE_USERNAME: postgres
|
||||
SPRING_DATASOURCE_PASSWORD: postgres
|
||||
APP_JWT_SECRET: 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
|
||||
APP_JWT_EXPIRATION: 86400000
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.example.bankcards.util;
|
||||
|
||||
import java.util.Base64;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class CardEncryptionUtil {
|
||||
|
||||
@Value("${app.card.encryption-key}")
|
||||
private String encryptionKey;
|
||||
|
||||
private static final String ALGORITHM = "AES";
|
||||
|
||||
public String encrypt(String cardNumber) {
|
||||
try {
|
||||
SecretKeySpec keySpec = new SecretKeySpec(
|
||||
encryptionKey.getBytes(),
|
||||
ALGORITHM
|
||||
);
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
|
||||
byte[] encrypted = cipher.doFinal(cardNumber.getBytes());
|
||||
return Base64.getEncoder().encodeToString(encrypted);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to encrypt card number", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String encryptedCardNumber) {
|
||||
try {
|
||||
SecretKeySpec keySpec = new SecretKeySpec(
|
||||
encryptionKey.getBytes(),
|
||||
ALGORITHM
|
||||
);
|
||||
Cipher cipher = Cipher.getInstance(ALGORITHM);
|
||||
cipher.init(Cipher.DECRYPT_MODE, keySpec);
|
||||
byte[] decoded = Base64.getDecoder().decode(encryptedCardNumber);
|
||||
byte[] decrypted = cipher.doFinal(decoded);
|
||||
return new String(decrypted);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to decrypt card number", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String mask(String cardNumber) {
|
||||
if (cardNumber == null || cardNumber.length() < 4) {
|
||||
return "****";
|
||||
}
|
||||
return (
|
||||
"**** **** **** " + cardNumber.substring(cardNumber.length() - 4)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,3 +17,5 @@ app:
|
||||
jwt:
|
||||
secret: 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970
|
||||
expiration: 86400000
|
||||
card:
|
||||
encryption-key: 1234567890123456
|
||||
|
||||
Reference in New Issue
Block a user