Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3/4TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

Unicode C++ Examples

Web API Categories

ASN.1
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Service Bus
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Compression
DKIM / DomainKey
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
ECC
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
Geolocation
Google APIs
Google Calendar
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text

HTTP
HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
Microsoft Graph
NTLM
OAuth1
OAuth2
OneDrive
OpenSSL
Outlook
PEM
PFX/P12
POP3
PRNG
REST
REST Misc
RSA Encryption
SCP
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
SharePoint
Socket/SSL/TLS
Spider
Stream
Tar Archive
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl

 

 

 

(Unicode C++) Decrypt a SAML Response

Demonstrates how to decrypt a SAML response.

Note: This example requires Chilkat v9.5.0.76 or greater.

Chilkat C/C++ Library Downloads

MS Visual C/C++

Linux/CentOS C/C++

Alpine Linux C/C++

MAC OS X C/C++

armhf/aarch64 C/C++

C++ Builder

iOS C/C++

Android C/C++

Win Mobile 5.0/Pocket PC 2003

Solaris C/C++

FreeBSD C/C++

OpenBSD C/C++

MinGW C/C++

#include <CkHttpW.h>
#include <CkStringBuilderW.h>
#include <CkXmlW.h>
#include <CkPrivateKeyW.h>
#include <CkRsaW.h>
#include <CkBinDataW.h>
#include <CkCrypt2W.h>

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

    //  This example decrypts this SAML response:

    //  <?xml version="1.0" encoding="UTF-8" ?>
    //  <saml2p:Response Destination="https://deskflow-asp2.com/ubc/ubcdfe.dll/cwlacs" ID="_e4585eaeedbcaf7c24dff7f1ee2499f5" IssueInstant="2018-10-11T17:46:20.727Z" Version="2.0" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol">
    //      <saml2:Issuer xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">https://authentication.stg.id.ubc.ca</saml2:Issuer>
    //      <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#"/>
    //              <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
    //              <ds:Reference URI="#_e4585eaeedbcaf7c24dff7f1ee2499f5">
    //                  <ds:Transforms>
    //                      <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
    //                      <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
    //                  </ds:Transforms>
    //                  <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
    //                  <ds:DigestValue>1ui22tqFyYEOoWI19CMwz4n+ynxNjLDGdTeRMdi60EU=</ds:DigestValue>
    //              </ds:Reference>
    //          </ds:SignedInfo>
    //          <ds:SignatureValue>ROg7FXV6vsp8socVhdo76/i7cRHGGKIveAiScKdujZT0QrHVqIvvbZ/RnwvEMJ9H9i/kJFAQA171
    //  		Eo2kDjSdvNFQ/YcKaJUwMtAwT05yVatGV42RZKEf7ME+vpcCTR1LWZdrhat1FWCg1MNQwNWB0EL5
    //  		fEP2a4jAcSTB8tFbjTAHsv7IWC39E5RVv99mACYXLa7iGZLtORANZxgYu5qQgmH6pUkI6Z1cpmf+
    //  		m9mIjKM6LF0EvLfWOBWL6udZ+GsHPOLjVTJg+1S0xb9FQCYDVW1QhbjSS0icKHKTNNbrsaxllVDY
    //  		m4q27YQjRh+XxugPgvsZ61Pxlto8Jbg+6jUlMQ==</ds:SignatureValue>
    //          <ds:KeyInfo>
    //              <ds:X509Data>
    //                  <ds:X509Certificate>MIIDTTCCAjWgAwIBAgIVAJccYyIV6wly8XyddumpgnHMJ2JLMA0GCSqGSIb3DQEBCwUAMCcxJTAj
    //  			BgNVBAMMHGF1dGhlbnRpY2F0aW9uLnN0Zy5pZC51YmMuY2EwHhcNMTcwMzAxMTk1NDM0WhcNMzcw
    //  			...
    //  			xUuh6HuHKIwQqHBz7udxbH3Zbb6jXGDJjiDHt1LRJ8xbVisFIcDlIwsGQQi0HeEJfx4P</ds:X509Certificate>
    //              </ds:X509Data>
    //          </ds:KeyInfo>
    //      </ds:Signature>
    //      <saml2p:Status>
    //          <saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    //      </saml2p:Status>
    //      <saml2:EncryptedAssertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">
    //          <xenc:EncryptedData Id="_314d80b9cf02d8eda8d686a6ffd626cf" Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
    //              <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"/>
    //              <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    //                  <xenc:EncryptedKey Id="_d7b6da6fb59a627ebb4a96928441ab79" Recipient="https://ubcdfe.deskflow-asp2.com" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
    //                      <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
    //                          <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" xmlns:ds="http://www.w3.org/2000/09/xmldsig#"/>
    //                      </xenc:EncryptionMethod>
    //                      <ds:KeyInfo>
    //                          <ds:X509Data>
    //                              <ds:X509Certificate>MIICuzCCAiQCCQD3bpigRnKMSzANBgkqhkiG9w0BAQsFADCBoTELMAkGA1UEBhMCQ0ExEDAOBgNV
    //  				BAgMB09udGFyaW8xEDAOBgNVBAcMB1Rvcm9udG8xJjAkBgNVBAoMHVRhY3RpY2FsIEJ1c2luZXNz
    //  				...
    //  				kVRcHd1UK3q7G8FoykWjdQz/0EoMTfEZ+Md56mLOe48eMUZV2ONZuL1kDCEKw1UwkaDQI4Pf8pzx
    //  				82b9rgw9wBDtvu5eFPlUGEGIBw==</ds:X509Certificate>
    //                          </ds:X509Data>
    //                      </ds:KeyInfo>
    //                      <xenc:CipherData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
    //                          <xenc:CipherValue>BNHfUOpgdPE5BgpN2VIZIDthMAv1rxk91qVnWyCZOG9bmUKChJtTUqMpndot7VJwYuyKFshkAdnT
    //  				D79KGdlSA1xHKcVeZXXzDWglqSyYjzhDCsyOhPaI4HelMFgCLwyFz89uEpUpqlvfl8ol3Am/XnzQ
    //  				Vp7V7oS76hocjUI51Qs=</xenc:CipherValue>
    //                      </xenc:CipherData>
    //                  </xenc:EncryptedKey>
    //              </ds:KeyInfo>
    //              <xenc:CipherData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
    //                  <xenc:CipherValue>R6l7tmbnXrOfBgB8lA3KnwLYsLH5ZO5omQ7Hp5K05atzw2o55xmCXVMYhNneFxMtxUh6raEyHeZX
    //  			PTZNgWrvdqc4GYND/R7MhRrJzk9OAq1WyoOXwbtRpwNDwWA4N2IuprPQJbvjVxaw/PesZMZwZqlp
    //  			...
    //  			zm9zAxahyu8Ooe8M4r3HN2cY0JxxxkZtDiulbnyA+rRtXfBRJtangvFQ4iFAnzM/Yg9hMyW9jcu0
    //  			S7FzuRB9ONMxi+nh0IFWgqp+</xenc:CipherValue>
    //              </xenc:CipherData>
    //          </xenc:EncryptedData>
    //      </saml2:EncryptedAssertion>
    //  </saml2p:Response>

    //  The sample encrypted SAML response and RSA private key are available online:
    CkHttpW http;
    CkStringBuilderW sbSamlResponse;
    CkStringBuilderW sbPrivateKeyPem;
    bool success = http.QuickGetSb(L"https://chilkatdownload.com/data/samlresponse.xml",sbSamlResponse);
    if (success == true) {
        success = http.QuickGetSb(L"https://chilkatdownload.com/data/samlresponse_privkey.pem",sbPrivateKeyPem);
    }

    if (success != true) {
        wprintf(L"%s\n",http.lastErrorText());
        return;
    }

    CkXmlW xml;
    xml.LoadSb(sbSamlResponse,true);

    //  Load the RSA private key..
    CkPrivateKeyW privkey;
    success = privkey.LoadPem(sbPrivateKeyPem.getAsString());
    if (success != true) {
        wprintf(L"%s\n",privkey.lastErrorText());
        return;
    }

    //  Prepare an RSA object w/ the private key...
    CkRsaW rsa;
    success = rsa.ImportPrivateKeyObj(privkey);
    if (success != true) {
        wprintf(L"%s\n",rsa.lastErrorText());
        return;
    }

    //  RSA will be used to decrypt the xenc:EncryptedKey
    //  The bytes to be decrypted are in xenc:CipherValue (in base64 format)
    const wchar_t *encryptedAesKey = xml.getChildContent(L"saml2:EncryptedAssertion|xenc:EncryptedData|ds:KeyInfo|xenc:EncryptedKey|xenc:CipherData|xenc:CipherValue");
    if (xml.get_LastMethodSuccess() != true) {
        wprintf(L"Encrypted AES key not found.\n");
        return;
    }

    wprintf(L"Encrypted AES key (base64) = %s\n",encryptedAesKey);

    CkBinDataW bdAesKey;
    bdAesKey.AppendEncoded(encryptedAesKey,L"base64");

    CkStringBuilderW sbRsaAlg;
    sbRsaAlg.Append(xml.chilkatPath(L"saml2:EncryptedAssertion|xenc:EncryptedData|ds:KeyInfo|xenc:EncryptedKey|xenc:EncryptionMethod|(Algorithm)"));
    wprintf(L"sbRsaAlg contains: %s\n",sbRsaAlg.getAsString());
    if (sbRsaAlg.Contains(L"rsa-oaep",true) == true) {
        rsa.put_OaepPadding(true);
    }

    //  Note: The DecryptBd method is introduced in Chilkat v9.5.0.76
    success = rsa.DecryptBd(bdAesKey,true);
    if (success != true) {
        wprintf(L"%s\n",rsa.lastErrorText());
        return;
    }

    wprintf(L"Decrypted AES key (hex) = %s\n",bdAesKey.getEncoded(L"hex"));

    //  Get the encrypted XML (in base64) to be decrypted w/ the AES key.
    const wchar_t *encrypted64 = xml.getChildContent(L"saml2:EncryptedAssertion|xenc:EncryptedData|xenc:CipherData|xenc:CipherValue");
    if (xml.get_LastMethodSuccess() != true) {
        wprintf(L"Encrypted data not found.\n");
        return;
    }

    CkBinDataW bdEncrypted;
    bdEncrypted.AppendEncoded(encrypted64,L"base64");

    //  Get the symmetric algorithm:  "http://www.w3.org/2001/04/xmlenc#aes128-cbc"
    //  and set the symmetric decrypt properties.
    CkCrypt2W crypt;
    CkStringBuilderW sbAlg;
    sbAlg.Append(xml.chilkatPath(L"saml2:EncryptedAssertion|xenc:EncryptedData|xenc:EncryptionMethod|(Algorithm)"));
    if (sbAlg.Contains(L"aes128-cbc",true) == true) {
        crypt.put_CryptAlgorithm(L"aes");
        crypt.put_KeyLength(128);
        crypt.put_CipherMode(L"cbc");
        //  The 1st 16 bytes of the encrypted data are the AES IV.
        crypt.SetEncodedIV(bdEncrypted.getEncodedChunk(0,16,L"hex"),L"hex");
        bdEncrypted.RemoveChunk(0,16);
    }

    //  Other algorithms, key lengths, etc, can be supported by checking for different Algorithm attribute values..

    crypt.SetEncodedKey(bdAesKey.getEncoded(L"hex"),L"hex");

    //  AES decrypt...
    success = crypt.DecryptBd(bdEncrypted);
    if (success != true) {
        wprintf(L"%s\n",crypt.lastErrorText());
        return;
    }

    //  Get the decrypted XML
    const wchar_t *decryptedXml = bdEncrypted.getString(L"utf-8");
    wprintf(L"Decrypted XML:\n");
    wprintf(L"%s\n",decryptedXml);

    //  The decrypted XML looks like this:

    //  <saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion" ID="_226e565c548db7986d165d7d969b48b4" IssueInstant="2018-10-11T17:46:20.727Z" Version="2.0">
    //  ...
    //  ...
    //  ...
    //  </saml2:Assertion>

    CkXmlW xmlAssertion;
    xmlAssertion.LoadXml(decryptedXml);

    //  Replace the saml2:EncryptedAssertion XML subtree with the saml2:Assertion XML.
    CkXmlW *xmlEncryptedAssertion = xml.FindChild(L"saml2:EncryptedAssertion");
    xmlEncryptedAssertion->SwapTree(xmlAssertion);
    delete xmlEncryptedAssertion;

    //  The decrypted XML assertion has now replaced the encrypted XML assertion.
    //  Examine the fully decrypted XML document:
    wprintf(L"Full XML SAML document with decrypted assertion:\n");
    wprintf(L"%s\n",xml.getXml());
    }

 

© 2000-2019 Chilkat Software, Inc. All Rights Reserved.