DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
XML 安全實作(下):XML 加密與 XML 簽名的完整流程
編輯:XML詳解     

Web 服務這類新興技術把 XML 大量用在資料交換上,於是 XML 在傳輸與儲存過程中的安全性就成了繞不開的課題。本系列分兩篇:上篇談 XML 安全背後的基礎技術,本篇則進入核心——XML 加密與 XML 簽名,並逐步示範如何用它們保護一段 XML 訊息。

先回答一個自然的疑問:既然 SSL 之類的既有技術已經能加密 XML 文件(就跟加密任何其他文件一樣),為什麼還需要另一套加密標準?答案藏在 XML 加密的設計目標裡。

XML 加密

XML 加密的首要目標包括:

  • 支援對任意數位內容加密,XML 文件只是其中一種。
  • 確保加密後的資料無論在傳輸途中還是儲存期間,都不會被未經授權者讀取。
  • 在訊息傳遞的每一跳都維持資料的安全性。這句話的重點是:不只傳輸過程中要安全(SSL 保證的就是這件事),資料停留在某個節點上時也要安全。
  • 以 XML 的形式表現被加密的資料。
  • 可以只挑選 XML 文件中的某一部分來加密。

把這些目標跟 HTTP 上的 SSL(也就是 HTTPS)比對一下就很清楚了。若採用 HTTPS,整條訊息都會被加密;抵達第一個目的地後整條訊息被解密,在它被重新完整加密、送往第二跳節點之前,有一段時間是暴露在嗅探風險之下的。換句話說,HTTPS 提供的加密只存在於傳輸過程中,並不持久。

XML 加密概覽

「加密後的資料要用 XML 表現」這個目標,直接決定了輸出文件的樣貌。其中有兩個元素特別需要理解:

  • <EncryptedData>:容納除了加密金鑰之外的所有加密內容。
  • <EncryptedKey>:當加密金鑰本身也被加密時,結果就放在這裡。

除了密文之外,XML 加密還允許在這兩個元素中指定所用的加密演算法,或者直接放入加密金鑰。這意味著你可以把金鑰隨密文一起保存、後續再引用,或者透過其他傳輸機制另外送給接收方。

要特別注意:XML 加密並沒有定義任何新的加密演算法,它只沿用既有演算法。

加密流程實作

下面用一段普通的 XML 當素材,走一遍加密的每個步驟。先看原始文件。

清單 1. XML 範例

<?XML version="1.0"?>
<PurchaseOrderRequest>
  <Order>
    <Item>
      <Code>Screw001</Code>
      <Description>Screw with half centimeter thread</Description>
    </Item>
    <Quantity>2</Quantity>
  </Order>
  <Payment>
    <CreditCard>
      <Type>MasterCard</Type>
      <Number>1234567891234567</Number>
      <ExpiryDate>20050501</ExpiryDate>
    </CreditCard>
    <PurchaseAmount>
      <Amount>30000</Amount>
      <Currency>INR</Currency>
      <Exponent>-3</Exponent>
    </PurchaseAmount>
  </Payment>
</PurchaseOrderRequest>

清單 2 示範如何只加密清單 1 的一部分,之後再逐步解釋每個環節。

清單 2. XML 加密程式碼

//Get the DOM document object for the XML that you
// want to encrypt.
// getDocument method that takes XML file name as input
// and returns DOM document provided in Listing 3 (Step 1)
Document doc = XmlUtil.getDocument(XMLFileName);
String xpath = "/PurchaseOrderRequest/Payment";
// Step 2. Get the shared secret. This key is used to encrypt the
// XML content
Key dataEncryptionKey = getKey();
// Algorithm type used to generate shared secret
// i.e. content encryption key
AlgorithmType dataEncryptionAlgoType = AlgorithmType.TRIPLEDES;
// Get the key pair. You are interested in the public key
// as that is the one you will use for encrypting the
// XML content
KeyPair keyPair = getKeyPair();
// Step 3. Get the public key of the key pair
Key keyEncryptionKey = keyPair.getPublic();
// Algorithm type used to generate the public
// private key pair
AlgorithmType keyEncryptionAlgoType = AlgorithmType.RSA1_5;
KeyInfo keyInfo = new KeyInfo();
// Step 4
try {
    Encryptor enc =
        new Encryptor(
            doc,
            dataEncryptionKey,
            dataEncryptionAlgoType,
            keyEncryptionKey,
            keyEncryptionAlgoType,
            keyInfo);
    XPath xpath = new XPath(xPath);
    // Step 5
    try {
        enc.encryptInPlace(xpath);
    } catch (XPathException e1) {
        System.out.println("XPath is not correct");
        e1.printStackTrace();
    }
    XmlUtil.XMLOnStdOut(doc);
} catch (Exception e) {
    System.out.println("Some exception");
    e.printStackTrace();
}

