4

我已经签署了 XML,但我不知道如何在签名中包含 KeyValue 元素。拥有一些文档将节省大量时间。

下面的代码(如果你有兴趣的话)是我到目前为止用 xmlseclibs 做的事情:

<?php
require('xmlseclibs.php'); 

XML 字符串

$getToken = '<getToken>
<item>
<Semilla>Random string</Semilla>
</item>
</getToken>';

创建 XML 对象(用于签名)

$getToken_DOMDocument = new DOMDocument(); 
$getToken_DOMDocument -> loadXml($getToken); 

使用 xmlseclibs 创建签名对象

$getToken_XMLSecurityDSig = new XMLSecurityDSig(); 
$getToken_XMLSecurityDSig -> setCanonicalMethod(XMLSecurityDSig::C14N); 

试图关闭不起作用的 ds: 前缀

$options['prefix'] = '';
$options['prefix_ns'] = '';
$options['force_uri'] = TRUE;
$options['id_name'] = 'ID';

$getToken_XMLSecurityDSig -> addReference($getToken_DOMDocument, XMLSecurityDSig::SHA1, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'), $options); 

访问必要的关键数据

$XMLSecurityKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private')); 
$XMLSecurityKey -> loadKey('../../DTE/certificado/firma/certificado.pem', TRUE); 
/* if key has Passphrase, set it using $objKey -> passphrase = <passphrase> */ 

签署 XML 对象

$getToken_XMLSecurityDSig -> sign($XMLSecurityKey); 

添加公钥

$getToken_XMLSecurityDSig -> add509Cert(file_get_contents('../../DTE/certificado/firma/certificado.pem')); 

将封装签名附加到 XML 对象

$getToken_XMLSecurityDSig -> appendSignature($getToken_DOMDocument -> documentElement); 

将签名的 XML 代码保存到文件

$getToken_DOMDocument -> save('sign-basic-test.xml'); 
?>

另外也想从这个库:

  1. 了解官方和可信赖的存储库,以确保库没有损坏。
  2. 关闭“ds:”前缀(因为我生成的 XML 的示例和文档均不包含此类前缀)。
  3. Base64 类型值中的每 X 个字符换行。
  4. 完全缩进(否则根本没有)。

我从此处输入链接描述中获得了库

提前致谢。

4

2 回答 2

2

我编写了一个名为xmldsig的外观库,用于简化下划线 XMLSecLibs 的使用

使用这个库,代码结果如下:

public function testSign()
{
    $getToken = '<getToken>
    <item>
    <Semilla>Random string</Semilla>
    </item>
    </getToken>';

    $data = new DOMDocument();
    $data->loadXml($getToken);

    $adapter = new XmlseclibsAdapter();
    $adapter
        ->setPrivateKey(file_get_contents('privateKey.pem'))
        ->setPublicKey(file_get_contents('publicKey.pem'))
        ->setCanonicalMethod('http://www.w3.org/2001/10/xml-exc-c14n#')
        ->sign($data);

        echo $data->saveXML();
    );
}
于 2015-02-21T10:02:40.627 回答