この項では,鍵データを暗号化するアプリケーションの開発の流れを,コーディング例を示して説明します。
JAXPのDocumentBuilderを使用して空のDocumentオブジェクトを生成します。ここで生成するDocumentオブジェクトは,EncryptedKey要素を文書要素とする暗号文書を作成するために必要となります。Documentオブジェクトを生成するときには,名前空間が有効になるように設定してください。コーディングの例を次に示します。
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().newDocument();
XMLEncryptionFactoryクラスを使用してXMLEncryptionインタフェースを生成し,暗号化に必要な暗号アルゴリズムを指定します。ここでは,暗号アルゴリズムにTripleDES鍵ラッピングを指定する場合のコーディングの例を示します。
XMLEncryptionFactory xef =
XMLEncryptionFactory.newInstance();
EncryptionMethod em = xef.newEncryptionMethod(
EncryptionMethod.URI_KEYWRAP_TRIPLEDES, null);
XMLEncryption xenc = xef.newXMLEncryption(em, null);
暗号データを生成するときは,コンテキストおよび暗号化対象の鍵データを指定してから,暗号データを生成します。ここでは,次の三つの処理について,コーディング例を示して説明します。
鍵データの暗号化に必要なコンテキストを設定します。暗号化に使用する鍵暗号化鍵で鍵リゾルバを生成し,コンテキストに鍵リゾルバを設定します。コンテキストの処理モードは,「暗号化」を指定してください。コーディングの例を次に示します。
XMLSecurityContext context = new XMLSecurityContext(
XMLSecurityContext.Mode.ENCRYPT, doc);
context.setKeyResolver(
new AdhocKeyResolver(Utilities.getSecretKey()));
暗号化の対象とする鍵データを生成して,指定します。TripleDES鍵を暗号化の対象とする場合のコーディングの例を次に示します。
SecretKey wk = Utilities.generateSecretKey("DESede", 168);
System.out.println("wrapped key="
+ Utilities.toHexString(wk.getEncoded()));
DataContainer toBeEncrypted =
new DataContainer(wk.getEncoded());
「(b) 暗号化対象の指定」で指定した鍵データの暗号値を計算します。コーディングの例を次に示します。
DataContainer encrypted =
xenc.encrypt(context, toBeEncrypted);
XMLEncryptionFactoryクラスを使用して,EncryptedKey要素以下の構文に対応するオブジェクトを生成します。この場合,CipherValue要素を使用して「(3)(C) 暗号データの生成」で計算した暗号値を設定します。次に,EncryptedDataクラスのgenerateメソッドを使用して,EncryptedKey要素を生成します。生成したEncryptedKey要素は,Documentオブジェクトに挿入します。コーディングの例を示します。
CipherData cd = xef.newCipherData(xef.newCipherValue(
encrypted.getAsByteArray()));
EncryptedKey ek =
xef.newEncryptedKey(em, null, cd, null, null, null);
Element encelem = ek.generate(context);
doc.appendChild(encelem);
XMLSerializerクラスを使用して,暗号化したい鍵データをEncryptedKey要素として挿入した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();