Created
July 8, 2026 13:05
-
-
Save dex4er/3bc25c6c9934a8a462375709d91dc822 to your computer and use it in GitHub Desktop.
aes.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Converter | |
| public class AesFieldEncryptor implements AttributeConverter<String, String> { | |
| private static final String ALGO = "AES/GCM/NoPadding"; | |
| private static final int GCM_TAG_LENGTH = 128; // bits | |
| private static final int GCM_IV_LENGTH = 12; // bytes | |
| private final SecretKey secretKey; | |
| public AesFieldEncryptor() { | |
| // Klucz pobrany ze zmiennej środowiskowej, np. base64 | |
| String keyBase64 = System.getenv("APP_AES_KEY"); | |
| if (keyBase64 == null) { | |
| throw new IllegalStateException("Brak APP_AES_KEY w środowisku"); | |
| } | |
| byte[] keyBytes = Base64.getDecoder().decode(keyBase64); | |
| this.secretKey = new SecretKeySpec(keyBytes, "AES"); | |
| } | |
| @Override | |
| public String convertToDatabaseColumn(String plainText) { | |
| if (plainText == null) return null; | |
| try { | |
| byte[] iv = new byte[GCM_IV_LENGTH]; | |
| SecureRandom.getInstanceStrong().nextBytes(iv); | |
| Cipher cipher = Cipher.getInstance(ALGO); | |
| cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(GCM_TAG_LENGTH, iv)); | |
| byte[] cipherText = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8)); | |
| // Zapisujemy IV razem z ciphertextem (np. iv + tag+ct), potem base64 | |
| ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherText.length); | |
| buffer.put(iv).put(cipherText); | |
| return Base64.getEncoder().encodeToString(buffer.array()); | |
| } catch (Exception e) { | |
| throw new RuntimeException("Błąd szyfrowania pola", e); | |
| } | |
| } | |
| @Override | |
| public String convertToEntityAttribute(String dbValue) { | |
| if (dbValue == null) return null; | |
| try { | |
| byte[] decoded = Base64.getDecoder().decode(dbValue); | |
| ByteBuffer buffer = ByteBuffer.wrap(decoded); | |
| byte[] iv = new byte[GCM_IV_LENGTH]; | |
| buffer.get(iv); | |
| byte[] cipherText = new byte[buffer.remaining()]; | |
| buffer.get(cipherText); | |
| Cipher cipher = Cipher.getInstance(ALGO); | |
| cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(GCM_TAG_LENGTH, iv)); | |
| byte[] plainBytes = cipher.doFinal(cipherText); | |
| return new String(plainBytes, StandardCharsets.UTF_8); | |
| } catch (Exception e) { | |
| throw new RuntimeException("Błąd deszyfrowania pola", e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment