2012-10-29 21 views
9

我需要使用ruby簽署xml,有人知道任何方法或lib的嗎?如何在ruby中執行xml簽名

我的XML框架是:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<Message> 
    <MessageId> 
     <ServiceId>service</ServiceId> 
     <Version>1.0</Version> 
     <MsgDesc>Service Description</MsgDesc> 
     <Code>4</Code> 
     <FromAddress>from</FromAddress> 
     <ToAddress>to</ToAddress> 
     <Date>2012-10-29</Date> 
    </MessageId> 
    <MessageBody/> 

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> 
    <SignedInfo> 
    <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> 
    <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> 
    <Reference URI=""> 
    <Transforms> 
     <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> 
    </Transforms> 
    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> 
    <DigestValue>??????</DigestValue> 
    </Reference> 
    </SignedInfo> 

    <SignatureValue>????????????</SignatureValue> 
    <KeyInfo> 
    <X509Data> 
     <X509Certificate>????????</X509Certificate> 
    </X509Data> 
    </KeyInfo> 
</Signature> 
</message> 

我試過的DigestValue此代碼,我已經測試過它,它與我的Java例子比較,但DigestValue中沒有與我的Java例的響應匹配:

require 'base64' 
require 'openssl' 

to_sign_xml = File.read 'service.xml' 
digest = OpenSSL::Digest::SHA1.digest(to_sign_xml) 

digest = Base64.encode64(digest.to_s).gsub(/\n/, '') 
raise digest.inspect 

我的文件service.xml中包含:

<Message> 
    <MessageId> 
     <ServiceId>service</ServiceId> 
     <Version>1.0</Version> 
     <MsgDesc>Service Description</MsgDesc> 
     <Code>4</Code> 
     <FromAddress>from</FromAddress> 
     <ToAddress>to</ToAddress> 
     <Date>2012-10-29</Date> 
    </MessageId> 
    <MessageBody/> 
<Message> 
+2

你沒見過拿考慮規範化,比照。 http://www.w3.org/TR/xml-exc-c14n/在你的情況。 – mkl

+3

我對你將要進入的痛苦世界提前道歉=)看到這個相關的問題:http://stackoverflow.com/questions/3038757/canonicalizing-xml-in-ruby – maerics

回答

2

不幸的是,XML小號忽略創建和驗證非常複雜。詳情可在spec中找到。我開始實施它作爲stdlib some time ago的補充,但之後因爲另一個項目變得更加重要而停止,並且Nokogiri開始提供我需要的Canonicalization功能,並且不幸已經直接使用libxml實現了這些功能。你可能想看看有什麼需要,然後將想法移植到普通的Nokogiri代碼中。

使用這些,應該可以在Ruby中完全實現XML-DSIG。但要做好準備,這不是一件容易的事情,很多很多小細節都有很大的潛力推動你堅果......

你可能會更好轉換到JRuby,並通過集成XML的default implementation -DSIG與Java標準庫一起提供。