Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Sign SOAP XML using a wsse:SecurityTokenReference

See more XML Digital Signatures Examples

This example signs SOAP XML such that the KeyInfo in the XML Signature is a wsse:SecurityTokenReference to the X.509 certificate embedded elsewhere in the SOAP XML.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Pfx,
  Chilkat.XmlDSigGen,
  Chilkat.StringBuilder,
  Chilkat.BinData,
  Chilkat.Cert,
  Chilkat.Http,
  Chilkat.Xml;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  sbXml: TStringBuilder;
  http: THttp;
  pfxData: TBinData;
  pfx: TPfx;
  password: string;
  cert: TCert;
  bdCert: TBinData;
  numReplaced: Integer;
  refXml: TXml;
  gen: TXmlDSigGen;

begin
  success := False;

  //  This example requires the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  //  To begin, we'll need a PFX containing a certificate and private key, and the SOAP XML to be signed.
  //  Chilkat provides sample data at chilkatsoft.com and chilkatdownload.com, and our first step is to download.

  //  -------------------------------------------------------------------------
  //  Step 1: Get the SOAP XML template to be signed.
  //  
  sbXml := TStringBuilder.Create;

  http := THttp.Create;
  success := http.QuickGetSb('https://www.chilkatsoft.com/exampleData/wssSoapTemplate.xml',sbXml);
  if (success = False) then
    begin
      WriteLn(http.LastErrorText);
      Exit;
    end;

  //  The SOAP XML template contains this:

  //  <?xml version="1.0" encoding="UTF8"?>
  //  <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  //  <SOAP-ENV:Header>
  //   <wsse:Security xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
  //                  xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
  //                  xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
  //                  xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" SOAP-ENV:mustUnderstand="1">
  //   <wsse:BinarySecurityToken
  //                 EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
  //                 ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509"
  //                 wsu:Id="x509cert00">BASE64_CERT</wsse:BinarySecurityToken>
  //   </wsse:Security>
  //  </SOAP-ENV:Header>
  //  <SOAP-ENV:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="TheBody">
  //   <getVersion xmlns="http://msgsec.wssecfvt.ws.ibm.com"/>
  //  </SOAP-ENV:Body>
  //  </SOAP-ENV:Envelope>
  //  

  //  -------------------------------------------------------------------------
  //  Step 2: Get the test certificate and private key stored in a .pfx
  //  
  pfxData := TBinData.Create;
  success := http.QuickGetBd('http://chilkatdownload.com/example_data/testcertificate.pfx',pfxData);
  if (success = False) then
    begin
      WriteLn(http.LastErrorText);
      Exit;
    end;

  pfx := TPfx.Create;
  password := 'test';
  success := pfx.LoadPfxEncoded(pfxData.GetEncoded('base64'),'base64',password);
  if (success = False) then
    begin
      WriteLn(pfx.LastErrorText);
      Exit;
    end;

  //  -------------------------------------------------------------------------
  //  Step 3: Get the certificate from the PFX.
  //  
  cert := TCert.Create;
  success := pfx.CertAt(0,cert);
  if (success = False) then
    begin
      WriteLn(pfx.LastErrorText);
      Exit;
    end;

  //  -------------------------------------------------------------------------
  //  Step 4: Replace "BASE64_CERT" with the actual base64 encoded certificate.
  //  
  bdCert := TBinData.Create;
  cert.ExportCertDerBd(bdCert);

  numReplaced := sbXml.Replace('BASE64_CERT',bdCert.GetEncoded('base64'));

  //  -------------------------------------------------------------------------
  //  Step 5: Build the wsse:SecurityTokenReference XML.
  //  This will be the CustomKeyInfoXml (see below).
  //  
  refXml := TXml.Create;
  refXml.Tag := 'wsse:SecurityTokenReference';
  refXml.UpdateAttrAt('wsse:Reference',True,'URI','#x509cert00');
  refXml.UpdateAttrAt('wsse:Reference',True,'ValueType','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509');

  //  The above lines of code builds the following XML:

  //  	<wsse:SecurityTokenReference>
  //  	    <wsse:Reference URI="#x509cert00" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509" />
  //  	</wsse:SecurityTokenReference>
  //  
  refXml.EmitXmlDecl := False;
  WriteLn(refXml.GetXml());

  //  -------------------------------------------------------------------------
  //  Step 6: Setup the XML Digital Signature Generator and add the XML Signature.
  //  
  gen := TXmlDSigGen.Create;
  gen.SigLocation := 'SOAP-ENV:Envelope|SOAP-ENV:Header|wsse:Security';
  gen.SignedInfoPrefixList := 'wsse SOAP-ENV';
  gen.AddSameDocRef('TheBody','sha1','EXCL_C14N','','');
  gen.KeyInfoType := 'Custom';
  refXml.EmitCompact := True;

  gen.CustomKeyInfoXml := refXml.GetXml();
  gen.SetX509Cert(cert,True);

  success := gen.CreateXmlDSigSb(sbXml);
  if (success = False) then
    begin
      WriteLn(gen.LastErrorText);
      Exit;
    end;

  //  Examine the signed XML
  WriteLn(sbXml.GetAsString());

  //  Pretty-printed, the XML signature looks as shown here: 
  //  (The exact XML signature is shown below. Pretty-printing invalidates the XML signature.)

  //  <?xml version="1.0" encoding="UTF8" ?>
  //  <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  //      <SOAP-ENV:Header>
  //          <wsse:Security xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" SOAP-ENV:mustUnderstand="1">
  //              <wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509" wsu:Id="x509cert00">MIID...</wsse:BinarySecurityToken>
  //              <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
  //                  <ds:SignedInfo>
  //                      <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
  //                          <InclusiveNamespaces xmlns="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wsse SOAP-ENV" />
  //                      </ds:CanonicalizationMethod>
  //                      <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
  //                      <ds:Reference URI="#TheBody">
  //                          <ds:Transforms>
  //                              <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
  //                          </ds:Transforms>
  //                          <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
  //                          <ds:DigestValue>VhsSnaEAFsY0OYegKQh99v9csXg=</ds:DigestValue>
  //                      </ds:Reference>
  //                  </ds:SignedInfo>
  //                  <ds:SignatureValue>Ynp3H4rtzpXIh4TaVxkpEkS1bMCCu672aeCzUOzheNNfnpmLsCZz3+zQjMBbchPggCayC5ihpEdhRe3XvPXjPXXAgxDP4mic091QPmjHlmUcu8yqRKfxnPtD35nqaxDtCYw+jGIzj+ch094vA4RPCfY8JQnb1mpy1ZjjsMW8741CIh1epbsd/0bZt6tfINUQ37seg07yvLbCJZ/Zf+h8FlFryQk6lHTTeZl/GfQ9NlDBcShby3x8Hc1KwW++zFqEA7G783R9AYPYn3fWTOBhYk5gkgFc+HaPRLR/L0Bp7ZPbmOR/iZQ+HK4W672tTdN/R2GdN7/deV7QTp2DYK1Z8w==</ds:SignatureValue>
  //                  <ds:KeyInfo>
  //                      <wsse:SecurityTokenReference>
  //                          <wsse:Reference URI="#x509cert00" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509" />
  //                      </wsse:SecurityTokenReference>
  //                  </ds:KeyInfo>
  //              </ds:Signature>
  //          </wsse:Security>
  //      </SOAP-ENV:Header>
  //      <SOAP-ENV:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="TheBody">
  //          <getVersion xmlns="http://msgsec.wssecfvt.ws.ibm.com" />
  //      </SOAP-ENV:Body>
  //  </SOAP-ENV:Envelope>
  //  

  //  --------------------------------------------------------------------------------------------
  //  This is the XML signature, which is also available at https://www.chilkatsoft.com/exampleData/signedSoapBinarySecurityToken.xml
  //  

  //  <?xml version="1.0" encoding="UTF8"?>
  //  <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
  //  <SOAP-ENV:Header>
  //   <wsse:Security xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
  //                  xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
  //                  xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
  //                  xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" SOAP-ENV:mustUnderstand="1">
  //   <wsse:BinarySecurityToken
  //                 EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
  //                 ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509"
  //                 wsu:Id="x509cert00">MIIDg...</wsse:BinarySecurityToken>
  //   <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"><InclusiveNamespaces xmlns="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="wsse SOAP-ENV"/></ds:CanonicalizationMethod><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/><ds:Reference URI="#TheBody"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>VhsSnaEAFsY0OYegKQh99v9csXg=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>Ynp3H4rtzpXIh4TaVxkpEkS1bMCCu672aeCzUOzheNNfnpmLsCZz3+zQjMBbchPggCayC5ihpEdhRe3XvPXjPXXAgxDP4mic091QPmjHlmUcu8yqRKfxnPtD35nqaxDtCYw+jGIzj+ch094vA4RPCfY8JQnb1mpy1ZjjsMW8741CIh1epbsd/0bZt6tfINUQ37seg07yvLbCJZ/Zf+h8FlFryQk6lHTTeZl/GfQ9NlDBcShby3x8Hc1KwW++zFqEA7G783R9AYPYn3fWTOBhYk5gkgFc+HaPRLR/L0Bp7ZPbmOR/iZQ+HK4W672tTdN/R2GdN7/deV7QTp2DYK1Z8w==</ds:SignatureValue><ds:KeyInfo><wsse:SecurityTokenReference><wsse:Reference URI="#x509cert00" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509" /></wsse:SecurityTokenReference></ds:KeyInfo></ds:Signature></wsse:Security>
  //  </SOAP-ENV:Header>
  //  <SOAP-ENV:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="TheBody">
  //   <getVersion xmlns="http://msgsec.wssecfvt.ws.ibm.com"/>
  //  </SOAP-ENV:Body>
  //  </SOAP-ENV:Envelope>
  //  


  sbXml.Free;
  http.Free;
  pfxData.Free;
  pfx.Free;
  cert.Free;
  bdCert.Free;
  refXml.Free;
  gen.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.