この項では,XMLデータの要素またはコンテンツを復号化するアプリケーションの開発の流れを,コーディング例を示して説明します。
JAXPのDocumentBuilderを使用して暗号化されたデータを含むXML文書を読み込み,Documentオブジェクトを取得します。Documentオブジェクトを取得するときに,名前空間が有効になるように設定してください。コーディングの例を次に示します。
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(input);
DocumentオブジェクトからEncryptedData要素を取得し,EncryptedDataオブジェクトを生成します。コーディングの例を次に示します。
Element encelem =
Utilities.getElement(doc, XMLEncryption.XMLNS,
"EncryptedData");
if (encelem == null) {
throw new Exception("missing xenc:EncryptedData");
}
XMLEncryptionFactoryクラスを使用して,EncryptedData要素以下の構文に対応するオブジェクトを生成します。なお,オブジェクトを生成する前に,復号化に必要なコンテキストを設定しておく必要があります。コンテキストの処理モードは,「復号化」を指定してください。
オブジェクトを生成したら,復号化に必要な暗号アルゴリズムを指定します。このとき,復号化に使用する鍵を取得し,コンテキストに設定します。
コーディングの例を次に示します。
XMLEncryptionFactory xef =
XMLEncryptionFactory.newInstance();
XMLSecurityContext context = new XMLSecurityContext(
XMLSecurityContext.Mode.DECRYPT, doc);
EncryptedData ed = xef.newEncryptedData(context, encelem);
XMLEncryption xenc =
xef.newXMLEncryption(
ed.getEncryptionMethod(),ed.getKeyInfo());
context.setKeyResolver(
new AdhocKeyResolver(Utilities.getSecretKey()));
XMLEncryptionクラスのdecryptXMLメソッドを使用して,暗号データを復号化します。次に,EncryptedDataクラスのreplaceメソッドを使用してEncryptedData要素を復号化したデータに置き換えます。コーディングの例を次に示します。
DOMFragment decrypted = xenc.decryptXML(context, ed);
ed.replace(context, decrypted);
XMLSerializerクラスを使用して,EncryptedData要素を復号したデータに置き換えた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();