11 Commits

Author SHA1 Message Date
curry772 15ac0fa2a2 BigTech 어댑터 로그 출력 부분 수정 2026-07-10 10:11:46 +09:00
curry772 e0039aca81 BigTech signature 생성 파라미터(UR) 로그 추가 2026-07-10 10:10:33 +09:00
curry772 5c094ef9b4 Merge branch 'master' of https://git.eactive.synology.me:8090/eapim/djbank/eapim-online.git 2026-07-10 09:46:51 +09:00
curry772 3772805301 BigTech 커스텀 어댑터 개발(커스텀 헤더 추가) 2026-07-10 09:46:33 +09:00
Rinjae d31b7a343c Merge remote-tracking branch 'origin/master' 2026-07-09 16:31:28 +09:00
curry772 47cb243ff4 REST Header 로그에 송신 Body 출력할 수 있는 기능 추가 2026-07-09 16:25:19 +09:00
Rinjae e3fb52343d "Jenkinsfile 개선:
- Tomcat 배포 구조 → WebLogic 기반으로 변경
- stage별 agent 명시 및 불필요한 환경변수 제거
- Webhook 알림 로직 추가"
2026-07-09 16:20:54 +09:00
curry772 46463a27a4 UnknownMessageLogUtils 클래스명 오타 수정 2026-07-09 14:55:23 +09:00
curry772 7e1af96fcf 사용하지 않는 단위테스트 삭제 2026-07-09 14:15:50 +09:00
curry772 f91b50a121 빅테크 Out Rest Adapter 생성 2026-07-09 14:15:35 +09:00
curry772 9cf16c9f49 일부 수정 2026-07-09 14:15:15 +09:00
8 changed files with 449 additions and 625 deletions
Vendored
+127 -133
View File
@@ -1,163 +1,157 @@
pipeline {
agent { label 'djb-vm' }
agent none
options {
timestamps()
disableConcurrentBuilds()
skipDefaultCheckout() // stage별 agent의 자동 SCM checkout 방지 (Deploy 노드는 git 접근 불필요, unstash로만 WAR 수신)
buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '20'))
}
environment {
JAVA_HOME = '/apps/opts/jdk8'
JAVA_HOME_TOMCAT = '/apps/opts/jdk17'
GRADLE_HOME = '/apps/opts/gradle-8.7'
GRADLE_USER_HOME = '/apps/opts/gradle-home'
NODE_HOME = '/apps/opts/node-v24'
PATH = "/apps/opts/jdk8/bin:/apps/opts/gradle-8.7/bin:/apps/opts/node-v24/bin:/apps/opts/bin:${env.PATH}"
GIT_SSH_COMMAND = 'ssh -o StrictHostKeyChecking=accept-new'
CATALINA_BASE = '/prod/eapim/apigw'
CATALINA_HOME = '/prod/eapim/apache-tomcat-9.0.116'
CATALINA_PID = '/prod/eapim/apigw/logs/catalina.pid'
DEPLOY_HTTP_PORT = '39110'
WEBHOOK_URL = 'http://172.30.1.50:18000/api/hooks/01ba51b01d3c4c98ae8f3183a23a84ed713197857d024b5da4f303458195eb32'
}
stages {
stage('Checkout') {
steps {
checkout scm
stage('Build (djb-vm)') {
agent { label 'djb-vm' }
environment {
JAVA_HOME = '/apps/opts/jdk8'
GRADLE_HOME = '/apps/opts/gradle-8.7'
GRADLE_USER_HOME = '/apps/opts/gradle-home'
NODE_HOME = '/apps/opts/node-v24'
PATH = "/apps/opts/jdk8/bin:/apps/opts/gradle-8.7/bin:/apps/opts/node-v24/bin:/apps/opts/bin:${env.PATH}"
}
}
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('Checkout modules') {
steps {
sh '''
set -eu
stage('Checkout modules') {
steps {
sh '''
set -eu
for REPO in elink-online-core elink-online-transformer elink-online-common elink-online-emsclient elink-online-core-jpa; do
if [ ! -e "$REPO/.git" ]; then
rm -rf "$REPO"
git clone --depth=1 --branch master \
"ssh://git@172.30.1.50:2222/djb-eapim/$REPO.git" \
"$REPO"
else
git -C "$REPO" fetch --depth=1 origin master
git -C "$REPO" reset --hard origin/master
git -C "$REPO" clean -fdx
fi
done
'''
}
}
for REPO in elink-online-core elink-online-transformer elink-online-common elink-online-emsclient elink-online-core-jpa; do
if [ ! -e "$REPO/.git" ]; then
rm -rf "$REPO"
git clone --depth=1 --branch master \
"ssh://git@172.30.1.50:2222/djb-eapim/$REPO.git" \
"$REPO"
else
git -C "$REPO" fetch --depth=1 origin master
git -C "$REPO" reset --hard origin/master
git -C "$REPO" clean -fdx
fi
done
'''
}
}
stage('Verify toolchain') {
steps {
sh '''
set -eu
java -version
gradle --version
'''
}
}
stage('Verify toolchain') {
steps {
sh '''
set -eu
java -version
gradle --version
'''
}
}
stage('Build WAR') {
steps {
sh 'gradle clean build -x test --no-daemon'
}
post {
success {
sh '''
set -eu
cd build/libs
sha1sum eapim-online.war > eapim-online.war.sha1
sha256sum eapim-online.war > eapim-online.war.sha256
md5sum eapim-online.war > eapim-online.war.md5
'''
archiveArtifacts artifacts: 'build/libs/eapim-online.war,build/libs/eapim-online.war.sha1,build/libs/eapim-online.war.sha256,build/libs/eapim-online.war.md5', fingerprint: true
stage('Build WAR') {
steps { sh 'gradle clean build -x test --no-daemon -Pprofile=weblogic' }
post {
success {
sh '''
set -eu
cd build/libs
sha256sum eapim-online.war > eapim-online.war.sha256
'''
archiveArtifacts artifacts: 'build/libs/eapim-online.war,build/libs/eapim-online.war.sha256', fingerprint: true
stash name: 'war', includes: 'build/libs/eapim-online.war'
}
}
}
}
}
stage('Stop Tomcat') {
steps {
sh '''
set +e
systemctl --user stop eapim-apigw 2>/dev/null
if [ -f "$CATALINA_PID" ] && kill -0 "$(cat "$CATALINA_PID")" 2>/dev/null; then
JAVA_HOME="$JAVA_HOME_TOMCAT" "$CATALINA_HOME/bin/shutdown.sh" 30 -force || true
for i in $(seq 1 30); do
[ -f "$CATALINA_PID" ] && kill -0 "$(cat "$CATALINA_PID")" 2>/dev/null || break
sleep 1
done
fi
rm -f "$CATALINA_PID"
'''
stage('Deploy (weblogic)') {
agent { label 'weblogic' }
environment {
JENKINS_NODE_COOKIE = 'dontKillMe' // background weblogic를 빌드 종료 시 죽이지 않게
WL_HOME = '/app/eapim/apigw'
WL_DEPLOY_DIR = '/app/eapim/apigw'
WL_WAR_NAME = 'eapim-online.war'
WL_HTTP_PORT = '39110'
WL_NOHUP = '/logs/weblogic/domains/eapimDomain/nohup.agwSvr11.out'
}
}
stages {
stage('Stop WebLogic') {
steps {
sh '"$WL_HOME/stopAgw11.sh"' // 동기: 완전 종료까지 블록, 미기동 시에도 안전
}
}
stage('Deploy WAR') {
steps {
unstash 'war'
sh '''
set -eu
cp build/libs/eapim-online.war "$WL_DEPLOY_DIR/$WL_WAR_NAME"
ls -la "$WL_DEPLOY_DIR"
'''
}
}
stage('Start WebLogic and readiness') {
steps {
sh '''
set -eu
"$WL_HOME/startAgw11.sh" # nohup & 로 백그라운드 기동, 즉시 리턴
stage('Deploy ROOT.war') {
steps {
sh '''
set -eu
DEPLOY_DIR="$CATALINA_BASE/webapps"
rm -rf "$DEPLOY_DIR/ROOT" "$DEPLOY_DIR/ROOT.war"
cp build/libs/eapim-online.war "$DEPLOY_DIR/ROOT.war"
ls -la "$DEPLOY_DIR"
'''
}
}
DEADLINE=$(($(date +%s) + 300))
STATUS=000
while [ "$(date +%s)" -lt "$DEADLINE" ]; do
STATUS=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 3 \
"http://localhost:$WL_HTTP_PORT/" 2>/dev/null || echo "000")
case "$STATUS" in
200|302|401|403|404) echo "Readiness OK (/ HTTP $STATUS)"; break ;;
esac
sleep 3
done
stage('Start Tomcat and readiness') {
steps {
sh '''
set -eu
LOG="$CATALINA_BASE/logs/catalina.$(date +%Y-%m-%d).log"
BEFORE=0
[ -f "$LOG" ] && BEFORE=$(stat -c %s "$LOG")
systemctl --user start eapim-apigw
PROBE_URL="http://localhost:$DEPLOY_HTTP_PORT/"
DEADLINE=$(($(date +%s) + 300))
STATUS=000
while [ "$(date +%s)" -lt "$DEADLINE" ]; do
STATUS=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 3 \
"$PROBE_URL" 2>/dev/null || echo "000")
case "$STATUS" in
200|302|401|403|404)
echo "Readiness OK ($PROBE_URL HTTP $STATUS)"
break
;;
esac
if [ -f "$LOG" ] && tail -c +$((BEFORE+1)) "$LOG" | grep -qE "Application listener .* Exception|SEVERE.*startup.Catalina"; then
echo "Startup error detected in log"
tail -c +$((BEFORE+1)) "$LOG" | tail -80
exit 1
fi
sleep 2
done
case "$STATUS" in
200|302|401|403|404) ;;
*)
echo "Readiness probe failed within 300s, last HTTP status: $STATUS"
echo "--- last 300 lines of catalina log ---"
[ -f "$LOG" ] && tail -c +$((BEFORE+1)) "$LOG" | tail -300
echo "--- systemd unit status ---"
systemctl --user status eapim-apigw --no-pager || true
echo "--- listening ports ---"
ss -tlnp 2>/dev/null | grep -E ":$DEPLOY_HTTP_PORT\\b" || echo "(port $DEPLOY_HTTP_PORT not listening)"
exit 1
;;
esac
echo "--- key boot log lines ---"
tail -c +$((BEFORE+1)) "$LOG" | grep -E "Server startup|Deployment of web" | head -10 || true
'''
case "$STATUS" in
200|302|401|403|404) ;;
*)
echo "Readiness failed within 300s, last HTTP=$STATUS"
[ -f "$WL_NOHUP" ] && tail -120 "$WL_NOHUP"
exit 1
;;
esac
'''
}
}
}
}
}
post {
success {
node('weblogic') {
sh '''
set +e
payload=$(printf '{"text":"[%s #%s](%s) SUCCESS"}' "$JOB_NAME" "$BUILD_NUMBER" "$BUILD_URL")
curl -sS --fail --max-time 5 -H 'Content-Type: application/json' -X POST --data "$payload" "$WEBHOOK_URL" >/dev/null || echo "Webhook failed"
'''
}
}
failure {
node('weblogic') {
sh '''
set +e
payload=$(printf '{"text":"[%s #%s](%s) FAILURE"}' "$JOB_NAME" "$BUILD_NUMBER" "$BUILD_URL")
curl -sS --fail --max-time 5 -H 'Content-Type: application/json' -X POST --data "$payload" "$WEBHOOK_URL" >/dev/null || echo "Webhook failed"
'''
}
}
}
}
@@ -33,9 +33,11 @@ import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
import com.eactive.eai.common.util.InboundErrorLogger;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.MessageUtil;
import com.eactive.eai.common.util.RestSendBodyLogUtils;
import com.eactive.eai.common.util.TxFileLogger;
import com.eactive.eai.common.util.TxSiftContext;
import com.eactive.eai.common.util.UUIDGenerator;
@@ -169,6 +171,14 @@ public class DJBApiAdapterController implements HttpAdapterServiceKey {
responseData = responseErrorMsg;
} finally {
// 어댑터 HTTP 로그에 응답 body 출력
if (RestSendBodyLogUtils.isBodyLoggingApi(transactionProp.getProperty("API_SERVICE_CODE"))) {
String trimmedBody = RestSendBodyLogUtils.getBodyByMaxSize(responseData);
transactionProp.setProperty(HttpAdapterExtraLogUtil.BODY_FIELD_NAME, trimmedBody);
}
servletRequest.setAttribute(TransactionContextKeys.TRANSACTION_PROP, transactionProp);
/**
* 로깅 인터셉터에 데이터를 전달하기 위한 처리 이미 거래처리가 끝나서 영향도가 없을만한 servletRequest에 Attribute로 전달
* 추후 더 좋은방법이 생길경우 개선 요망
@@ -1,19 +1,22 @@
package com.eactive.eai.adapter.interceptor;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
import com.eactive.eai.common.util.Logger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.dynamic.HttpAdapterServiceKey;
import com.eactive.eai.common.TransactionContextKeys;
import com.eactive.eai.common.logger.HttpAdapterExtraHeaderVo;
import com.eactive.eai.common.util.HttpAdapterExtraLogUtil;
import com.eactive.eai.common.util.Logger;
public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
@@ -55,6 +58,11 @@ public class HttpResponseLoggingInterceptor implements HandlerInterceptor {
logger.debug(String.format( "httpHeader logging Interceptor headerKey=%s, headerValue=%s", headerName, headerValue));
headerMap.put(headerName, headerValue);
}
String body = transactionProp.getProperty(HttpAdapterExtraLogUtil.BODY_FIELD_NAME);
if (StringUtils.isNotEmpty(body)) {
headerMap.put(HttpAdapterExtraLogUtil.BODY_FIELD_NAME, body);
}
int httpStatusCode = response.getStatus();
HttpAdapterExtraLogUtil.insertHttpAdapterExtraLog(uuid, 400, adapterGroupName, adapterName, headerMap, url, method, httpStatusCode);
@@ -30,7 +30,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.eactive.eai.adapter.http.dynamic.UnkownMessageLogUtils;
import com.eactive.eai.adapter.http.dynamic.UnknownMessageLogUtils;
import com.eactive.eai.adapter.http.dynamic.filter.JwtAuthException;
import com.eactive.eai.authserver.config.RequestContextData;
import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;
@@ -164,7 +164,7 @@ public class DJBOAuth2Controller {
Properties logProp = new Properties();
logProp.put("clientId", clientId);
UnkownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, e.getMessage());
@@ -179,7 +179,7 @@ public class DJBOAuth2Controller {
Properties logProp = new Properties();
logProp.put("clientId", clientId);
UnkownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
UnknownMessageLogUtils.logUnkownMessage(this.getClass().getSimpleName(), this.getClass().getSimpleName(),
tokenRequest.toString(), logProp, request, response, "RECEAIIRP301", e);
String errorJson = MessageUtil.makeJsonErrorMessage(MessageUtil.ERROR_CODE_AUTH_FAIL, "Unauthorized. [Unknown]");
@@ -0,0 +1,136 @@
package com.eactive.eai.custom.adapter.http.client.impl;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Properties;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.client.impl.HttpClient5AdapterServiceRest;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.MaskingUtils;
/**
* 1. 기능 : EAI HTTP OutBound 용 어댑터로 수동 시스템의 HTTP 웹 컴포넌트를 GET/POST 방식으로 호출할 수 있는
* 기능을 제공한다.<br>
* 2. 처리 개요 : <br>
* * - 2020-09-25: Http Header 받아서 처리할 수 있게 기능 추가<br>
* 3. 주의사항 <br>
*
* @author :
* @version : v 1.0.0
* @see : HttpClientAdapterServiceFactory.java,
* HttpClientAdapterServiceSupport.java
* @since :
*
*/
public class HttpClient5AdapterServiceBigTech extends HttpClient5AdapterServiceRest
implements HttpClientAdapterServiceKey {
private static final char[] _HEX_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f' };
private static String hexEncode(byte[] data) {
if (data == null) {
return null;
}
int length = data.length;
char[] encoded = new char[length << 1];
for (int i = 0, j = 0; i < length; i++) {
encoded[j++] = _HEX_LOWER[(0xF0 & data[i]) >>> 4];
encoded[j++] = _HEX_LOWER[0x0F & data[i]];
}
return new String(encoded);
} // end of hex_encode
private static final String _BTP_CHARSET = "UTF-8";
private static final String _BTP_ALGORITHM = "HmacSHA256";
private static final String _BTP_ACCESS_KEY = "{BTP_ACCESS_KEY}";
private static final String _BTP_SECRET_KEY = "{BTP_SECRET_KEY}";
private static byte[] mac(String charset, String algorithm, String timestamp, String accessKey, String secretKey,
String url) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
String message = String.join(" ", Arrays.asList(url, timestamp, accessKey));
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(charset), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKeySpec);
return mac.doFinal(message.getBytes(charset));
}// end of mac
private static String macHex(String charset, String algorithm, String timestamp, String accessKey, String secretKey,
String url) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException {
return hexEncode(mac(charset, algorithm, timestamp, accessKey, secretKey, url));
}// end of macHex
protected void assignRequestHeaders(HttpUriRequestBase method, Object httpHeader, Properties prop, Properties tempProp) {
super.assignRequestHeaders(method, httpHeader, prop, tempProp);
try {
String adapterGroupName = tempProp.getProperty(ADAPTER_GROUP_NAME);
Properties customProp = PropManager.getInstance().getProperties(adapterGroupName);
String charset = customProp.getProperty("_BTP_CHARSET", _BTP_CHARSET);
String algorithm = customProp.getProperty("_BTP_ALGORITHM", _BTP_ALGORITHM);
String timestamp = System.currentTimeMillis() + "";
String accessKey = customProp.getProperty("_BTP_ACCESS_KEY", _BTP_ACCESS_KEY);
String secretKey = customProp.getProperty("_BTP_SECRET_KEY", _BTP_SECRET_KEY);
if(logger.isDebug()) {
logger.debug("charset={}", charset);
logger.debug("algorithm={}", algorithm);
logger.debug("timestamp={}", timestamp);
logger.debug("accessKey={}", accessKey);
logger.debug("secretKey={}", MaskingUtils.maskPassword(secretKey));
logger.debug("url={}", method.getRequestUri());
}
String signature = macHex(charset// charset
, algorithm// algorithm
, timestamp// timestamp
, accessKey// accessKey
, secretKey// secretKey
, method.getRequestUri());
method.setHeader("x-btp-access-key", accessKey);
method.setHeader("x-btp-timestamp", timestamp);
method.setHeader("x-btp-signature-v1", signature);
} catch (InvalidKeyException | UnsupportedEncodingException | NoSuchAlgorithmException e) {
throw new RuntimeException("BigTech 헤더 설정 실패", e);
}
}
// public static void main(String[] args) {
// try {
// String url = "/rest/v1/service?param0=&param1=";
// String timestamp = System.currentTimeMillis()+"";
// String accessKey = _BTP_ACCESS_KEY;
// String secretKey = _BTP_SECRET_KEY;
// String signature = macHex(
// _BTP_CHARSET//charset
// , _BTP_ALGORITHM//algorithm
// , timestamp// timestamp
// , _BTP_ACCESS_KEY//accessKey
// , _BTP_SECRET_KEY//secretKey
// , url
// );
// System.out.println(String.format("charset=%s", _BTP_CHARSET));
// System.out.println(String.format("algorithm=%s", _BTP_ALGORITHM));
// System.out.println(String.format("accessKey=%s", accessKey));
// System.out.println(String.format("secretKey=%s", secretKey));
// System.out.println(String.format("timestamp=%s", timestamp));
// System.out.println(String.format("signature=%s", signature));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }// end of main
}
@@ -0,0 +1,147 @@
package com.eactive.eai.custom.adapter.http.client.impl;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Node;
import org.json.simple.JSONObject;
import com.eactive.eai.adapter.http.client.HttpClientAdapterServiceKey;
import com.eactive.eai.adapter.http.client.impl.filter.HttpClient5AdapterFilterFactory;
import com.eactive.eai.adapter.http.client.impl.filter.HttpClientAdapterFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* 1. 기능 : HttpClient5AdapterServiceRest 호출 전후 Filter 적용할 수 있는 기능을 제공한다.<br>
* 2. 처리 개요 : <br>
* 3. 주의사항 <br>
*
* @author :
* @version : v 1.0.0
* @see : HttpClientAdapterServiceFactory.java,
* HttpClientAdapterServiceSupport.java, HttpClient5AdapterServiceRest.java
* @since :
*
*/
public class HttpClient5AdapterServiceBigTechAddFilter extends HttpClient5AdapterServiceBigTech
implements HttpClientAdapterServiceKey {
// 요청전 수행할 필터(쉼표(,)로 구분)
static final String PRE_FILTERS = "PRE_FILTERS";
// 요청후 수행할 필터(쉼표(,)로 구분)
static final String POST_FILTERS = "POST_FILTERS";
// // Adapter에서 Exception이 발생한 경우, 처리할 필터
// static final String EXCEPTION_FILTER = "EXCEPTION_FILTER";
private ObjectMapper mapper = new ObjectMapper();
/**
* 1. 기능 : HttpClient 호출 전후 Filter 적용용 2. 처리 개요 : <br>
* 3. 주의사항 <br>
*
* @param prop Http Adapter 속성 정보
* @return 반환 된 Object
* @exception Exception 수동 시스템 간 통신 중 발생
*/
public Object execute(Properties prop, Object data, Properties tempProp) throws Exception {
String adptGrpName = tempProp.getProperty(ADAPTER_GROUP_NAME);
String adptName = tempProp.getProperty(ADAPTER_NAME);
data = doPreFilters(adptGrpName, adptName, prop, data, tempProp);
Object adapterResponse = super.execute(prop, data, tempProp);
adapterResponse = doPostFilters(adptGrpName, adptName, prop, adapterResponse, tempProp);
if (adapterResponse instanceof JSONObject)
adapterResponse = ((JSONObject) adapterResponse).toJSONString();
else if (adapterResponse instanceof ObjectNode)
adapterResponse = mapper.writeValueAsString((ObjectNode) adapterResponse);
else if (adapterResponse instanceof Node)
adapterResponse = ((Node) adapterResponse).asXML();
return adapterResponse;
}
protected Object doPreFilters(String adptGrpName, String adptName, Properties prop, Object message,
Properties tempProp) throws Exception {
// boolean isSetCommonFilterInAdapterProp = false;
// 1. adapter에 설정된 필터 수행
String preFiltersStr = prop.getProperty(PRE_FILTERS);
if (StringUtils.isNotEmpty(preFiltersStr)) {
String[] preFilters = StringUtils.split(preFiltersStr, ",");
for (String filterName : preFilters) {
if (StringUtils.isBlank(filterName)) {
continue;
}
logger.debug("HttpClient5AdapterServiceRestAddFilter] Processing Start [" + filterName + "]");
HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());
if (adapterFilter != null) {
// if (adapterFilter instanceof IBKOutCommonFilter)
// isSetCommonFilterInAdapterProp = true;
message = adapterFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
} else {
throw new Exception("Failed get Filter Class: " + filterName);
}
}
}
// // 2. IBKOutCommonFilter 필터 수행(adapter 필터에서 수행하지 않을 때만)
// if (!isSetCommonFilterInAdapterProp) {
// HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
// .createFilter(IBKOutCommonFilter.class.getName());
// if (ibkFilter != null) {
// message = ibkFilter.doPreFilter(adptGrpName, adptName, prop, message, tempProp);
// }
// } else {
// logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'POST_FILTERS'. already in adapter filters");
// }
return message;
}
protected Object doPostFilters(String adptGrpName, String adptName, Properties prop, Object message,
Properties tempProp) throws Exception {
// boolean isSetCommonFilterInAdapterProp = false;
// 1. adapter에 설정된 필터 수행
String postFiltersStr = prop.getProperty(POST_FILTERS);
if (StringUtils.isNotEmpty(postFiltersStr)) {
String[] postFilters = StringUtils.split(postFiltersStr, ",");
for (String filterName : postFilters) {
if (StringUtils.isBlank(filterName)) {
continue;
}
HttpClientAdapterFilter adapterFilter = HttpClient5AdapterFilterFactory.createFilter(filterName.trim());
if (adapterFilter != null) {
// if (adapterFilter instanceof IBKOutCommonFilter)
// isSetCommonFilterInAdapterProp = true;
message = adapterFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
} else {
throw new Exception("Failed get Filter Class: " + filterName);
}
}
}
// // 2. IBKOutCommonFilter 필터 수행
// if (!isSetCommonFilterInAdapterProp) {
// HttpClientAdapterFilter ibkFilter = HttpClient5AdapterFilterFactory
// .createFilter(IBKOutCommonFilter.class.getName());
// if (ibkFilter != null) {
// message = ibkFilter.doPostFilter(adptGrpName, adptName, prop, message, tempProp);
// }
// } else {
// logger.debug("IBKOutCommonFilter isSetCommonFilterInAdapterProp 'PRE_FILTERS'. already in adapter filters");
// }
return message;
}
}
@@ -81,7 +81,7 @@ public class DJBErpNsmapiAccessTokenService implements HttpClientAccessTokenServ
}
String connectionTimeoutTemp = adapterProp.getProperty("CONNECTION_TIMEOUT");
if (StringUtils.isBlank(connectionTimeoutTemp)) {
connectionTimeoutTemp = "30000";
connectionTimeoutTemp = "3000";
}
int timeout = Integer.parseInt(timeoutTemp);
@@ -245,7 +245,7 @@ public class DJBErpNsmapiAccessTokenService implements HttpClientAccessTokenServ
logger.debug("contentType = [" + contentType + "]");
logger.debug("encode = [" + encode + "]");
OAuth2AccessTokenVO accessToken = new OAuth2AccessTokenVO();
OAuth2AccessTokenVO accessToken = null;
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
if (response.getCode() != 200) {
throw new Exception("OAuth token receive status fail value= " + response.getCode());
@@ -266,7 +266,11 @@ public class DJBErpNsmapiAccessTokenService implements HttpClientAccessTokenServ
JsonNode data = responseJSON.path("data");
if(data.has("token")) {
String token = data.path("token").asText();
accessToken = new OAuth2AccessTokenVO();
accessToken.setAccessToken(token);
accessToken.setExpiration(new Date(currentTime + 30_000L));
logger.debug("oauthToken =" + accessToken.toString());
return accessToken;
} else {
throw new Exception("oauth token return null");
}
@@ -274,18 +278,13 @@ public class DJBErpNsmapiAccessTokenService implements HttpClientAccessTokenServ
throw new Exception("oauth token return null");
}
// accessToken.setExpiration(new Date(currentTime + oAuthCredentialVo.getIntervalSec() * 1000L));
accessToken.setExpiration(new Date(currentTime + 30_000L));
logger.debug("oauthToken =" + accessToken.toString());
return accessToken;
} else {
throw new Exception("oauth token return null");
}
} catch (Exception e) {
e.printStackTrace();
logger.error("[DJBErpNsmapiAccessTokenService] retrieve accessToken exception :" + e.getMessage(), e);
return accessToken;
logger.error("[DJBErpNsmapiAccessTokenService] retrieve accessToken exception :" + e.getMessage(), e);
throw e;
}
}
}
@@ -1,470 +0,0 @@
package com.eactive.eai.custom.adapter.http.dynamic.filter;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.context.support.GenericApplicationContext;
import com.eactive.eai.adapter.http.dynamic.filter.InCryptoFilter;
import com.eactive.eai.adapter.http.filter.AbstractCryptoFilter;
import com.eactive.eai.common.hsm.HsmCryptoService;
import com.eactive.eai.common.hsm.HsmManager;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.security.CryptoModuleConfigVO;
import com.eactive.eai.common.security.CryptoModuleManager;
import com.eactive.eai.common.security.CryptoModuleService;
import com.eactive.eai.common.security.keyderiv.strategy.HsmKeyDerivationStrategy;
import com.eactive.eai.common.security.loader.CryptoModuleConfigLoader;
import com.eactive.eai.common.security.mapper.CryptoModuleConfigMapper;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.custom.common.security.keyderiv.HsmContextSha256KeyDerivationStrategy;
import com.eactive.eai.data.entity.onl.security.CryptoModuleConfig;
/**
* CryptoFilter HSM 연동 통합 테스트 (SoftHSM2 / SunPKCS11)
*
* SoftHSM2에서 MASTER_KEY를 조회하여 키를 도출한 뒤
* InCryptoFilter 의 암복호화 전체 흐름을 검증한다.
*
* 사전 조건:
* C:\SoftHSM2 에 SoftHSM2 설치 (미설치 시 자동 건너뜀)
* MASTER_KEY alias는 없으면 자동 생성됨
*
* 검증 전략:
* HSM → 키 도출 → CryptoModuleExtension → InCryptoFilter doPostFilter(암호화) → doPreFilter(복호화) → 원문 일치
*/
@TestMethodOrder(MethodOrderer.DisplayName.class)
public class CryptoFilterHsmIntegrationTest {
// -------------------------------------------------------------------------
// 상수
// -------------------------------------------------------------------------
private static final String SOFTHSM2_DLL = "C:/SoftHSM2/lib/softhsm2-x64.dll";
private static final String SOFTHSM2_UTIL = "C:/SoftHSM2/bin/softhsm2-util.exe";
private static final String TOKEN_LABEL = "eapim-test";
private static final String PIN = "1234";
private static final String MASTER_KEY_ALIAS = "MASTER_KEY";
/** HsmKeyDerivationStrategy: HSM 마스터키를 파생 없이 직접 사용 */
private static final String MOD_HSM_GCM = "HSM_GCM";
/** HsmContextSha256KeyDerivationStrategy: HSM 마스터키 + 컨텍스트값 SHA-256 파생 */
private static final String MOD_CTX_SHA_GCM = "CTX_SHA256_GCM";
private static final String CTX_KEY = "X-Api-Group-Seq";
private static final String CTX_VAL_A = "GROUP-A";
private static final String CTX_VAL_B = "GROUP-B";
// -------------------------------------------------------------------------
// 정적 필드
// -------------------------------------------------------------------------
private static GenericApplicationContext springCtx;
private static HsmManager hsmManager;
private static File tempCfgFile;
// -------------------------------------------------------------------------
// 내부 클래스: runtimeContext를 고정값으로 반환하는 필터
// -------------------------------------------------------------------------
static class ContextAwareCryptoFilter extends InCryptoFilter {
private final String key;
private final String value;
ContextAwareCryptoFilter(String key, String value) {
this.key = key;
this.value = value;
}
@Override
protected Map<String, String> buildRuntimeContext(Properties prop, HttpServletRequest request) {
Map<String, String> ctx = new HashMap<>();
ctx.put(key, value);
return ctx;
}
}
// -------------------------------------------------------------------------
// 인스턴스 필드
// -------------------------------------------------------------------------
private HttpServletRequest mockReq;
private HttpServletResponse mockRes;
// -------------------------------------------------------------------------
// 전체 설정 / 해제
// -------------------------------------------------------------------------
@BeforeAll
static void setUpAll() throws Exception {
assumeTrue(new File(SOFTHSM2_DLL).exists(),
"SoftHSM2 미설치 (C:/SoftHSM2) - 테스트 건너뜀");
System.setProperty("SOFTHSM2_CONF", "C:\\SoftHSM2\\etc\\softhsm2.conf");
// 1. 토큰 초기화
ensureTokenInitialized();
// 2. PKCS11 설정 문자열
// attributes(*,...): generate/import 모두 CKA_SENSITIVE=false → getEncoded() 사용 가능
String cfgContent = "name = SoftHSM\n"
+ "library = " + SOFTHSM2_DLL + "\n"
+ "slotListIndex = 0\n"
+ "attributes(*, CKO_SECRET_KEY, CKK_AES) = {\n"
+ " CKA_SENSITIVE = false\n"
+ " CKA_EXTRACTABLE = true\n"
+ "}\n";
tempCfgFile = File.createTempFile("pkcs11-filter-it-", ".cfg");
Files.write(tempCfgFile.toPath(), cfgContent.getBytes("UTF-8"));
// 3. Mock PropManager (DB 없이 HSM 설정값 제공)
PropManager mockPropManager = mock(PropManager.class);
when(mockPropManager.getProperty("HSM", "PKCS11_CONFIG")).thenReturn(cfgContent);
when(mockPropManager.getProperty("HSM", "PIN")).thenReturn(PIN);
when(mockPropManager.getProperty(eq("HSM"), eq("CACHE_RELOAD_YN"), anyString())).thenReturn("N");
// 4. HsmManager (private 생성자 → 리플렉션)
Constructor<HsmManager> hsmCtor = HsmManager.class.getDeclaredConstructor();
hsmCtor.setAccessible(true);
hsmManager = hsmCtor.newInstance();
// 5. CryptoModuleManager (private 생성자 → 리플렉션)
CryptoModuleConfigLoader mockLoader = mock(CryptoModuleConfigLoader.class);
when(mockLoader.findAll()).thenReturn(buildModuleConfigs());
Constructor<CryptoModuleManager> managerCtor = CryptoModuleManager.class.getDeclaredConstructor();
managerCtor.setAccessible(true);
CryptoModuleManager manager = managerCtor.newInstance();
CryptoModuleService cryptoService = new CryptoModuleService();
HsmCryptoService hsmCryptoService = new HsmCryptoService();
// 6. Spring ApplicationContext 구성
springCtx = new GenericApplicationContext();
springCtx.getBeanFactory().registerSingleton("propManager", mockPropManager);
springCtx.getBeanFactory().registerSingleton("hsmManager", hsmManager);
springCtx.getBeanFactory().registerSingleton("hsmCryptoService", hsmCryptoService);
springCtx.getBeanFactory().registerSingleton("cryptoModuleConfigLoader", mockLoader);
springCtx.getBeanFactory().registerSingleton("cryptoModuleManager", manager);
springCtx.getBeanFactory().registerSingleton("cryptoModuleService", cryptoService);
springCtx.getBeanFactory().registerSingleton("cryptoModuleConfigMapper", testMapper());
springCtx.registerBeanDefinition("applicationContextProvider",
BeanDefinitionBuilder.genericBeanDefinition(ApplicationContextProvider.class)
.getBeanDefinition());
springCtx.refresh();
// 7. HsmManager 시작 (SunPKCS11 Provider 초기화 + KeyStore 오픈)
hsmManager.start();
assertTrue(hsmManager.isReady(), "HsmManager 초기화 실패");
System.out.println("[HSM] Provider: " + hsmManager.getPkcs11Provider().getName());
// 8. MASTER_KEY 등록 (없으면 자동 생성)
ensureMasterKey();
// 9. CryptoModuleManager 시작 (모듈 설정 로드)
manager.start();
System.out.println("[Crypto] 모듈 로드 완료");
}
@AfterAll
static void tearDownAll() throws Exception {
if (hsmManager != null && hsmManager.isStarted()) hsmManager.stop();
if (springCtx != null) springCtx.close();
if (tempCfgFile != null) tempCfgFile.delete();
}
@BeforeEach
void setUp() {
mockReq = mock(HttpServletRequest.class);
mockRes = mock(HttpServletResponse.class);
}
// =========================================================================
// 1. HsmKeyDerivationStrategy — HSM 마스터키 직접 사용 (InCryptoFilter)
// =========================================================================
@Test
@DisplayName("1-1. FIELD/GCM HsmKey — doPostFilter 암호화 → doPreFilter 복호화 라운드트립")
void testHsmGcm_field_roundTrip() throws Exception {
InCryptoFilter filter = new InCryptoFilter();
String original = "{\"acno\":\"1234567890\",\"amount\":\"100000\"}";
Properties prop = new Properties();
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
// SCOPE 기본값 FIELD, 경로 기본값 사용
// 암호화: body 전체 → /encrypted_data 필드
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
System.out.println("[1-1] encrypted: " + encrypted);
assertTrue(encrypted.contains("encrypted_data"), "/encrypted_data 필드가 있어야 한다");
// 복호화: /encrypted_data 필드 → body 전체 교체
String decrypted = (String) filter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes);
System.out.println("[1-1] decrypted: " + decrypted);
assertEquals(original, decrypted);
}
@Test
@DisplayName("1-2. BODY/GCM HsmKey — doPostFilter 암호화 → doPreFilter 복호화 라운드트립")
void testHsmGcm_body_roundTrip() throws Exception {
InCryptoFilter filter = new InCryptoFilter();
String original = "{\"acno\":\"1234567890\",\"amount\":\"100000\"}";
Properties prop = new Properties();
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
prop.setProperty(AbstractCryptoFilter.PROP_SCOPE, "BODY");
// 암호화: body 전체 → Base64 암호문
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
System.out.println("[1-2] encrypted(Base64): " + encrypted);
assertNotEquals(original, encrypted, "암호문은 평문과 달라야 한다");
// 복호화: Base64 암호문 → 원문
String decrypted = (String) filter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes);
System.out.println("[1-2] decrypted: " + decrypted);
assertEquals(original, decrypted);
}
@Test
@DisplayName("1-3. FIELD/GCM HsmKey + AAD 헤더 — 동일 요청 ID로 암복호화 성공")
void testHsmGcm_field_withAad_success() throws Exception {
InCryptoFilter filter = new InCryptoFilter();
String original = "{\"amount\":\"500000\"}";
String requestId = "REQ-20240101-001";
when(mockReq.getHeader("X-Request-Id")).thenReturn(requestId);
Properties prop = new Properties();
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
prop.setProperty(AbstractCryptoFilter.PROP_AAD_HEADER, "X-Request-Id");
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
String decrypted = (String) filter.doPreFilter( "G", "A", encrypted, prop, mockReq, mockRes);
System.out.println("[1-3] decrypted: " + decrypted);
assertEquals(original, decrypted);
}
@Test
@DisplayName("1-4. FIELD/GCM HsmKey + AAD 헤더 — 다른 요청 ID로 복호화 시 GCM 인증 실패")
void testHsmGcm_field_withAad_wrongAad_fails() throws Exception {
InCryptoFilter filter = new InCryptoFilter();
String original = "{\"amount\":\"500000\"}";
// 암호화 시 요청 ID
HttpServletRequest encReq = mock(HttpServletRequest.class);
when(encReq.getHeader("X-Request-Id")).thenReturn("REQ-CORRECT");
// 복호화 시 다른 요청 ID
HttpServletRequest decReq = mock(HttpServletRequest.class);
when(decReq.getHeader("X-Request-Id")).thenReturn("REQ-WRONG");
Properties prop = new Properties();
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_HSM_GCM);
prop.setProperty(AbstractCryptoFilter.PROP_AAD_HEADER, "X-Request-Id");
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, encReq, mockRes);
assertThrows(Exception.class,
() -> filter.doPreFilter("G", "A", encrypted, prop, decReq, mockRes),
"잘못된 AAD로 GCM 복호화 시 예외가 발생해야 한다");
System.out.println("[1-4] 다른 AAD 복호화 예외 확인 완료");
}
// =========================================================================
// 2. HsmContextSha256KeyDerivationStrategy — 컨텍스트 기반 SHA-256 파생 키
// =========================================================================
@Test
@DisplayName("2-1. FIELD/GCM ContextSha256 — 동일 컨텍스트로 암복호화 라운드트립")
void testCtxSha256Gcm_field_roundTrip() throws Exception {
InCryptoFilter filter = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_A);
String original = "{\"accNo\":\"0011234567890\",\"amount\":\"50000\"}";
Properties prop = new Properties();
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_CTX_SHA_GCM);
String encrypted = (String) filter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
System.out.println("[2-1] encrypted: " + encrypted);
assertTrue(encrypted.contains("encrypted_data"));
String decrypted = (String) filter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes);
System.out.println("[2-1] decrypted: " + decrypted);
assertEquals(original, decrypted);
}
@Test
@DisplayName("2-2. FIELD/GCM ContextSha256 — 암호화와 다른 컨텍스트로 복호화 시 GCM 인증 실패")
void testCtxSha256Gcm_differentContext_throwsException() throws Exception {
InCryptoFilter encFilter = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_A);
InCryptoFilter decFilter = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_B);
String original = "{\"data\":\"sensitive\"}";
Properties prop = new Properties();
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_CTX_SHA_GCM);
String encrypted = (String) encFilter.doPostFilter("G", "A", original, prop, mockReq, mockRes);
assertThrows(Exception.class,
() -> decFilter.doPreFilter("G", "A", encrypted, prop, mockReq, mockRes),
"다른 컨텍스트 키로 파생된 키는 복호화에 실패해야 한다");
System.out.println("[2-2] 다른 컨텍스트 복호화 예외 확인 완료");
}
@Test
@DisplayName("2-3. FIELD/GCM ContextSha256 — 컨텍스트별 독립 암복호화 (GROUP-A, GROUP-B 각각 성공)")
void testCtxSha256Gcm_perGroupRoundTrip() throws Exception {
InCryptoFilter filterA = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_A);
InCryptoFilter filterB = new ContextAwareCryptoFilter(CTX_KEY, CTX_VAL_B);
String plainA = "{\"group\":\"A\",\"amount\":\"1000\"}";
String plainB = "{\"group\":\"B\",\"amount\":\"2000\"}";
Properties prop = new Properties();
prop.setProperty(AbstractCryptoFilter.PROP_MODULE_NAME, MOD_CTX_SHA_GCM);
String encA = (String) filterA.doPostFilter("G", "A", plainA, prop, mockReq, mockRes);
String encB = (String) filterB.doPostFilter("G", "B", plainB, prop, mockReq, mockRes);
assertEquals(plainA, (String) filterA.doPreFilter("G", "A", encA, prop, mockReq, mockRes));
assertEquals(plainB, (String) filterB.doPreFilter("G", "B", encB, prop, mockReq, mockRes));
System.out.println("[2-3] GROUP-A, GROUP-B 각각 독립 암복호화 성공");
}
// =========================================================================
// 헬퍼
// =========================================================================
private static List<CryptoModuleConfig> buildModuleConfigs() {
return Arrays.asList(
buildDynamic(MOD_HSM_GCM, "AES", "GCM", "NoPadding",
HsmKeyDerivationStrategy.class.getName(),
"{\"hsmKeyAlias\":\"" + MASTER_KEY_ALIAS + "\"}"),
buildDynamic(MOD_CTX_SHA_GCM, "AES", "GCM", "NoPadding",
HsmContextSha256KeyDerivationStrategy.class.getName(),
"{\"hsmKeyAlias\":\"" + MASTER_KEY_ALIAS + "\",\"contextKey\":\"" + CTX_KEY + "\"}")
);
}
private static CryptoModuleConfig buildDynamic(String name, String alg, String mode, String padding,
String strategy, String params) {
CryptoModuleConfig c = new CryptoModuleConfig();
c.setCryptoId(UUID.randomUUID().toString());
c.setCryptoName(name);
c.setAlgType(alg);
c.setCipherMode(mode);
c.setPadding(padding);
c.setKeySourceType("DYNAMIC");
c.setKeyDerivStrategy(strategy);
c.setKeyDerivParams(params);
c.setCacheYn("Y");
c.setCacheTtlSec(60);
c.setUseYn("Y");
// ivHex = null: GCM에서 IV를 AAD 대체값으로 사용하지 않도록 의도적으로 미설정
return c;
}
private static void ensureMasterKey() throws Exception {
java.security.KeyStore ks = hsmManager.getKeyStore();
// 이전 실행 키 삭제 (sensitive 여부 무관하게 항상 고정키로 재등록)
if (ks.containsAlias(MASTER_KEY_ALIAS)) {
ks.deleteEntry(MASTER_KEY_ALIAS);
System.out.println("[HSM] 기존 MASTER_KEY 삭제");
}
// CryptoModuleServiceTest.KEY_128 과 동일한 고정 키 → 두 테스트 간 암호문 비교 가능
// attributes(*, CKO_SECRET_KEY, CKK_AES) 지시어로 임포트 시 CKA_SENSITIVE=false 적용
byte[] keyBytes = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
SecretKey fixedKey = new SecretKeySpec(keyBytes, "AES");
ks.setKeyEntry(MASTER_KEY_ALIAS, fixedKey, null, null);
// 임포트 후 getEncoded() 검증
SecretKey stored = (SecretKey) ks.getKey(MASTER_KEY_ALIAS, null);
byte[] encoded = stored.getEncoded();
System.out.println("[HSM] MASTER_KEY 등록 완료: alias=" + MASTER_KEY_ALIAS
+ " / getEncoded()=" + (encoded != null ? encoded.length + "bytes, " + new String(encoded) : "null (추출 불가!)"));
}
private static void ensureTokenInitialized() throws Exception {
ProcessBuilder pb = new ProcessBuilder(
SOFTHSM2_UTIL, "--init-token", "--free",
"--label", TOKEN_LABEL, "--pin", PIN, "--so-pin", PIN);
pb.redirectErrorStream(true);
Process p = pb.start();
String out = readOutput(p);
p.waitFor(10, TimeUnit.SECONDS);
System.out.println("[SoftHSM2] init-token: " + out.trim());
}
private static CryptoModuleConfigMapper testMapper() {
return new CryptoModuleConfigMapper() {
@Override
public CryptoModuleConfigVO toVo(CryptoModuleConfig e) {
CryptoModuleConfigVO vo = new CryptoModuleConfigVO();
vo.setCryptoId(e.getCryptoId());
vo.setCryptoName(e.getCryptoName());
vo.setCryptoDesc(e.getCryptoDesc());
vo.setAlgType(e.getAlgType());
vo.setCipherMode(e.getCipherMode());
vo.setPadding(e.getPadding());
vo.setIvHex(e.getIvHex());
vo.setKeySourceType(e.getKeySourceType());
vo.setEncKeyHex(e.getEncKeyHex());
vo.setDecKeyHex(e.getDecKeyHex());
vo.setKeyDerivStrategy(e.getKeyDerivStrategy());
vo.setKeyDerivParams(e.getKeyDerivParams());
vo.setCacheYn(e.getCacheYn());
vo.setCacheTtlSec(e.getCacheTtlSec());
vo.setUseYn(e.getUseYn());
return vo;
}
@Override
public CryptoModuleConfig toEntity(CryptoModuleConfigVO vo) {
return null;
}
};
}
private static String readOutput(Process p) throws Exception {
InputStream is = p.getInputStream();
byte[] buf = new byte[4096];
StringBuilder sb = new StringBuilder();
int len;
while ((len = is.read(buf)) != -1) {
sb.append(new String(buf, 0, len, "UTF-8"));
}
return sb.toString();
}
}