この項では,Detached署名を生成する場合の処理内容とコーディング例を説明します。
JAXPのDocumentBuilderを使用して空のDocumentオブジェクトを生成します。ここで生成するDocumentオブジェクトは,Signature要素を文書要素とする署名文書を作成するために必要となります。Documentオブジェクトを取得するときに,名前空間が有効になるように設定してください。コーディングの例を次に示します。
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
XMLSignatureFactoryクラスを使用して,各要素に対応するオブジェクトを生成します。署名対象および各種アルゴリズムは,XML署名構文を構築するときに設定しておきます。ここでは,次の設定をする場合の例を説明します。
コーディングの例を次に示します。
XMLSignatureFactory xsf = XMLSignatureFactory.newInstance();
Reference ref = xsf.newReference(
new File(input).toURI().toString(),
xsf.newDigestMethod(DigestMethod.URI_SHA1, null),
Collections.singletonList(xsf.newTransform(
Transform.URI_C14N_OMIT_COMMENTS, null)));
SignedInfo si =
xsf.newSignedInfo(xsf.newCanonicalizationMethod(
CanonicalizationMethod.URI_OMIT_COMMENTS, null),
xsf.newSignatureMethod(
SignatureMethod.URI_RSA_SHA1, null),
Collections.singletonList(ref));
XMLSignature sig = xsf.newXMLSignature(si, null, null);
Detached署名データを生成するには,コンテキストおよび署名生成位置を指定する必要があります。ここでは,次の三つの処理について,コーディング例を示して説明します。
Detached署名データの生成に必要なコンテキストを設定します。署名に使用する鍵を使って鍵リゾルバを生成し,コンテキストに鍵リゾルバを設定します。コンテキストの処理モードは,「署名生成」を指定してください。コーディングの例を次に示します。
XMLSecurityContext context = new XMLSecurityContext(
XMLSecurityContext.Mode.SIGN, doc);
context.setKeyResolver(
new AdhocKeyResolver(Utilities.getPrivateKey()));
署名対象のDocumentオブジェクト中の,どの位置にXML署名を生成するのかを設定します。次の例では,Signature要素が新しい文書要素となります。コーディングの例を次に示します。
DOMPosition pos = new DOMPosition(doc, null);
XMLSignatureクラスのsignメソッドを使用して,Signature要素の署名値を生成します。Reference要素のダイジェスト値と同時に,Signature要素の署名値も生成されます。コーディングの例を次に示します。
sig.sign(context, pos);
XMLSerializerクラスを使用して,Signature要素を持つDocumentオブジェクトをXML形式で出力します。冗長な名前空間を省略し,Shift_JISで出力する場合のコーディングの例を次に示します。
XMLOutputFormat format = new XMLOutputFormat();
format.setOmitRedundantNamespaceDecls(true);
format.setEncoding("Shift_JIS");
OutputStream os = new BufferedOutputStream(
new FileOutputStream(output));
XMLSerializer xsr = new XMLSerializer(os, format);
xsr.serialize(doc);
os.close();