doubeishuai6598 2013-11-06 17:51
浏览 112

使用PHP对XML文件进行数字签名

I need to sign a XML file with a private RSA key to be verified with my C# application. When I sign the xml with my C# application, this is the final output:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
    <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>VIRRzqwb20aCSXrRTX1Y5vW//IA=</DigestValue>
    </Reference>
  </SignedInfo>
  <SignatureValue>mS3JQ/KmyXCayLly4hHRXKM51jPy230B3h4ngjzOhq0xR/7BRDQP2wfp7ugVcL5kMWaV+pBHbJgdvvu8OrzyxCUQ+R7RYqWpEBYJHUARov0Pws7oFybFpmzRnwhg2gPaPEzcVpK4VL4G1iM07XgmoSKM8Id0fRQ1lD+4BEcAxNY=</SignatureValue>
</Signature>

Signing in C#:

public static void SignXmlDocument(RSA key, XmlDocument doc)
{
    var sxml = new SignedXml(doc);
    sxml.SigningKey = key;
    sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;
    var r = new Reference("");
    r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));
    sxml.AddReference(r);
    sxml.ComputeSignature();
    var sig = sxml.GetXml();
    doc.DocumentElement.AppendChild(sig);
}

How can I make the same in PHP?

  • 写回答

1条回答 默认 最新

  • doupaoshu8334 2014-01-10 18:42
    关注

    You can use XMLDsig

    Install the library and register the paths in your autoloader. If you use composer both steps are automatic.

    require_once __DIR__ . '/vendor/autoload.php';
    
    $xmlDocument = new DOMDocument();
    $xmlDocument..... // define the contents to sign
    
    $xmlTool = new FR3D\XmlDSig\Adapter\XmlseclibsAdapter();
    $xmlTool->setPrivateKey(file_get_contents('<path to your private key>/private.pem');
    $xmlTool->addTransform(FR3D\XmlDSig\Adapter\XmlseclibsAdapter::ENVELOPED);
    
    $xmlTool->sign($xmlDocument);
    

    Now $xmlDocument has the <signature> element at the end.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog