4.2.8 鍵合意で作成した鍵を利用してデータを復号化する
暗号化されたXMLデータの要素やコンテンツ,バイナリデータ,または鍵を復号化する場合に使用する鍵は,鍵合意で生成できます。鍵合意で鍵を生成するには,AgreementMethodクラスを使用します。この項では,Diffie-Hellman鍵合意アルゴリズムで生成した共通鍵を利用してデータを復号化するアプリケーションの開発の流れを,コーディング例を示して説明します。
(1) Documentオブジェクトの取得
JAXPのDocumentBuilderを使用して暗号化されたデータを含むXML文書を読み込み,Documentオブジェクトを取得します。Documentオブジェクトを取得するときに,名前空間が有効になるように設定してください。コーディングの例を次に示します。
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(input);
(2) 暗号データの取得
DocumentオブジェクトからEncryptedData要素を取得し,EncryptedDataオブジェクトを生成します。コーディングの例を次に示します。
Element encelem = Utilities.getElement(
doc, XMLEncryption.XMLNS,"EncryptedData");
if (encelem == null) {
System.err.println("missing xenc:EncryptedData");
}
(3) 暗号構文の構築
XMLEncryptionFactoryクラスを使用して,EncryptedData要素以下の構文に対応するオブジェクトを生成します。コンテキストの処理モードは,「復号化」を指定してください。オブジェクトを生成したら,復号化に必要な暗号アルゴリズムを指定します。このとき,復号化に使用する鍵も取得します。コーディングの例を次に示します。
XMLEncryptionFactory xef =
XMLEncryptionFactory.newInstance();
XMLSecurityContext context = new XMLSecurityContext(
XMLSecurityContext.Mode.DECRYPT, doc);
EncryptedData ed = xef.newEncryptedData(context, encelem);
EncryptionMethod em = ed.getEncryptionMethod();
KeyInfo ki = ed.getKeyInfo();
XMLEncryption xenc = xef.newXMLEncryption(em, ki);
(4) 鍵合意による共通鍵の生成
XML Security - Coreでは,Diffie-Hellman鍵合意アルゴリズムを利用して,復号化に必要な共通鍵を生成します。ここでは,次の三つの処理について,コーディング例を示して説明します。
-
AgreementMethodオブジェクトの取得
-
鍵合意のコンテキストの設定
-
共通鍵の作成
(a) AgreementMethodオブジェクトの取得
Diffie-Hellman鍵合意アルゴリズムで生成した鍵を使用して暗号化されたデータを復号化するには,まずKeyInfo要素からAgreementMethodオブジェクトを取得します。コーディングの例を次に示します。
AgreementMethod am = (AgreementMethod) ki.getSingleContent(
XMLEncryption.XMLNS, "AgreementMethod");
if (am == null) {
throw new Exception("missing xenc:AgreementMethod");
}(b) 鍵合意のコンテキストの設定
鍵合意に必要な情報をDHKeyAgreementContextに設定します。コンテキストの設定では,鍵合意によって作成される共通鍵を使用するアルゴリズム,受信者の秘密鍵,および送信者の公開鍵が必要です。コーディングの例を次に示します。
DHKeyAgreementContext kac = new DHKeyAgreementContext(em,
Utilities.getBobDHPrivateKey(),
Utilities.getAliceDHPublicKey());- 参考
-
受信者の秘密鍵および送信者の公開鍵は,RecipientKeyInfo要素またはOriginatorKeyInfo要素から取得することもできます。
(5) データの復号化
データを復号化する前に,復号化に必要な鍵をコンテキストに設定しておきます。次に,XMLEncryptionクラスのdecryptXMLメソッドを使用して,暗号データを復号化します。最後に,EncryptedDataクラスのreplaceメソッドを使用してEncryptedData要素を復号化したデータに置き換えます。コーディングの例を次に示します。
context.setKeyResolver(new AdhocKeyResolver(key));
DOMFragment decrypted = xenc.decryptXML(context, ed);
ed.replace(context, decrypted);
(6) 復号化結果の出力
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();