步驟 1:把 XML 轉成 DOM 物件。

清單 3. 由 XML 建立 DOM 物件

public static Document getDocument(String fileName) {
    Document doc = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    File f = new File(fileName);
    DocumentBuilder builder = null;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        System.out.println("Parse configuration exception");
        e.printStackTrace();
    }
    try {
        doc = builder.parse(f);
    } catch (Exception e1) {
        System.out.println("Some exception");
        e1.printStackTrace();
    }
    return doc;
}

步驟 2:取得共享金鑰(shared secret),它就是真正用來加密 XML 內容的那把鑰匙。本文附帶的程式碼所搭配的加密實作只認三重 DES(Triple-DES),因此範例就用這種演算法產生金鑰。

步驟 3:取得公鑰—私鑰對中的公鑰,用它來加密共享金鑰。如系列上篇所述,這組金鑰對是以 RSA 演算法產生的。

步驟 4:拿資料加密金鑰、金鑰加密金鑰、兩者對應的演算法,以及未來要放進輸出文件的金鑰資訊,一起建立一個 Encryptor 物件。注意:建立時指定的演算法必須與實際金鑰相符。Encryptor 是整個加密流程的主角,類別位於 com.verisign.xmlenc 套件,依 W3C XML Encryption 規範進行加密。你可以指定要加密的是 Element 還是 Content;清單 2 用的是 Element,也是預設值。此外,Encryptor 必須能解讀 XPath 運算式,才能定位到要加密的 XML 元素。

步驟 5:最後呼叫 Encryptor 的 encrypt 或 encryptInPlace,並把 XPath 傳進去。該 XPath 所指向的元素、它的所有子元素,以及它身上的屬性都會被加密。本例加密的是 /PurchaseOrderRequest/Payment。兩個方法都會用共享金鑰加密指定的 XML 元素、用公鑰加密共享金鑰,並把加密結果嵌進輸出文件裡。唯一的差別是:encrypt 回傳一個全新的、含加密資料的 DOM 文件;encryptInPlace 則直接改寫傳入的原始文件。加密後的結果如下。

清單 4. 加密後的 XML

<?XML version="1.0" encoding="UTF-8"?>
<PurchaseOrderRequest>
  <Order>
    <Item>
      <Code>Screw001</Code>
      <Description>Screw with half centimeter thread</Description>
    </Item>
    <Quantity>2</Quantity>
  </Order>
  <xenc:EncryptedData Type="https://www.w3.org/2001/04/XMLenc#Element"
   xmlns:xenc="https://www.w3.org/2001/04/XMLenc#">
    <xenc:EncryptionMethod Algorithm=
     "https://www.w3.org/2001/04/XMLenc#tripledes-cbc"/>
    <ds:KeyInfo xmlns:ds="https://www.w3.org/2000/09/xmldsig#">
      <xenc:EncryptedKey>
        <xenc:EncryptionMethod Algorithm=
         "https://www.w3.org/2001/04/XMLenc#rsa-1_5"/>
        <xenc:CipherData>
          <xenc:CipherValue>
           F1aIpdp3axm8nFofx/xX62VlsxildddHcxaevd7sbr+lv/fzZ7e8ovmKGQopAjclxPTybpkW
           YG8GVcOIbD4UGR24CNxeB7eZCws5/RKBTqKp+76FkVxf+G+EqgMmueRqoaF4oYOrTKquWLnR
           kiSOFmplRaJ8G7bR2j0eTFdiFRk=
          </xenc:CipherValue>
        </xenc:CipherData>
      </xenc:EncryptedKey>
    </ds:KeyInfo>
    <xenc:CipherData>
      <xenc:CipherValue>
       KMkufRUY7rs0i+4jX6VhviiUIbYWay1KbwhTQxH9SaqJ6HA+Qc2Ce7TVZUQuH0GGD4xTR8hB
       hOls+hgHA16EfmmxLd3E+YqO4sXQ+GkX9O9EcO4ULha/q1KmP2yNGNy/tavdj9a7JuZnnNGV
       /M4gxdt5fCJXT0A9bw9HwKR/Pc81rZYWa7fOrmvDvC7Q+//OCzkqcAaCmAHEySWbv2vK3T+a
       GlQOI2Wooxa9hm7Dx70BuLI8ihhSAV3moK+JAPdn1vdCpoFKdzzq2HSh/yOisYZvQOh+jIks
       MW8oUzWnVUe/DFztPtvvDKbPE/xoAasixlbDLa42gFFe9uzEeIG89XBMSkZtTio0zn9xPPSf
       Dc0WFMy+UoLnCA==
      </xenc:CipherValue>
    </xenc:CipherData>
  </xenc:EncryptedData>
</PurchaseOrderRequest>

清單 4 是一份「部分加密」的文件。只有握有加密時所用公鑰對應私鑰的接收者,才能讀懂被加密的那一段。

解密流程實作

清單 5 示範如何把加密後的 XML 還原。

清單 5. XML 解密

// Get the DOM document object for the XML that you
// want to decrypt (The one shown in Listing 4)
// The getDocument method that takes an XML file name as input
// and returns a DOM document is provided in Listing 3 (Step 1)
Document doc = XmlUtil.getDocument(encryptedXMLFileName);
// Step 2. Get the private key of the pair whose public key was
// used to encrypt the XML
Key privateKey = keyPair.getPrivate();
// Specifying the XPath at which encrypted data is lying
// in the XML
// Step 3. Specify XPath expression
String xpath = "//xenc:EncryptedData";
// Specify the namespace that relates to the XPath
// expression
String[] ns =
    { "xenc", "https://www.w3.org/2001/04/XMLenc#" };
// Create the XPath helper with the XPath expression and a map
// of namespaces that relate to the XPath expression
XPath xpath = new XPath(xPath, ns);
// Step 4. Create the Decryptor object with decryption key and
// location of the encrypted data to be decrypted
Decryptor decrypt = null;
try {
    decrypt = new Decryptor(doc, privateKey, xpath);
} catch (Exception e) {
    System.out.println("Some exception");
    e.printStackTrace();
}
// Step 5. Method decryptInPlace is called to decrypt the
// encrypted contents of the XML
try {
    decrypt.decryptInPlace();
} catch (Exception e1) {
    System.out.println("Some exception");
    e1.printStackTrace();
}

步驟 1:把加密後的 XML 轉成 DOM 物件,做法與加密時相同。

步驟 2:取出金鑰對中對應的私鑰。切的來說,這裡要的是「加密時所用公鑰」的那把私鑰。

步驟 3:建立 XPath 與相關命名空間,用來指出密文在文件中的位置。本例的 XPath 是 //xenc:EncryptedData。不論原本被加密的是哪個元素,密文永遠掛在 xenc:EncryptedData 之下;寫成 //xenc:EncryptedData 的意思是「在文件中任何可能出現密文的地方尋找 EncryptedData 元素」。

步驟 4:用解密密鑰與密文位置建立 Decryptor 物件。Decryptor 是解密流程的主角,類別同樣位於 com.verisign.xmlenc 套件,依 W3C XML Encryption 規範作業,支援 Element 與 Content 兩種型別,並需能解讀 XPath 以定位要解密的元素。

步驟 5:最後呼叫 decryptInPlace 或 decrypt。兩者都會先用私鑰解開內嵌在訊息中的共享金鑰,再用這把共享金鑰還原其餘內容。差別只在:decrypt 會建立一個新的 DOM 物件裝解密結果,decryptInPlace 則直接在傳入的同一個 DOM 物件上就地解密。

XML 簽名

數位簽章已經行之有年,任何數位內容都能用公開金鑰密碼標準(最常見的是 PKCS#7 簽章)簽署;S/MIME 則讓簽章能附加在電子郵件上,使接收方得以驗證寄件者身份。XML 簽名是對這套既有基礎設施的延伸,其設計目標包括:

  • 在數位簽章周圍建立結構,讓簽章本身也能以 XML 文件的形式表現。
  • 只對一部分 XML 簽名,其餘保持不簽。
  • 對同一份 XML 文件的不同部分套用多組以上的簽章。
  • 讓簽章不只服務於傳輸與通訊,還能長期保存。

XML 簽名概覽

XML 簽名可用於對任何數位內容簽章,XML 文件只是其中一類。簽章過程分兩階段:第一階段先對數位內容做正規化,把結果放進一個 XML 元素;第二階段再對這個正規化後的值簽章。之所以要分兩階段,理由很單純:正規化之後得到的是一個很小但唯一的密碼結果(稱為摘要),對它簽名的時間遠比對原始全文簽名少得多。

簽完之後,結果以一個 <Signature> 元素表示。它與原始內容的相對關係,決定了簽章屬於哪一種型別:

  • 封外簽名(Enveloping signature):<Signature> 元素把被簽章的內容包在裡面,後者成為它的子元素。
  • 封內簽名(Enveloped signature):<Signature> 元素成為被簽章資料的子元素,並透過內部的 <Reference> 元素所給的資訊指回被簽章的內容。
  • 分離簽名(Detached signature):<Signature> 與被簽章內容各自獨立。兩者可以在同一份文件裡,也可以完全分屬不同文件。

除了指向被簽章的內容之外,<Signature> 元素還承載了這些資訊:用來把數位內容正規化的方法、對正規化結果產生簽章所用的演算法,以及在正規化之前如何處理待簽章元素的附加資訊。

簽章流程實作

接著沿用清單 1 的例子,走完一次完整的簽章過程。

清單 6. 數位簽章流程

// Get the DOM document object for the XML that you
// want to digitally sign.
// getDocument method that takes XML file name as input
// and returns DOM document is provided in Listing 3 (Step 1)
Document doc = XmlUtil.getDocument(XMLFileName);
// XPath expression that is to be digitally signed
String xpath = "/PurchaseOrderRequest/Payment";
// Step 2. Get both the public and private keys. The private key is
// used to digitally sign the content, whereas the public key
// is sent along with the digitally signed content for the
// receiver to verify the digital signature.
KeyPair keyPair = getKeyPair();
PublicKey verificationKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Step 3. Create a signer object passing the document whose part
// is to be signed, the private key to be used for
// signing, and the public key that is to be used
// for verification.
Signer signer = null;
// Step 4
try {
    signer = new Signer(doc, privateKey, verificationKey);
    XPath location1 =
        new XPath("/PurchaseOrderRequest/Payment/CreditCard");
    signer.addReference(location1);

    XPath location2 =
        new XPath("/PurchaseOrderRequest/Payment/PurchaseAmount");
    signer.addReference(location2);
} catch (Exception e) {
    e.printStackTrace();
}
// Step 5. Use the signer object to sign the document passing the
// XPath of the element that is to be signed.
try {
    d = signer.sign(new XPath(xPath));
} catch (Exception e1) {
    e1.printStackTrace();
}

步驟 1:和加密時一樣,先把要簽章的 XML 轉成 DOM 物件。

步驟 2:取得系列上篇「產生公鑰—私鑰對」一節中所建立的金鑰對,公私鑰都要。私鑰用來簽章,公鑰則隨簽章後的訊息一起送到接收方,供其驗證。前面提過,這組金鑰對以 RSA 為基礎。

步驟 3:以待簽章的 DOM 文件、簽章用私鑰、驗證用公鑰建立 Signer 物件(驗證用公鑰並非必填)。Signer 是簽章流程的主角,類別位於 com.verisign.xmlsig 套件,依 W3C XML Signature 規範作業,並支援封外、封內、分離三種模式。

步驟 4:指定要簽章的部分。方法是呼叫 Signer 的 addReference,並把目標元素的 XPath 傳入。想簽多個元素就多次呼叫 addReference——範例中我們同時掛上了 CreditCard 與 PurchaseAmount 兩處。

步驟 5:最後呼叫 signer.sign 完成簽章。若不傳任何參數,產生的是封外簽名;若傳入 XPath 並把簽章放回文件內,則產生封內簽名。

結語

走到這裡,我們已經把「安全」的定義、XML 正規化、PKI 基礎設施、XML 加密與 XML 簽名依序鋪陳完畢。從理論到程式碼,希望這一整套說明能讓 XML 安全不再顯得神祕——實作 XML 加密與數位簽章,其實沒有想像中那麼難。

後續文章會接著談安全性宣告標記語言(SAML)與 XML 金鑰管理系統(XKMS)。SAML 能在不同協作實體之間傳遞憑證以及其他與主體、人員相關的資訊,且不會失去資訊的歸屬關係;XKMS 則把管理公開金鑰基礎設施(PKI)的複雜度從用戶端應用中抽離,交給可信的第三方處理,讓 PKI 的日常管理大幅簡化。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved