package com.vmis.interfaceapp.gpki; import com.vmis.interfaceapp.config.properties.GpkiProperties; import com.vmis.interfaceapp.util.GpkiCryptoUtil; import lombok.extern.slf4j.Slf4j; /** * Real GPKI service backed by native GPKI JNI via legacy NewGpkiUtil wrapper. * Uses YAML-configured paths and options in {@link GpkiProperties}. */ @Slf4j public class RealGpkiService implements GpkiService { private final GpkiProperties gpkiProps; private final GpkiCryptoUtil crypto; public RealGpkiService(GpkiProperties gpkiProps) { this.gpkiProps = gpkiProps; try { this.crypto = GpkiCryptoUtil.from(gpkiProps); } catch (Exception e) { throw new IllegalStateException("Failed to initialize GPKI (JNI) util. Check YAML paths/passwords and license.", e); } } @Override public String encrypt(String plain) throws Exception { String charset = gpkiProps.getCharset(); String targetId = gpkiProps.getTargetServerId(); boolean useSign = gpkiProps.isUseSign(); try { // 샘플 순서 준수: encrypt(bytes) → (서명) → Base64 return crypto.encryptThenSignToBase64(plain, targetId, charset, useSign); } catch (Exception e) { String detail = extractGpkiDetail(e); if (detail != null) { log.warn("[GPKI-ENC-ERR] targetId={}, detail={}", targetId, detail); } throw e; } } @Override public String decrypt(String cipher) throws Exception { String charset = gpkiProps.getCharset(); boolean useSign = gpkiProps.isUseSign(); try { // 샘플 순서 준수: Base64 decode → (서명검증) → decrypt → String 변환 return crypto.decodeValidateThenDecrypt(cipher, charset, useSign); } catch (Exception e) { String detail = extractGpkiDetail(e); if (detail != null) { log.warn("[GPKI-DEC-ERR] detail={}", detail); } throw e; } } @Override public boolean isEnabled() { return true; } private static String extractGpkiDetail(Throwable t) { if (t == null) return null; Throwable root = t; int guard = 0; while (root.getCause() != null && root.getCause() != root && guard++ < 20) { root = root.getCause(); } String msg = root.getMessage(); if (msg == null) return null; int idx = msg.indexOf("gpkiErrorMessage="); if (idx >= 0) { return msg.substring(idx + "gpkiErrorMessage=".length()).trim(); } return msg; } }