2012-10-29 83 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标准库一起提供。