From 1adb69266182ed7b33139e4f0edb1b65ff5efe3c Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Wed, 16 Sep 2026 12:30:30 +0900 Subject: [PATCH] =?UTF-8?q?260916=5F01=5FENH:=20=EA=B3=B5=ED=86=B5=20?= =?UTF-8?q?=EC=95=94=ED=98=B8=ED=99=94=20=EB=B0=8F=20=ED=95=B4=EC=8B=9C=20?= =?UTF-8?q?=EA=B8=B0=EB=8A=A5=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .agent/consumer.md | 6 +- AGENTS.md | 6 +- README.md | 100 ++++++ build.gradle | 2 +- .../crypto/CryptoAutoConfiguration.java | 38 +++ .../crypto/CryptoProperties.java | 54 +++ .../crypto/CryptoAuthenticationException.java | 11 + .../feature/crypto/CryptoException.java | 15 + .../crypto/CryptoKeyNotFoundException.java | 11 + .../feature/crypto/aes/AesAlgorithm.java | 36 ++ .../feature/crypto/aes/AesCryptoService.java | 28 ++ .../feature/crypto/aes/AesDecryptRequest.java | 65 ++++ .../feature/crypto/aes/AesEncryptRequest.java | 144 ++++++++ .../feature/crypto/aes/AesEncryptedValue.java | 88 +++++ .../crypto/aes/AesEncryptedValueCodec.java | 79 +++++ .../common/feature/crypto/aes/TagLayout.java | 13 + .../crypto/hash/AdaptiveHashService.java | 13 + .../feature/crypto/hash/DigestAlgorithm.java | 29 ++ .../feature/crypto/hash/DigestEncoding.java | 10 + .../feature/crypto/hash/DigestRequest.java | 61 ++++ .../feature/crypto/hash/DigestService.java | 45 +++ .../crypto/aes/DefaultAesCryptoService.java | 321 ++++++++++++++++++ .../hash/BCryptAdaptiveHashService.java | 53 +++ .../runtime/crypto/hash/JdkDigestService.java | 59 ++++ ...ot.autoconfigure.AutoConfiguration.imports | 1 + 25 files changed, 1285 insertions(+), 3 deletions(-) create mode 100644 src/main/java/com/kri/common/autoconfigure/crypto/CryptoAutoConfiguration.java create mode 100644 src/main/java/com/kri/common/autoconfigure/crypto/CryptoProperties.java create mode 100644 src/main/java/com/kri/common/feature/crypto/CryptoAuthenticationException.java create mode 100644 src/main/java/com/kri/common/feature/crypto/CryptoException.java create mode 100644 src/main/java/com/kri/common/feature/crypto/CryptoKeyNotFoundException.java create mode 100644 src/main/java/com/kri/common/feature/crypto/aes/AesAlgorithm.java create mode 100644 src/main/java/com/kri/common/feature/crypto/aes/AesCryptoService.java create mode 100644 src/main/java/com/kri/common/feature/crypto/aes/AesDecryptRequest.java create mode 100644 src/main/java/com/kri/common/feature/crypto/aes/AesEncryptRequest.java create mode 100644 src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValue.java create mode 100644 src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValueCodec.java create mode 100644 src/main/java/com/kri/common/feature/crypto/aes/TagLayout.java create mode 100644 src/main/java/com/kri/common/feature/crypto/hash/AdaptiveHashService.java create mode 100644 src/main/java/com/kri/common/feature/crypto/hash/DigestAlgorithm.java create mode 100644 src/main/java/com/kri/common/feature/crypto/hash/DigestEncoding.java create mode 100644 src/main/java/com/kri/common/feature/crypto/hash/DigestRequest.java create mode 100644 src/main/java/com/kri/common/feature/crypto/hash/DigestService.java create mode 100644 src/main/java/com/kri/common/runtime/crypto/aes/DefaultAesCryptoService.java create mode 100644 src/main/java/com/kri/common/runtime/crypto/hash/BCryptAdaptiveHashService.java create mode 100644 src/main/java/com/kri/common/runtime/crypto/hash/JdkDigestService.java diff --git a/.agent/consumer.md b/.agent/consumer.md index b82895a..dc4fb64 100644 --- a/.agent/consumer.md +++ b/.agent/consumer.md @@ -9,7 +9,7 @@ ### Configuration and Overrides -- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`. +- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.crypto`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`. - Read the version-matched README and configuration-property classes before setting a property; do not infer a property name or default from an older service. - Supply production JWT secrets, API keys, credentials, allowlists, and service URLs through the consumer's approved secret and configuration system. Never rely on library example or default secrets in production. - Preserve consumer override points. KriCommon's default security chain is created only when the consumer does not provide one, and overridable beans should remain explicit. @@ -26,6 +26,10 @@ - `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes. - Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply. - `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics. +- Crypto APIs are under `com.kri.common.feature.crypto.*` and do not use a central key database. AES uses PBKDF2-HMAC-SHA256 key derivation with salt and defaults to AES-256-GCM; callers may supply a master key, salt, IV, AAD, and detached or appended GCM tag representation for legacy interoperability. +- `kri.crypto.aes.keys` and per-call master keys are supported operational compromises. Never log them or commit real values. Per-call key material takes precedence over configured keys, and encrypted values retain key ID and KDF metadata for decryption compatibility. +- AES-GCM always requires its authentication tag. Use `AES_256_CBC_PKCS5` only for explicitly identified legacy data that has no tag, and do not treat CBC as authenticated encryption. +- `DigestService` supports SHA-256/SHA-512 plus legacy-only MD5/SHA-1. `AdaptiveHashService` uses BCrypt for short secrets; do not use MD5, SHA-1, or a fast digest for new password or secret storage. ### Project Instruction Budget diff --git a/AGENTS.md b/AGENTS.md index 292c0a9..89ad28d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -224,7 +224,7 @@ When implementation is complete, report in Korean: ### Configuration and Overrides -- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`. +- KriCommon configuration uses only `kri.*`. Established groups include `kri.auth.jwt`, `kri.auth.apikey`, `kri.crypto`, `kri.security`, `kri.swagger`, `kri.web`, `kri.web.mdc`, `kri.http.bypass`, `kri.redis`, `kri.scheduling`, and `kri.error.expose`. - Read the version-matched README and configuration-property classes before setting a property; do not infer a property name or default from an older service. - Supply production JWT secrets, API keys, credentials, allowlists, and service URLs through the consumer's approved secret and configuration system. Never rely on library example or default secrets in production. - Preserve consumer override points. KriCommon's default security chain is created only when the consumer does not provide one, and overridable beans should remain explicit. @@ -241,6 +241,10 @@ When implementation is complete, report in Korean: - `ExternalApiClient` multipart requests generate their own boundary and ignore a caller-supplied `Content-Type`. Multipart headers and `formField` values use UTF-8, while file bodies preserve the supplied bytes. - Multipart filenames, including non-ASCII names, are sent unchanged in the quoted `filename` parameter as raw UTF-8. No ASCII fallback or `filename*` parameter is added; CR/LF rejection and quote/backslash escaping still apply. - `JsonUtil` requires the consumer's explicit `ObjectMapper`; shared date/time helpers define KST as `Asia/Seoul` and also expose UTC semantics. +- Crypto APIs are under `com.kri.common.feature.crypto.*` and do not use a central key database. AES uses PBKDF2-HMAC-SHA256 key derivation with salt and defaults to AES-256-GCM; callers may supply a master key, salt, IV, AAD, and detached or appended GCM tag representation for legacy interoperability. +- `kri.crypto.aes.keys` and per-call master keys are supported operational compromises. Never log them or commit real values. Per-call key material takes precedence over configured keys, and encrypted values retain key ID and KDF metadata for decryption compatibility. +- AES-GCM always requires its authentication tag. Use `AES_256_CBC_PKCS5` only for explicitly identified legacy data that has no tag, and do not treat CBC as authenticated encryption. +- `DigestService` supports SHA-256/SHA-512 plus legacy-only MD5/SHA-1. `AdaptiveHashService` uses BCrypt for short secrets; do not use MD5, SHA-1, or a fast digest for new password or secret storage. ### Project Instruction Budget diff --git a/README.md b/README.md index 2eb24ea..760bef5 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,77 @@ BypassResponse response = bypassClient.forward( `Host`, `Content-Length`, `Transfer-Encoding`, `Connection` 같은 hop-by-hop header는 전달하지 않습니다. +### 암호화와 해시 + +공개 API는 `com.kri.common.feature.crypto.*`에 있습니다. 중앙 키 DB를 사용하지 않으며, +AES master key는 `kri.crypto.aes.keys` 설정 또는 각 호출의 `masterKey`로 전달합니다. + +#### AES-256 + +기본 알고리즘은 인증 암호화인 `AES_256_GCM`입니다. `masterKey`와 salt를 +`PBKDF2WithHmacSHA256`으로 처리해 256-bit AES key를 만들며, salt와 IV를 생략하면 +안전한 난수로 자동 생성합니다. 기존 시스템 연동을 위해 salt와 IV를 직접 전달할 수도 있습니다. + +```java +import com.kri.common.feature.crypto.aes.AesCryptoService; +import com.kri.common.feature.crypto.aes.AesDecryptRequest; +import com.kri.common.feature.crypto.aes.AesEncryptRequest; +import com.kri.common.feature.crypto.aes.AesEncryptedValue; +import com.kri.common.feature.crypto.aes.AesEncryptedValueCodec; +import com.kri.common.feature.crypto.aes.TagLayout; + +AesEncryptedValue encrypted = aesCryptoService.encrypt( + AesEncryptRequest.builder(plainBytes) + .masterKey(masterKey) + .salt(salt) + .iv(iv) + .aad(aad) + .tagLayout(TagLayout.DETACHED) + .build() +); + +String storedValue = AesEncryptedValueCodec.encode(encrypted); +AesEncryptedValue decoded = AesEncryptedValueCodec.decode(storedValue); +byte[] restored = aesCryptoService.decrypt( + AesDecryptRequest.builder(decoded) + .masterKey(masterKey) + .aad(aad) + .build() +); +``` + +- GCM tag는 ciphertext 결합형 `APPENDED` 또는 별도 필드형 `DETACHED`를 지원합니다. +- GCM tag는 생략할 수 없습니다. tag가 없는 기존 데이터는 명시적으로 + `AES_256_CBC_PKCS5`를 선택해야 하며, CBC는 변조를 감지하지 못하므로 신규 데이터에 권장하지 않습니다. +- GCM IV는 12바이트, CBC IV는 16바이트이고 salt는 최소 16바이트입니다. +- 호출자가 IV를 직접 전달하면 동일한 key에서 IV가 중복되지 않도록 호출 서비스가 보장해야 합니다. +- AAD는 GCM에서만 지원하며 복호화할 때 암호화 시점과 동일한 값을 전달해야 합니다. +- 암호화 결과는 format version, algorithm, key ID, KDF iteration, salt, IV, ciphertext 및 tag 정보를 포함합니다. + +#### 일반 digest와 BCrypt + +```java +import com.kri.common.feature.crypto.hash.AdaptiveHashService; +import com.kri.common.feature.crypto.hash.DigestAlgorithm; +import com.kri.common.feature.crypto.hash.DigestEncoding; +import com.kri.common.feature.crypto.hash.DigestService; + +String checksum = digestService.digest( + bytes, + DigestAlgorithm.SHA_256, + DigestEncoding.HEX_LOWER +); + +String encodedSecret = adaptiveHashService.hash("secret-value"); +boolean matched = adaptiveHashService.matches("secret-value", encodedSecret); +``` + +`DigestService`는 MD5, SHA-1, SHA-256, SHA-512와 HEX 소문자/대문자, Base64 출력을 지원합니다. +MD5와 SHA-1 enum 이름은 각각 `MD5_LEGACY`, `SHA_1_LEGACY`이며 기존 데이터 검증과 +연동에만 사용해야 합니다. `AdaptiveHashService`는 BCrypt 기반이며 비밀번호뿐 아니라 PIN, +복구 코드, API Secret 같은 짧은 비밀값 검증에 사용할 수 있습니다. BCrypt 결과에는 salt가 +포함되며 일반적인 구현의 72바이트 입력 제한을 고려해야 합니다. + ### JSON #### `JsonUtil` @@ -497,6 +568,19 @@ kri: jpa: show-sql: false format-sql: false + crypto: + aes: + active-key-id: "key-2026" + keys: + key-2026: "replace-with-a-service-master-key" + algorithm: AES_256_GCM + tag-layout: APPENDED + kdf: + iterations: 600000 + salt-length: 16 + hash: + bcrypt: + strength: 12 security: enabled: true allowed-ips: @@ -532,6 +616,20 @@ kri: 운영 서비스에서는 JWT secret, API Key DB 접속 정보, Swagger/API Key admin 허용 IP를 반드시 서비스 환경에 맞게 override해야 합니다. +### `kri.crypto` + +- `aes.active-key-id`: 직접 master key를 전달하지 않았을 때 사용할 key ID +- `aes.keys`: key ID별 master key. 복호화 호환을 위해 교체 전 key도 필요한 기간 동안 유지 +- `aes.algorithm`: 기본값 `AES_256_GCM` +- `aes.tag-layout`: 기본값 `APPENDED` +- `aes.kdf.iterations`: PBKDF2 반복 횟수, 기본값 `600000` +- `aes.kdf.salt-length`: 자동 생성 salt 길이, 기본값 `16` +- `hash.bcrypt.strength`: 기본 BCrypt cost, 기본값 `12`, 허용 범위 `4..31` + +`kri.crypto.enabled` 설정은 없습니다. Crypto API Bean은 항상 자동 구성되며, YML 키가 없어도 +호출 시 master key를 직접 전달할 수 있습니다. 설정과 호출 양쪽에 키가 있으면 직접 전달한 키가 +우선합니다. master key를 소스에 커밋하거나 로그와 예외에 출력하지 마십시오. + ### `kri.auth.jwt` 관련 클래스: @@ -753,6 +851,7 @@ Endpoint: - `com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration` - `com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration` - `com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration` +- `com.kri.common.autoconfigure.crypto.CryptoAutoConfiguration` --- @@ -761,6 +860,7 @@ Endpoint: - 서비스 코드에서는 가능한 한 `feature` 패키지의 타입만 직접 사용합니다. - `runtime` 패키지는 자동 구성으로 조립되는 내부 구현으로 보고 직접 의존을 피합니다. - 운영 환경에서는 기본 JWT secret과 API Key DB 설정을 사용하지 않습니다. +- AES 신규 데이터는 GCM을 사용하고, MD5·SHA-1·AES-CBC는 레거시 호환 범위로 제한합니다. - 자체 보안 정책이 필요한 서비스는 직접 `SecurityFilterChain` Bean을 등록해 기본 구성을 대체합니다. - Swagger 접근 제한은 운영망/관리망 정책에 맞춰 `allowed-ips`를 명시합니다. - 대용량 Excel은 일반 `Workbook` 변환보다 streaming API를 우선 검토합니다. diff --git a/build.gradle b/build.gradle index d124084..c40da10 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ plugins { } // 버전 변경은 여기서 -def commonVer = "beta.1.6.5" +def commonVer = "beta.1.6.6" group = 'com.kri.common' version = commonVer diff --git a/src/main/java/com/kri/common/autoconfigure/crypto/CryptoAutoConfiguration.java b/src/main/java/com/kri/common/autoconfigure/crypto/CryptoAutoConfiguration.java new file mode 100644 index 0000000..541dc36 --- /dev/null +++ b/src/main/java/com/kri/common/autoconfigure/crypto/CryptoAutoConfiguration.java @@ -0,0 +1,38 @@ +package com.kri.common.autoconfigure.crypto; + +import com.kri.common.feature.crypto.aes.AesCryptoService; +import com.kri.common.feature.crypto.hash.AdaptiveHashService; +import com.kri.common.feature.crypto.hash.DigestService; +import com.kri.common.runtime.crypto.aes.DefaultAesCryptoService; +import com.kri.common.runtime.crypto.hash.BCryptAdaptiveHashService; +import com.kri.common.runtime.crypto.hash.JdkDigestService; +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +@AutoConfiguration +@EnableConfigurationProperties(CryptoProperties.class) +public class CryptoAutoConfiguration { + + @Bean + @ConditionalOnMissingBean(AesCryptoService.class) + public AesCryptoService aesCryptoService(CryptoProperties properties) { + return new DefaultAesCryptoService(properties); + } + + @Bean + @ConditionalOnMissingBean(DigestService.class) + public DigestService digestService() { + return new JdkDigestService(); + } + + @Bean + @ConditionalOnClass(BCryptPasswordEncoder.class) + @ConditionalOnMissingBean(AdaptiveHashService.class) + public AdaptiveHashService adaptiveHashService(CryptoProperties properties) { + return new BCryptAdaptiveHashService(properties.getHash().getBcrypt().getStrength()); + } +} diff --git a/src/main/java/com/kri/common/autoconfigure/crypto/CryptoProperties.java b/src/main/java/com/kri/common/autoconfigure/crypto/CryptoProperties.java new file mode 100644 index 0000000..980c6f9 --- /dev/null +++ b/src/main/java/com/kri/common/autoconfigure/crypto/CryptoProperties.java @@ -0,0 +1,54 @@ +package com.kri.common.autoconfigure.crypto; + +import com.kri.common.feature.crypto.aes.AesAlgorithm; +import com.kri.common.feature.crypto.aes.TagLayout; +import java.util.LinkedHashMap; +import java.util.Map; +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; + +@Getter +@Setter +@ConfigurationProperties(prefix = "kri.crypto") +public class CryptoProperties { + + private Aes aes = new Aes(); + private Hash hash = new Hash(); + + @Getter + @Setter + public static class Aes { + /** 직접 master key를 전달하지 않았을 때 사용할 key ID입니다. */ + private String activeKeyId; + /** key ID별 master key입니다. 실제 값은 로그나 소스 관리에 노출하지 않아야 합니다. */ + private Map keys = new LinkedHashMap<>(); + /** 기본 AES 알고리즘입니다. */ + private AesAlgorithm algorithm = AesAlgorithm.AES_256_GCM; + /** AES-GCM 인증 태그의 기본 저장 형태입니다. */ + private TagLayout tagLayout = TagLayout.APPENDED; + private Kdf kdf = new Kdf(); + } + + @Getter + @Setter + public static class Kdf { + /** PBKDF2-HMAC-SHA256 반복 횟수입니다. */ + private int iterations = 600_000; + /** 자동 생성하는 salt 길이(byte)입니다. 최소 16입니다. */ + private int saltLength = 16; + } + + @Getter + @Setter + public static class Hash { + private Bcrypt bcrypt = new Bcrypt(); + } + + @Getter + @Setter + public static class Bcrypt { + /** BCrypt cost입니다. 허용 범위는 4부터 31까지입니다. */ + private int strength = 12; + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/CryptoAuthenticationException.java b/src/main/java/com/kri/common/feature/crypto/CryptoAuthenticationException.java new file mode 100644 index 0000000..eee895d --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/CryptoAuthenticationException.java @@ -0,0 +1,11 @@ +package com.kri.common.feature.crypto; + +/** + * 암호문 인증 실패, 잘못된 키 또는 잘못된 AAD로 복호화할 수 없을 때 발생합니다. + */ +public class CryptoAuthenticationException extends CryptoException { + + public CryptoAuthenticationException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/CryptoException.java b/src/main/java/com/kri/common/feature/crypto/CryptoException.java new file mode 100644 index 0000000..1d096c0 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/CryptoException.java @@ -0,0 +1,15 @@ +package com.kri.common.feature.crypto; + +/** + * 암호화, 복호화 또는 해시 처리 중 발생하는 공통 예외입니다. + */ +public class CryptoException extends RuntimeException { + + public CryptoException(String message) { + super(message); + } + + public CryptoException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/CryptoKeyNotFoundException.java b/src/main/java/com/kri/common/feature/crypto/CryptoKeyNotFoundException.java new file mode 100644 index 0000000..cee14b2 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/CryptoKeyNotFoundException.java @@ -0,0 +1,11 @@ +package com.kri.common.feature.crypto; + +/** + * 요청한 암호화 키를 찾을 수 없을 때 발생합니다. + */ +public class CryptoKeyNotFoundException extends CryptoException { + + public CryptoKeyNotFoundException(String message) { + super(message); + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/aes/AesAlgorithm.java b/src/main/java/com/kri/common/feature/crypto/aes/AesAlgorithm.java new file mode 100644 index 0000000..1498601 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/aes/AesAlgorithm.java @@ -0,0 +1,36 @@ +package com.kri.common.feature.crypto.aes; + +/** + * 지원하는 AES 알고리즘입니다. + */ +public enum AesAlgorithm { + /** 인증 암호화 기본값입니다. */ + AES_256_GCM("AES/GCM/NoPadding", 12, true), + + /** + * 인증 태그가 없는 레거시 호환 모드입니다. 신규 데이터에는 {@link #AES_256_GCM}을 사용하십시오. + */ + AES_256_CBC_PKCS5("AES/CBC/PKCS5Padding", 16, false); + + private final String transformation; + private final int ivLength; + private final boolean authenticated; + + AesAlgorithm(String transformation, int ivLength, boolean authenticated) { + this.transformation = transformation; + this.ivLength = ivLength; + this.authenticated = authenticated; + } + + public String getTransformation() { + return transformation; + } + + public int getIvLength() { + return ivLength; + } + + public boolean isAuthenticated() { + return authenticated; + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/aes/AesCryptoService.java b/src/main/java/com/kri/common/feature/crypto/aes/AesCryptoService.java new file mode 100644 index 0000000..51b57cf --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/aes/AesCryptoService.java @@ -0,0 +1,28 @@ +package com.kri.common.feature.crypto.aes; + +import java.nio.charset.StandardCharsets; + +/** + * AES 양방향 암호화 공개 API입니다. + */ +public interface AesCryptoService { + + AesEncryptedValue encrypt(byte[] plaintext); + + AesEncryptedValue encrypt(AesEncryptRequest request); + + byte[] decrypt(AesEncryptedValue encryptedValue); + + byte[] decrypt(AesDecryptRequest request); + + default AesEncryptedValue encryptUtf8(String plaintext) { + if (plaintext == null) { + throw new IllegalArgumentException("plaintext must not be null"); + } + return encrypt(plaintext.getBytes(StandardCharsets.UTF_8)); + } + + default String decryptUtf8(AesEncryptedValue encryptedValue) { + return new String(decrypt(encryptedValue), StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/aes/AesDecryptRequest.java b/src/main/java/com/kri/common/feature/crypto/aes/AesDecryptRequest.java new file mode 100644 index 0000000..1080eb0 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/aes/AesDecryptRequest.java @@ -0,0 +1,65 @@ +package com.kri.common.feature.crypto.aes; + +import java.util.Arrays; + +/** + * AES 복호화 요청입니다. masterKey를 생략하면 암호문의 keyId에 해당하는 설정 키를 사용합니다. + */ +public final class AesDecryptRequest { + + private final AesEncryptedValue encryptedValue; + private final char[] masterKey; + private final byte[] aad; + + private AesDecryptRequest(Builder builder) { + this.encryptedValue = builder.encryptedValue; + this.masterKey = builder.masterKey == null + ? null : Arrays.copyOf(builder.masterKey, builder.masterKey.length); + this.aad = builder.aad == null ? null : Arrays.copyOf(builder.aad, builder.aad.length); + } + + public static Builder builder(AesEncryptedValue encryptedValue) { + return new Builder(encryptedValue); + } + + public AesEncryptedValue getEncryptedValue() { + return encryptedValue; + } + + public char[] getMasterKey() { + return masterKey == null ? null : Arrays.copyOf(masterKey, masterKey.length); + } + + public byte[] getAad() { + return aad == null ? null : Arrays.copyOf(aad, aad.length); + } + + public static final class Builder { + private final AesEncryptedValue encryptedValue; + private char[] masterKey; + private byte[] aad; + + private Builder(AesEncryptedValue encryptedValue) { + this.encryptedValue = encryptedValue; + } + + public Builder masterKey(char[] masterKey) { + this.masterKey = masterKey == null ? null : Arrays.copyOf(masterKey, masterKey.length); + return this; + } + + public Builder masterKey(String masterKey) { + this.masterKey = masterKey == null ? null : masterKey.toCharArray(); + return this; + } + + public Builder aad(byte[] aad) { + this.aad = aad == null ? null : Arrays.copyOf(aad, aad.length); + return this; + } + + public AesDecryptRequest build() { + return new AesDecryptRequest(this); + } + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptRequest.java b/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptRequest.java new file mode 100644 index 0000000..d374c3b --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptRequest.java @@ -0,0 +1,144 @@ +package com.kri.common.feature.crypto.aes; + +import java.util.Arrays; + +/** + * AES 암호화 요청입니다. masterKey, salt, IV를 직접 전달하지 않으면 설정값 또는 안전한 난수를 사용합니다. + */ +public final class AesEncryptRequest { + + private final byte[] plaintext; + private final char[] masterKey; + private final byte[] salt; + private final byte[] iv; + private final byte[] aad; + private final String keyId; + private final AesAlgorithm algorithm; + private final TagLayout tagLayout; + private final Integer kdfIterations; + + private AesEncryptRequest(Builder builder) { + this.plaintext = copy(builder.plaintext); + this.masterKey = copy(builder.masterKey); + this.salt = copy(builder.salt); + this.iv = copy(builder.iv); + this.aad = copy(builder.aad); + this.keyId = builder.keyId; + this.algorithm = builder.algorithm; + this.tagLayout = builder.tagLayout; + this.kdfIterations = builder.kdfIterations; + } + + public static Builder builder(byte[] plaintext) { + return new Builder(plaintext); + } + + public byte[] getPlaintext() { + return copy(plaintext); + } + + public char[] getMasterKey() { + return copy(masterKey); + } + + public byte[] getSalt() { + return copy(salt); + } + + public byte[] getIv() { + return copy(iv); + } + + public byte[] getAad() { + return copy(aad); + } + + public String getKeyId() { + return keyId; + } + + public AesAlgorithm getAlgorithm() { + return algorithm; + } + + public TagLayout getTagLayout() { + return tagLayout; + } + + public Integer getKdfIterations() { + return kdfIterations; + } + + private static byte[] copy(byte[] value) { + return value == null ? null : Arrays.copyOf(value, value.length); + } + + private static char[] copy(char[] value) { + return value == null ? null : Arrays.copyOf(value, value.length); + } + + public static final class Builder { + private final byte[] plaintext; + private char[] masterKey; + private byte[] salt; + private byte[] iv; + private byte[] aad; + private String keyId; + private AesAlgorithm algorithm; + private TagLayout tagLayout; + private Integer kdfIterations; + + private Builder(byte[] plaintext) { + this.plaintext = copy(plaintext); + } + + public Builder masterKey(char[] masterKey) { + this.masterKey = copy(masterKey); + return this; + } + + public Builder masterKey(String masterKey) { + this.masterKey = masterKey == null ? null : masterKey.toCharArray(); + return this; + } + + public Builder salt(byte[] salt) { + this.salt = copy(salt); + return this; + } + + public Builder iv(byte[] iv) { + this.iv = copy(iv); + return this; + } + + public Builder aad(byte[] aad) { + this.aad = copy(aad); + return this; + } + + public Builder keyId(String keyId) { + this.keyId = keyId; + return this; + } + + public Builder algorithm(AesAlgorithm algorithm) { + this.algorithm = algorithm; + return this; + } + + public Builder tagLayout(TagLayout tagLayout) { + this.tagLayout = tagLayout; + return this; + } + + public Builder kdfIterations(int kdfIterations) { + this.kdfIterations = kdfIterations; + return this; + } + + public AesEncryptRequest build() { + return new AesEncryptRequest(this); + } + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValue.java b/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValue.java new file mode 100644 index 0000000..2242fcc --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValue.java @@ -0,0 +1,88 @@ +package com.kri.common.feature.crypto.aes; + +import java.util.Arrays; + +/** + * 복호화와 키 교체에 필요한 메타데이터를 포함한 AES 암호화 결과입니다. + */ +public final class AesEncryptedValue { + + public static final String CURRENT_FORMAT_VERSION = "v1"; + public static final String KDF_ALGORITHM = "PBKDF2_WITH_HMAC_SHA256"; + + private final String formatVersion; + private final AesAlgorithm algorithm; + private final String keyId; + private final int kdfIterations; + private final byte[] salt; + private final byte[] iv; + private final byte[] ciphertext; + private final byte[] tag; + private final TagLayout tagLayout; + + public AesEncryptedValue( + String formatVersion, + AesAlgorithm algorithm, + String keyId, + int kdfIterations, + byte[] salt, + byte[] iv, + byte[] ciphertext, + byte[] tag, + TagLayout tagLayout + ) { + this.formatVersion = formatVersion; + this.algorithm = algorithm; + this.keyId = keyId; + this.kdfIterations = kdfIterations; + this.salt = copy(salt); + this.iv = copy(iv); + this.ciphertext = copy(ciphertext); + this.tag = copy(tag); + this.tagLayout = tagLayout; + } + + public String getFormatVersion() { + return formatVersion; + } + + public AesAlgorithm getAlgorithm() { + return algorithm; + } + + public String getKeyId() { + return keyId; + } + + public String getKdfAlgorithm() { + return KDF_ALGORITHM; + } + + public int getKdfIterations() { + return kdfIterations; + } + + public byte[] getSalt() { + return copy(salt); + } + + public byte[] getIv() { + return copy(iv); + } + + public byte[] getCiphertext() { + return copy(ciphertext); + } + + public byte[] getTag() { + return copy(tag); + } + + public TagLayout getTagLayout() { + return tagLayout; + } + + private static byte[] copy(byte[] value) { + return value == null ? null : Arrays.copyOf(value, value.length); + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValueCodec.java b/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValueCodec.java new file mode 100644 index 0000000..0e0b35f --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/aes/AesEncryptedValueCodec.java @@ -0,0 +1,79 @@ +package com.kri.common.feature.crypto.aes; + +import com.kri.common.feature.crypto.CryptoException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +/** + * {@link AesEncryptedValue}를 단일 저장 문자열로 변환합니다. + */ +public final class AesEncryptedValueCodec { + + private static final String PREFIX = "kri"; + private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); + private static final Base64.Decoder DECODER = Base64.getUrlDecoder(); + + private AesEncryptedValueCodec() { + } + + public static String encode(AesEncryptedValue value) { + requireValue(value); + return String.join(":", + PREFIX, + value.getFormatVersion(), + value.getAlgorithm().name(), + Integer.toString(value.getKdfIterations()), + encodeText(value.getKeyId()), + value.getTagLayout().name(), + encodeBytes(value.getSalt()), + encodeBytes(value.getIv()), + encodeBytes(value.getCiphertext()), + encodeBytes(value.getTag())); + } + + public static AesEncryptedValue decode(String encoded) { + try { + String[] parts = encoded == null ? new String[0] : encoded.split(":", -1); + if (parts.length != 10 || !PREFIX.equals(parts[0])) { + throw new IllegalArgumentException("invalid field count or prefix"); + } + if (!AesEncryptedValue.CURRENT_FORMAT_VERSION.equals(parts[1])) { + throw new IllegalArgumentException("unsupported format version"); + } + return new AesEncryptedValue( + parts[1], + AesAlgorithm.valueOf(parts[2]), + decodeText(parts[4]), + Integer.parseInt(parts[3]), + decodeBytes(parts[6]), + decodeBytes(parts[7]), + decodeBytes(parts[8]), + decodeBytes(parts[9]), + TagLayout.valueOf(parts[5])); + } catch (RuntimeException e) { + throw new CryptoException("Invalid encrypted value format", e); + } + } + + private static void requireValue(AesEncryptedValue value) { + if (value == null) { + throw new CryptoException("Encrypted value must not be null"); + } + } + + private static String encodeText(String value) { + return value == null ? "" : encodeBytes(value.getBytes(StandardCharsets.UTF_8)); + } + + private static String decodeText(String value) { + return value.isEmpty() ? null : new String(decodeBytes(value), StandardCharsets.UTF_8); + } + + private static String encodeBytes(byte[] value) { + return value == null || value.length == 0 ? "" : ENCODER.encodeToString(value); + } + + private static byte[] decodeBytes(String value) { + return value.isEmpty() ? new byte[0] : DECODER.decode(value); + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/aes/TagLayout.java b/src/main/java/com/kri/common/feature/crypto/aes/TagLayout.java new file mode 100644 index 0000000..1ae8ceb --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/aes/TagLayout.java @@ -0,0 +1,13 @@ +package com.kri.common.feature.crypto.aes; + +/** + * 인증 태그의 저장 형태입니다. + */ +public enum TagLayout { + /** GCM 태그가 ciphertext 마지막에 포함됩니다. */ + APPENDED, + /** GCM 태그가 별도 필드에 저장됩니다. */ + DETACHED, + /** 인증 태그가 없는 CBC 호환 모드입니다. */ + NONE +} diff --git a/src/main/java/com/kri/common/feature/crypto/hash/AdaptiveHashService.java b/src/main/java/com/kri/common/feature/crypto/hash/AdaptiveHashService.java new file mode 100644 index 0000000..6235002 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/hash/AdaptiveHashService.java @@ -0,0 +1,13 @@ +package com.kri.common.feature.crypto.hash; + +/** + * 비밀번호, PIN, 복구 코드, API Secret 등 짧은 비밀값을 위한 adaptive hash API입니다. + */ +public interface AdaptiveHashService { + + String hash(CharSequence value); + + String hash(CharSequence value, int strength); + + boolean matches(CharSequence value, String encodedHash); +} diff --git a/src/main/java/com/kri/common/feature/crypto/hash/DigestAlgorithm.java b/src/main/java/com/kri/common/feature/crypto/hash/DigestAlgorithm.java new file mode 100644 index 0000000..212a683 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/hash/DigestAlgorithm.java @@ -0,0 +1,29 @@ +package com.kri.common.feature.crypto.hash; + +/** + * 일반 메시지 다이제스트 알고리즘입니다. + */ +public enum DigestAlgorithm { + /** 레거시 검증 전용입니다. 신규 보안 기능에 사용하지 마십시오. */ + MD5_LEGACY("MD5", true), + /** 레거시 검증 전용입니다. 신규 보안 기능에 사용하지 마십시오. */ + SHA_1_LEGACY("SHA-1", true), + SHA_256("SHA-256", false), + SHA_512("SHA-512", false); + + private final String jcaName; + private final boolean legacy; + + DigestAlgorithm(String jcaName, boolean legacy) { + this.jcaName = jcaName; + this.legacy = legacy; + } + + public String getJcaName() { + return jcaName; + } + + public boolean isLegacy() { + return legacy; + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/hash/DigestEncoding.java b/src/main/java/com/kri/common/feature/crypto/hash/DigestEncoding.java new file mode 100644 index 0000000..9506a46 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/hash/DigestEncoding.java @@ -0,0 +1,10 @@ +package com.kri.common.feature.crypto.hash; + +/** + * 다이제스트 출력 인코딩입니다. + */ +public enum DigestEncoding { + HEX_LOWER, + HEX_UPPER, + BASE64 +} diff --git a/src/main/java/com/kri/common/feature/crypto/hash/DigestRequest.java b/src/main/java/com/kri/common/feature/crypto/hash/DigestRequest.java new file mode 100644 index 0000000..48b85a9 --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/hash/DigestRequest.java @@ -0,0 +1,61 @@ +package com.kri.common.feature.crypto.hash; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +/** + * 알고리즘과 출력 형식을 함께 전달하는 일반 digest 요청입니다. + */ +public final class DigestRequest { + + private final byte[] value; + private final DigestAlgorithm algorithm; + private final DigestEncoding encoding; + + private DigestRequest(byte[] value, DigestAlgorithm algorithm, DigestEncoding encoding) { + this.value = value == null ? null : Arrays.copyOf(value, value.length); + this.algorithm = algorithm; + this.encoding = encoding; + } + + public static DigestRequest of( + byte[] value, + DigestAlgorithm algorithm, + DigestEncoding encoding + ) { + return new DigestRequest(value, algorithm, encoding); + } + + public static DigestRequest of( + String value, + Charset charset, + DigestAlgorithm algorithm, + DigestEncoding encoding + ) { + if (value == null || charset == null) { + throw new IllegalArgumentException("value and charset must not be null"); + } + return new DigestRequest(value.getBytes(charset), algorithm, encoding); + } + + public static DigestRequest utf8( + String value, + DigestAlgorithm algorithm, + DigestEncoding encoding + ) { + return of(value, StandardCharsets.UTF_8, algorithm, encoding); + } + + public byte[] getValue() { + return value == null ? null : Arrays.copyOf(value, value.length); + } + + public DigestAlgorithm getAlgorithm() { + return algorithm; + } + + public DigestEncoding getEncoding() { + return encoding; + } +} diff --git a/src/main/java/com/kri/common/feature/crypto/hash/DigestService.java b/src/main/java/com/kri/common/feature/crypto/hash/DigestService.java new file mode 100644 index 0000000..c1cae0a --- /dev/null +++ b/src/main/java/com/kri/common/feature/crypto/hash/DigestService.java @@ -0,0 +1,45 @@ +package com.kri.common.feature.crypto.hash; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * 파일 무결성, 식별값 및 레거시 연동을 위한 일반 해시 API입니다. + */ +public interface DigestService { + + String digest(byte[] value, DigestAlgorithm algorithm, DigestEncoding encoding); + + default String digest(DigestRequest request) { + if (request == null) { + throw new IllegalArgumentException("request must not be null"); + } + return digest(request.getValue(), request.getAlgorithm(), request.getEncoding()); + } + + boolean matches( + byte[] value, + String expectedDigest, + DigestAlgorithm algorithm, + DigestEncoding encoding + ); + + default String digest(String value, DigestAlgorithm algorithm, DigestEncoding encoding) { + return digest(value, StandardCharsets.UTF_8, algorithm, encoding); + } + + default String digest( + String value, + Charset charset, + DigestAlgorithm algorithm, + DigestEncoding encoding + ) { + if (value == null) { + throw new IllegalArgumentException("value must not be null"); + } + if (charset == null) { + throw new IllegalArgumentException("charset must not be null"); + } + return digest(value.getBytes(charset), algorithm, encoding); + } +} diff --git a/src/main/java/com/kri/common/runtime/crypto/aes/DefaultAesCryptoService.java b/src/main/java/com/kri/common/runtime/crypto/aes/DefaultAesCryptoService.java new file mode 100644 index 0000000..c73f43a --- /dev/null +++ b/src/main/java/com/kri/common/runtime/crypto/aes/DefaultAesCryptoService.java @@ -0,0 +1,321 @@ +package com.kri.common.runtime.crypto.aes; + +import com.kri.common.autoconfigure.crypto.CryptoProperties; +import com.kri.common.feature.crypto.CryptoAuthenticationException; +import com.kri.common.feature.crypto.CryptoException; +import com.kri.common.feature.crypto.CryptoKeyNotFoundException; +import com.kri.common.feature.crypto.aes.AesAlgorithm; +import com.kri.common.feature.crypto.aes.AesCryptoService; +import com.kri.common.feature.crypto.aes.AesDecryptRequest; +import com.kri.common.feature.crypto.aes.AesEncryptRequest; +import com.kri.common.feature.crypto.aes.AesEncryptedValue; +import com.kri.common.feature.crypto.aes.TagLayout; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +public class DefaultAesCryptoService implements AesCryptoService { + + private static final int AES_KEY_BITS = 256; + private static final int GCM_TAG_BITS = 128; + private static final int GCM_TAG_BYTES = GCM_TAG_BITS / 8; + private static final int MIN_SALT_BYTES = 16; + private static final int MIN_KDF_ITERATIONS = 1; + private static final int MAX_KDF_ITERATIONS = 5_000_000; + + private final CryptoProperties properties; + private final SecureRandom secureRandom; + + public DefaultAesCryptoService(CryptoProperties properties) { + this(properties, new SecureRandom()); + } + + DefaultAesCryptoService(CryptoProperties properties, SecureRandom secureRandom) { + this.properties = properties; + this.secureRandom = secureRandom; + } + + @Override + public AesEncryptedValue encrypt(byte[] plaintext) { + return encrypt(AesEncryptRequest.builder(plaintext).build()); + } + + @Override + public AesEncryptedValue encrypt(AesEncryptRequest request) { + validateRequest(request); + byte[] plaintext = request.getPlaintext(); + AesAlgorithm algorithm = defaultIfNull(request.getAlgorithm(), properties.getAes().getAlgorithm()); + TagLayout tagLayout = resolveTagLayout(algorithm, request.getTagLayout()); + int iterations = defaultIfNull(request.getKdfIterations(), properties.getAes().getKdf().getIterations()); + validateIterations(iterations); + + String keyId = request.getKeyId(); + char[] masterKey = request.getMasterKey(); + if (masterKey == null || masterKey.length == 0) { + keyId = isBlank(keyId) ? properties.getAes().getActiveKeyId() : keyId; + masterKey = configuredKey(keyId); + } + + byte[] salt = request.getSalt(); + if (salt == null) { + salt = randomBytes(properties.getAes().getKdf().getSaltLength()); + } + validateSalt(salt); + + byte[] iv = request.getIv(); + if (iv == null) { + iv = randomBytes(algorithm.getIvLength()); + } + validateIv(iv, algorithm); + validateAad(request.getAad(), algorithm); + + try { + SecretKey key = deriveKey(masterKey, salt, iterations); + Cipher cipher = initCipher(Cipher.ENCRYPT_MODE, algorithm, key, iv); + updateAad(cipher, request.getAad(), algorithm); + byte[] encrypted = cipher.doFinal(plaintext); + return toEncryptedValue(algorithm, keyId, iterations, salt, iv, encrypted, tagLayout); + } catch (GeneralSecurityException e) { + throw new CryptoException("AES encryption failed", e); + } finally { + Arrays.fill(masterKey, '\0'); + } + } + + @Override + public byte[] decrypt(AesEncryptedValue encryptedValue) { + return decrypt(AesDecryptRequest.builder(encryptedValue).build()); + } + + @Override + public byte[] decrypt(AesDecryptRequest request) { + if (request == null || request.getEncryptedValue() == null) { + throw new IllegalArgumentException("encryptedValue must not be null"); + } + AesEncryptedValue value = request.getEncryptedValue(); + validateEncryptedValue(value); + char[] masterKey = request.getMasterKey(); + if (masterKey == null || masterKey.length == 0) { + masterKey = configuredKey(value.getKeyId()); + } + + try { + SecretKey key = deriveKey(masterKey, value.getSalt(), value.getKdfIterations()); + Cipher cipher = initCipher( + Cipher.DECRYPT_MODE, value.getAlgorithm(), key, value.getIv()); + updateAad(cipher, request.getAad(), value.getAlgorithm()); + return cipher.doFinal(ciphertextWithTag(value)); + } catch (AEADBadTagException e) { + throw new CryptoAuthenticationException( + "AES-GCM authentication failed: ciphertext, key, IV, tag or AAD is invalid", e); + } catch (GeneralSecurityException e) { + throw new CryptoException("AES decryption failed", e); + } finally { + Arrays.fill(masterKey, '\0'); + } + } + + private AesEncryptedValue toEncryptedValue( + AesAlgorithm algorithm, + String keyId, + int iterations, + byte[] salt, + byte[] iv, + byte[] encrypted, + TagLayout tagLayout + ) { + byte[] ciphertext = encrypted; + byte[] tag = new byte[0]; + if (algorithm == AesAlgorithm.AES_256_GCM && tagLayout == TagLayout.DETACHED) { + if (encrypted.length < GCM_TAG_BYTES) { + throw new CryptoException("AES-GCM result is shorter than its authentication tag"); + } + int ciphertextLength = encrypted.length - GCM_TAG_BYTES; + ciphertext = Arrays.copyOf(encrypted, ciphertextLength); + tag = Arrays.copyOfRange(encrypted, ciphertextLength, encrypted.length); + } + return new AesEncryptedValue( + AesEncryptedValue.CURRENT_FORMAT_VERSION, + algorithm, + keyId, + iterations, + salt, + iv, + ciphertext, + tag, + tagLayout); + } + + private byte[] ciphertextWithTag(AesEncryptedValue value) { + byte[] ciphertext = value.getCiphertext(); + if (value.getAlgorithm() != AesAlgorithm.AES_256_GCM + || value.getTagLayout() == TagLayout.APPENDED) { + return ciphertext; + } + byte[] tag = value.getTag(); + byte[] combined = Arrays.copyOf(ciphertext, ciphertext.length + tag.length); + System.arraycopy(tag, 0, combined, ciphertext.length, tag.length); + return combined; + } + + private SecretKey deriveKey(char[] masterKey, byte[] salt, int iterations) + throws GeneralSecurityException { + if (masterKey == null || masterKey.length == 0) { + throw new CryptoKeyNotFoundException("AES master key is missing"); + } + PBEKeySpec spec = new PBEKeySpec(masterKey, salt, iterations, AES_KEY_BITS); + try { + byte[] encoded = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") + .generateSecret(spec) + .getEncoded(); + try { + return new SecretKeySpec(encoded, "AES"); + } finally { + Arrays.fill(encoded, (byte) 0); + } + } finally { + spec.clearPassword(); + } + } + + private Cipher initCipher( + int mode, + AesAlgorithm algorithm, + SecretKey key, + byte[] iv + ) throws GeneralSecurityException { + Cipher cipher = Cipher.getInstance(algorithm.getTransformation()); + if (algorithm == AesAlgorithm.AES_256_GCM) { + cipher.init(mode, key, new GCMParameterSpec(GCM_TAG_BITS, iv)); + } else { + cipher.init(mode, key, new IvParameterSpec(iv)); + } + return cipher; + } + + private void updateAad(Cipher cipher, byte[] aad, AesAlgorithm algorithm) { + if (aad != null && aad.length > 0 && algorithm == AesAlgorithm.AES_256_GCM) { + cipher.updateAAD(aad); + } + } + + private char[] configuredKey(String keyId) { + if (isBlank(keyId)) { + throw new CryptoKeyNotFoundException( + "AES master key was not provided and kri.crypto.aes.active-key-id is empty"); + } + if (properties.getAes().getKeys() == null) { + throw new CryptoKeyNotFoundException("AES master key map is empty"); + } + String configured = properties.getAes().getKeys().get(keyId); + if (configured == null || configured.isEmpty()) { + throw new CryptoKeyNotFoundException("AES master key was not found for keyId=" + keyId); + } + return configured.toCharArray(); + } + + private void validateRequest(AesEncryptRequest request) { + if (request == null || request.getPlaintext() == null) { + throw new IllegalArgumentException("plaintext must not be null"); + } + } + + private void validateEncryptedValue(AesEncryptedValue value) { + if (!AesEncryptedValue.CURRENT_FORMAT_VERSION.equals(value.getFormatVersion())) { + throw new CryptoException("Unsupported encrypted value format version"); + } + if (value.getAlgorithm() == null || value.getTagLayout() == null) { + throw new CryptoException("Encrypted value algorithm and tag layout are required"); + } + validateIterations(value.getKdfIterations()); + validateSalt(value.getSalt()); + validateIv(value.getIv(), value.getAlgorithm()); + if (value.getCiphertext() == null) { + throw new CryptoException("Encrypted value ciphertext is required"); + } + if (value.getAlgorithm() == AesAlgorithm.AES_256_GCM) { + if (value.getTagLayout() == TagLayout.NONE) { + throw new CryptoException("AES-GCM authentication tag is required"); + } + if (value.getTagLayout() == TagLayout.DETACHED + && (value.getTag() == null || value.getTag().length != GCM_TAG_BYTES)) { + throw new CryptoException("Detached AES-GCM tag must be 16 bytes"); + } + if (value.getTagLayout() == TagLayout.APPENDED + && value.getCiphertext().length < GCM_TAG_BYTES) { + throw new CryptoException("Appended AES-GCM ciphertext does not contain a tag"); + } + } else if (value.getTagLayout() != TagLayout.NONE) { + throw new CryptoException("AES-CBC does not use a GCM tag layout"); + } + } + + private TagLayout resolveTagLayout(AesAlgorithm algorithm, TagLayout requested) { + if (algorithm == AesAlgorithm.AES_256_CBC_PKCS5) { + if (requested != null && requested != TagLayout.NONE) { + throw new IllegalArgumentException("AES-CBC tag layout must be NONE"); + } + return TagLayout.NONE; + } + TagLayout resolved = defaultIfNull(requested, properties.getAes().getTagLayout()); + if (resolved == TagLayout.NONE) { + throw new IllegalArgumentException("AES-GCM authentication tag cannot be omitted"); + } + return resolved; + } + + private void validateSalt(byte[] salt) { + if (salt == null || salt.length < MIN_SALT_BYTES) { + throw new IllegalArgumentException("salt must be at least 16 bytes"); + } + } + + private void validateIv(byte[] iv, AesAlgorithm algorithm) { + if (iv == null || iv.length != algorithm.getIvLength()) { + throw new IllegalArgumentException( + algorithm + " IV must be exactly " + algorithm.getIvLength() + " bytes"); + } + } + + private void validateAad(byte[] aad, AesAlgorithm algorithm) { + if (aad != null && aad.length > 0 && algorithm != AesAlgorithm.AES_256_GCM) { + throw new IllegalArgumentException("AAD is supported only by AES-GCM"); + } + } + + private void validateIterations(int iterations) { + if (iterations < MIN_KDF_ITERATIONS || iterations > MAX_KDF_ITERATIONS) { + throw new IllegalArgumentException( + "PBKDF2 iterations must be between 1 and " + MAX_KDF_ITERATIONS); + } + } + + private byte[] randomBytes(int length) { + if (length < MIN_SALT_BYTES && length != 12) { + throw new IllegalArgumentException("random byte length is invalid"); + } + byte[] value = new byte[length]; + secureRandom.nextBytes(value); + return value; + } + + private boolean isBlank(String value) { + return value == null || value.isBlank(); + } + + private T defaultIfNull(T value, T defaultValue) { + return value == null ? defaultValue : value; + } + + private int defaultIfNull(Integer value, int defaultValue) { + return value == null ? defaultValue : value; + } +} diff --git a/src/main/java/com/kri/common/runtime/crypto/hash/BCryptAdaptiveHashService.java b/src/main/java/com/kri/common/runtime/crypto/hash/BCryptAdaptiveHashService.java new file mode 100644 index 0000000..e911309 --- /dev/null +++ b/src/main/java/com/kri/common/runtime/crypto/hash/BCryptAdaptiveHashService.java @@ -0,0 +1,53 @@ +package com.kri.common.runtime.crypto.hash; + +import com.kri.common.feature.crypto.hash.AdaptiveHashService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +public class BCryptAdaptiveHashService implements AdaptiveHashService { + + private final int defaultStrength; + private final BCryptPasswordEncoder defaultEncoder; + + public BCryptAdaptiveHashService(int defaultStrength) { + validateStrength(defaultStrength); + this.defaultStrength = defaultStrength; + this.defaultEncoder = new BCryptPasswordEncoder(defaultStrength); + } + + @Override + public String hash(CharSequence value) { + validateValue(value); + return defaultEncoder.encode(value); + } + + @Override + public String hash(CharSequence value, int strength) { + validateValue(value); + validateStrength(strength); + if (strength == defaultStrength) { + return defaultEncoder.encode(value); + } + return new BCryptPasswordEncoder(strength).encode(value); + } + + @Override + public boolean matches(CharSequence value, String encodedHash) { + validateValue(value); + if (encodedHash == null || encodedHash.isBlank()) { + return false; + } + return defaultEncoder.matches(value, encodedHash); + } + + private void validateValue(CharSequence value) { + if (value == null) { + throw new IllegalArgumentException("value must not be null"); + } + } + + private void validateStrength(int strength) { + if (strength < 4 || strength > 31) { + throw new IllegalArgumentException("BCrypt strength must be between 4 and 31"); + } + } +} diff --git a/src/main/java/com/kri/common/runtime/crypto/hash/JdkDigestService.java b/src/main/java/com/kri/common/runtime/crypto/hash/JdkDigestService.java new file mode 100644 index 0000000..aeb01b4 --- /dev/null +++ b/src/main/java/com/kri/common/runtime/crypto/hash/JdkDigestService.java @@ -0,0 +1,59 @@ +package com.kri.common.runtime.crypto.hash; + +import com.kri.common.feature.crypto.CryptoException; +import com.kri.common.feature.crypto.hash.DigestAlgorithm; +import com.kri.common.feature.crypto.hash.DigestEncoding; +import com.kri.common.feature.crypto.hash.DigestService; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; + +public class JdkDigestService implements DigestService { + + private static final char[] LOWER_HEX = "0123456789abcdef".toCharArray(); + private static final char[] UPPER_HEX = "0123456789ABCDEF".toCharArray(); + + @Override + public String digest(byte[] value, DigestAlgorithm algorithm, DigestEncoding encoding) { + if (value == null || algorithm == null || encoding == null) { + throw new IllegalArgumentException("value, algorithm and encoding must not be null"); + } + try { + byte[] digest = MessageDigest.getInstance(algorithm.getJcaName()).digest(value); + return encode(digest, encoding); + } catch (NoSuchAlgorithmException e) { + throw new CryptoException("Digest algorithm is not available: " + algorithm, e); + } + } + + @Override + public boolean matches( + byte[] value, + String expectedDigest, + DigestAlgorithm algorithm, + DigestEncoding encoding + ) { + if (expectedDigest == null) { + return false; + } + String actual = digest(value, algorithm, encoding); + return MessageDigest.isEqual( + actual.getBytes(StandardCharsets.US_ASCII), + expectedDigest.getBytes(StandardCharsets.US_ASCII)); + } + + private String encode(byte[] value, DigestEncoding encoding) { + if (encoding == DigestEncoding.BASE64) { + return Base64.getEncoder().encodeToString(value); + } + char[] alphabet = encoding == DigestEncoding.HEX_UPPER ? UPPER_HEX : LOWER_HEX; + char[] output = new char[value.length * 2]; + for (int i = 0; i < value.length; i++) { + int current = value[i] & 0xff; + output[i * 2] = alphabet[current >>> 4]; + output[i * 2 + 1] = alphabet[current & 0x0f]; + } + return new String(output); + } +} diff --git a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 902e5ec..851b0f7 100644 --- a/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -9,3 +9,4 @@ com.kri.common.autoconfigure.swagger.KriSwaggerAutoConfiguration com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration com.kri.common.autoconfigure.http.bypass.BypassAutoConfiguration +com.kri.common.autoconfigure.crypto.CryptoAutoConfiguration