260916_01_ENH: 공통 암호화 및 해시 기능 추가

This commit is contained in:
2026-09-16 12:30:30 +09:00
parent 333709fbfc
commit 1adb692661
25 changed files with 1285 additions and 3 deletions

View File

@@ -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());
}
}

View File

@@ -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<String, String> 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;
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,11 @@
package com.kri.common.feature.crypto;
/**
* 요청한 암호화 키를 찾을 수 없을 때 발생합니다.
*/
public class CryptoKeyNotFoundException extends CryptoException {
public CryptoKeyNotFoundException(String message) {
super(message);
}
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -0,0 +1,13 @@
package com.kri.common.feature.crypto.aes;
/**
* 인증 태그의 저장 형태입니다.
*/
public enum TagLayout {
/** GCM 태그가 ciphertext 마지막에 포함됩니다. */
APPENDED,
/** GCM 태그가 별도 필드에 저장됩니다. */
DETACHED,
/** 인증 태그가 없는 CBC 호환 모드입니다. */
NONE
}

View File

@@ -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);
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,10 @@
package com.kri.common.feature.crypto.hash;
/**
* 다이제스트 출력 인코딩입니다.
*/
public enum DigestEncoding {
HEX_LOWER,
HEX_UPPER,
BASE64
}

View File

@@ -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;
}
}

View File

@@ -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);
}
}

View File

@@ -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> T defaultIfNull(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
private int defaultIfNull(Integer value, int defaultValue) {
return value == null ? defaultValue : value;
}
}

View File

@@ -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");
}
}
}

View File

@@ -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);
}
}

View File

@@ -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