Sample code for 30+ languages & platforms
Xbase++

Create PEM-encoded PKCS#7 Detached Signature

See more Digital Signatures Examples

Demonstrates how to create a PKCS7 PEM-encoded object containing a detached signature.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oCert
LOCAL oCrypt
LOCAL cTextToSign
LOCAL cSigBase64
LOCAL oSb
LOCAL nCrlf

nSuccess := 0

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

oCert := CreateObject("Chilkat.Cert")

//  Load the cert and private key.
nSuccess := oCert:LoadPfxFile("qa_data/pfx/myCertAndKey.p12", "password")
IF (nSuccess != 1)
    ? oCert:LastErrorText
    oCert:destroy()
    RETURN
ENDIF

oCrypt := CreateObject("Chilkat.Crypt2")

nSuccess := oCrypt:SetSigningCert(oCert)
IF (nSuccess != 1)
    ? oCrypt:LastErrorText
    oCert:destroy()
    oCrypt:destroy()
    RETURN
ENDIF

//  Use SHA-256
oCrypt:HashAlgorithm := "sha256"

//  Hash the utf-8 byte representation of the string
oCrypt:Charset := "utf-8"

//  Return the result in base64
oCrypt:EncodingMode := "base64Mime"

//  Sign some text to create a detached signature (i.e. a signature that does not include the signed data)
cTextToSign := "This is the text to be hashed and signed."
cSigBase64 := oCrypt:SignStringENC(cTextToSign)
IF (oCrypt:LastMethodSuccess != 1)
    ? oCrypt:LastErrorText
    oCert:destroy()
    oCrypt:destroy()
    RETURN
ENDIF

? cSigBase64

//  The result:

//  MIIWbgYJKoZIhvcNAQcCoIIWXzCCFlsCAQExDzANBglghkgBZQMEAgEFADALBgkqhkiG9w0BBwGg
//  ghMXMIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UEBhMCSVQx
//  ...
//  ...

//  If we want it in PEM format with just LF line-endings:
oSb := CreateObject("Chilkat.StringBuilder")
//  Just LF line endings, not CRLF.
nCrlf := 0
oSb:AppendLine("-----BEGIN PKCS7-----", nCrlf)
oSb:Append(cSigBase64)
oSb:AppendLine("-----END PKCS7-----", nCrlf)
oSb:ToLF()

//  Save to a file.
oSb:WriteFile("c:/temp/qa_output/sig.pem", "utf-8", 0)

//  Examine..
? oSb:GetAsString()

//  Result is:

//  -----BEGIN PKCS7-----
//  MIIWbgYJKoZIhvcNAQcCoIIWXzCCFlsCAQExDzANBglghkgBZQMEAgEFADALBgkqhkiG9w0BBwGg
//  ghMXMIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UEBhMCSVQx
//  DjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1ODUyMDk2NzEnMCUG
//  A1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENBMB4XDTExMDkyMjExMjIwMloXDTMw
//  MDkyMjExMjIwMlowazELMAkGA1UEBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3Rh
//  bGlzIFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBS
//  b290IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNvUTuf
//  ClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX4ay8IMKx4INRimlN
//  AJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9KK3giq0itFZljoZUj5NDKd45Rnij
//  MCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9
//  ...
//  ...
//  -----END PKCS7-----

oCert:destroy()
oCrypt:destroy()
oSb:destroy()