[java] Apache XML Security 라이브러리와 XML 서명

Apache XML Security 라이브러리는 XML 문서에 디지털 서명을 추가하고 검증하기 위한 기능을 제공합니다. 이 라이브러리를 사용하면 안전한 웹 서비스와 메시지 교환을 보장할 수 있습니다. 이번 글에서는 Apache XML Security 라이브러리를 사용하여 XML 문서를 서명하고 검증하는 방법에 대해 알아보겠습니다.

Apache XML Security 라이브러리란?

Apache XML Security 라이브러리는 XML 기반의 보안 표준을 구현하는 Java 및 C++ 라이브러리입니다. XML 서명 및 암호화의 기능을 제공하며, XML 디지털 서명 및 검증을 위한 API를 제공합니다. 이를 통해 XML 문서의 무결성과 신원을 보호할 수 있습니다.

XML 문서 서명하기

XML 문서를 서명하려면 먼저 Apache XML Security 라이브러리를 프로젝트에 추가해야 합니다. 그런 다음, 다음과 같은 코드로 XML 문서를 서명할 수 있습니다.

// Create a DOM XMLSignatureFactory that will be used to generate the enveloped signature
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

// Create a Reference to the enveloped document as inElement (we are just wrapping the entire xml with this)
Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null));

// Create the SignedInfo
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));

// Create a KeyInfo and add the KeyValue to it
KeyInfoFactory kif = fac.getKeyInfoFactory();
KeyValue kv = kif.newKeyValue(key);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

// Create a DOMSignContext and specify the RSA PrivateKey and Document
DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement());

// Create the XMLSignature (but don't sign it yet)
XMLSignature signature = fac.newXMLSignature(si, ki);

// Marshal, generate, and sign the enveloped signature
signature.sign(dsc);

위 코드는 XML 문서를 서명하기 위한 간단한 예제입니다. 이를 통해 Apache XML Security 라이브러리를 사용하여 XML 문서에 서명할 수 있습니다.

XML 서명 검증하기

이제 서명된 XML 문서를 검증하는 방법을 살펴보겠습니다. Apache XML Security 라이브러리를 사용하여 다음과 같이 서명된 XML 문서를 검증할 수 있습니다.

// Find the Signature element
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

if (nl.getLength() == 0) {
    throw new RuntimeException("Cannot find Signature element");
}

// Create a DOMValidateContext and specify the RSA PublicKey and Document
DOMValidateContext valContext = new DOMValidateContext(publicKey, nl.item(0));

// Unmarshal the XMLSignature
XMLSignature signature = fac.unmarshalXMLSignature(valContext);

// Validate the XMLSignature (generated above)
boolean isValid = signature.validate(valContext);

위 코드는 서명된 XML 문서의 유효성을 확인하는 방법을 보여줍니다. 이를 통해 Apache XML Security 라이브러리를 사용하여 XML 서명을 검증할 수 있습니다.

마치며

Apache XML Security 라이브러리를 사용하면 XML 문서에 대한 디지털 서명을 쉽게 추가하고 검증할 수 있습니다. 이를 통해 안전한 데이터 교환을 보장하고 데이터의 무결성을 확보할 수 있습니다. 자세한 내용은 Apache XML Security 라이브러리의 공식 문서를 참고하시기 바랍니다.

Apache XML Security 라이브러리 공식 문서