SecureBlackbox 2020 iOS Edition

Questions / Feedback?

CAdESSigner Class

Properties   Methods   Events   Configuration Settings   Errors  

The CAdESSigner class creates CAdES- and CMS-compliant electronic signatures.

Syntax

SecureBlackboxCAdESSigner
SecureBlackboxCAdESSignerSwift

Remarks

CAdESSigner can sign documents and files in compliance with CMS Advanced Electronic Signatures (CAdES) specification. Originally developed by ETSI on the basis of PKCS#7 format and initially adopted in the European Union, CAdES has quickly become a recognized international standard for signing all sorts of electronic documents.

Besides being a signature standard in its own right, CAdES is used as part of other higher-level signature standards, such as PAdES or S/MIME. It provides a convenient framework for creating short-lived and long-term signatures over any kind of documents, and is now used by governments, healthcare providers, banks, and independent service providers all across the globe.

Standards and technologies supported

CAdESSigner offers the following signing capabilities:

  • Create and upgrade CAdES signatures in accordance with the most recent CAdES specification (ETSI EN 319 122). Some features from older versions are also supported.
  • All profiles are supported (BES, EPES, T, C, X, XL, A, including Baseline and Extended variants).
  • Timestamping using external TSAs.
  • All industry-standard cryptographic algorithms (RSA, ECDSA, SHA256-512, and many others).

Configuring the signature parameters

Configuring CAdESSigner to make it produce a signature of the right type is the main task you would need to perform in your code. Normally the service or software you will be communicating your signed documents to will provide you with the list of requirements that your signatures should match.

Typically, those will dictate the following key aspects of the signatures:

  • The signature Level (such BES, T, XL, A, or XLong). This can be passed as the Level parameter of the Sign method.
  • Whether the signature should be detached or enveloping: this can be adjusted via the Detached parameter of the Sign method.
  • When creating a timestamped signature (such as T or A), provide the address of your online TSA service via TimestampServer property.
  • When creating long-term signatures that include the signing chain and validation material, tune up validation parameters via RevocationCheck, OfflineMode, and IgnoreChainValidationErrors properties.

In some circumstances you will also need to adjust the following lower-level settings:

Signing certificates

CAdESSigner can use certificates residing on different media. Besides generic certificates stored in PFX or PEM files (A1), it can operate with non-exportable certificates residing on hardware media (A3) or in the cloud.

Non-exportable certificates can be accessed transparently via a Windows CSP or a PKCS#11 driver, if supplied by the certificate issuer. Proprietary interfaces can be plugged in with the external signing feature (see below).

You can use CertificateManager and CertificateStorage components to access the signing certificate. Assign the certificate to SigningCertificate property, and optionally provide the remainder of its chain via SigningChain property.

Note: If signing with a non-exportable key (such as residing on a hardware device or in the cloud), please make sure you keep the original CertificateStorage object open until the signing is completed. This is because the storage component provides a 'bridge' to the private key. If the storage is closed prematurely, this bridge is destroyed, and the private key can't be used.

You don't need to provide a signing certificate or chain when timestamping and upgrading signatures, since this type of operation does not involve the signing private key.

Signing a file

Now that you have set up all signature properties and attached the signing certificate, it is time to proceed to signing. You can provide the input document in one of the following forms: as a file (assign the path to InputFile property), as a stream (assign to InputStream property), or as a byte array (assign to InputBytes). Similarly, the output can be collected in one of the same forms, either by passing the destination path or stream via OutputFile and OutputStream respectively, or by reading the resulting document bytes from the OutputBytes property after the signing completes.

Having set up the input and output (unless using OutputBytes, which should be read later), call the component's Sign method, passing the desired signature level and type as parameters. This will initiate the signing process. Depending on the settings, the signing may be as straightforward as calculating the document hash and signing it with the private key (e.g. in CAdES-BES or B-B variant), or it may involve advanced chain validation routines (CAdES-XL or -A). During the latter the component may contact a number of external revocation information sources (CRL and OCSP servers) to establish the validity of the signing certificate.

If a TSA server was provided via the TimestampServer property, the component will contact it too to timestamp the new signature.

During the signing CAdESSigner may fire events to let your code know of certain conditions. It may fire TLSCertValidate if one of the HTTP endpoints involved in the operation (which may be a CRL, OCSP, or TSA service) works over TLS and needs its certificate to be validated.

Apart from signing, CAdESSigner can perform operations on signatures of other kinds. Use Upgrade method to upgrade an existing CAdES signature to a higher level (e.g. BES to XL). Use Timestamp to add a generic or validation timestamp to an existing signature. Use the Countersign method to add a countersignature to an existing signature. For any of these operations the input should constitute a valid CAdES signature.

External signing and DCAuth

CAdESSigner, like many other components offered by the product, supports two methods of signing with external keys. These methods are fully independent of each other: you can choose the one that suits your usage scenario best.

Synchronous method: ExternalSign

This is a simpler method that basically lets you infiltrate into the heart of the signing routine by taking care of the hash signing operation. The component does the rest of the job (hash calculation, preparation of signature objects, CRL/OCSP retrieval).

To initiate this method, call SignExternal instead of Sign. When the hash is ready, it will be passed back to your code with ExternalSign event. Your event handler needs to sign the hash with the private key and return the created signature back to the component - which will embed it into the document.

You don't need your signing certificate to contain an associated private key when using this method. The certificate itself (its public copy) may be needed though, as it is often included in the hash calculation.

This method is synchronous, meaning SignExternal provides you the results immediately upon its completion.

Asynchronous method: DCAuth

DCAuth is a SecureBlackbox-own know-how technology. This protocol was designed to allow sharing of private keys across environments, allowing the signer and the private key to reside on different systems. It works in the following way:

  • The signing party - such as CAdESSigner - initiates the operation using SignAsyncBegin call. This produces two outcomes: a pre-signed document (a document with a blank signature placeholder), and a request state (an object containing a hash that needs to be signed). At this point the CAdESSigner instance can be released, and the process itself terminated (which may be useful when run as part of a web page).
  • The request state is passed to the private key holder party. The private key holder passes the request state to a DCAuth object, which parses the request state, extracts the hash, and signs it. The output of DCAuth processing is another object, response state, which contains the signature. The private key holder then sends the response state back to the signing party.
  • The signing party re-creates the controls, and passes the response state, together with the pre-signed version of the document, to the signer's SignAsyncEnd method. SignAsyncEnd extracts the signature from the response state and incorporates it into the pre-signed document.

This method is asynchronous in that sense that, from the signing party's viewpoint, it splits the signing operation into the pre-signing and completion stages which can be performed independently from each other and in different execution contexts. This makes this method particularly helpful for use in web pages and other scenarios where the signing key is not available in real time.

Fine-grained chain validation setup

Chain validation is a sophisticated, multi-faceted procedure that involves a lot of variables. Depending on the configuration of your operating environment, the specifics of the PKI framework being used, and the validation policy you need to follow, you may want to tune up your chain validation parameters so they fit them best. Below is given a summary of such parameters.

  • RevocationCheck property lets you choose between and/or prioritize revocation origins. OCSP sources are often preferred to CRL because of their real-time capability and the smaller size of validation tokens they produce.
  • OfflineMode is a master switch that stops class from looking for any validation tokens online. If this property is switched on, the component will only use KnownCertificates, TrustedCertificates, KnownCRLs, and KnownOCSPs collections to look for the missing validation material.
  • IgnoreChainValidationErrors makes the component ignore any major validation issues it encounters (such us an untrusted chain or missing CRL). This option is handy for debugging and for creating signatures in the environments where the signing certificate is not trusted.
  • KnownCertificates, KnownCRLs, and KnownOCSPs let you provide your own validation material. This may be useful when working in OfflineMode, where the signer has no access to the validation sources, or where the validation material has already been collected.
  • TrustedCertificates lets you provide a list of trust anchors, either as a complement to the system's or as an alternative for it.
  • BlockedCertificates lets you provide a list of blocked/distrusted certificates. Any CA certificate contained in it will be deemed untrusted/invalid.

The following parameters are not directly related to chain validation, but may have an implicit effect on it.

  • Proxy, SocketSettings, and TLSSettings let you tune up the connectivity and TLS options in accordance with local preferences.
  • TLSClientChain lets you provide the client certificate and its chain for TLS client authentication.
  • Subscribe to TLSCertValidate to validate any TLS certificates of the services involved in chain validation.

The results of the chain validation procedure, upon its completion, are published in the following properties:

  • ChainValidationResult contains the primary result of the chain validation routine: valid, valid but untrusted, invalid, or undefined.
  • ChainValidationDetails provides the details of the factors that contributed to the chain validation result, such as an outdated certificate, a missing CRL, or a missing CA certificate.
  • ValidationLog contains the detailed chain validation log. The log can often be very helpful in nailing down various validation issues.

Property List


The following is the full list of the properties of the class with short descriptions. Click on the links for further details.

- blockedCertCountThe number of records in the BlockedCert arrays.
- blockedCertBytes:(int)blockedCertIndexReturns raw certificate data in DER format.
- blockedCertHandle:(int)blockedCertIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- chainValidationDetailsThe details of a certificate chain validation outcome.
- chainValidationResultThe general outcome of a certificate chain validation routine. Use ChainValidationDetails to get information about the reasons that contributed to the validation result.
- claimedSigningTimeThe signing time from the signer's computer.
- dataBytesA byte array containing the external data source.
- dataFileA path to a file containing an external data source.
- externalCryptoCustomParamsCustom parameters to be passed to the signing service (uninterpreted).
- externalCryptoDataAdditional data to be included in the async state and mirrored back by the requestor.
- externalCryptoExternalHashCalculationSpecifies whether the message hash is to be calculated at the external endpoint.
- externalCryptoHashAlgorithmSpecifies the request's signature hash algorithm.
- externalCryptoKeyIDThe ID of the pre-shared key used for DC request authentication.
- externalCryptoKeySecretThe pre-shared key used for DC request authentication.
- externalCryptoMethodSpecifies the asynchronous signing method.
- externalCryptoModeSpecifies the external cryptography mode.
- externalCryptoPublicKeyAlgorithmProvide public key algorithm here if the certificate is not available on the pre-signing stage.
- hashAlgorithmSpecifies the hash algorithm to be used.
- ignoreChainValidationErrorsMakes the class tolerant to chain validation errors.
- inputBytesUse this property to pass the input to class in the byte array form.
- inputFileA path to a file containing the data to be signed or updated.
- knownCertCountThe number of records in the KnownCert arrays.
- knownCertBytes:(int)knownCertIndexReturns raw certificate data in DER format.
- knownCertHandle:(int)knownCertIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- knownCRLCountThe number of records in the KnownCRL arrays.
- knownCRLBytes:(int)knownCRLIndexReturns raw CRL data in DER format.
- knownCRLHandle:(int)knownCRLIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- knownOCSPCountThe number of records in the KnownOCSP arrays.
- knownOCSPBytes:(int)knownOCSPIndexBuffer containing raw OCSP response data.
- knownOCSPHandle:(int)knownOCSPIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- offlineModeSwitches the class to the offline mode.
- outputBytesUse this property to read the output the class object has produced.
- outputFileA file where the signed data is to be saved.
- policyHashThe signature policy hash value.
- policyHashAlgorithmThe algorithm that was used to calculate the signature policy hash.
- policyIDThe policy ID to be included into the signature.
- policyURIThe signature policy URI to be included in the signature.
- profileSpecifies a pre-defined profile to apply when creating the signature.
- proxyAddressThe IP address of the proxy server.
- proxyAuthenticationThe authentication type used by the proxy server.
- proxyPasswordThe password to authenticate to the proxy server.
- proxyPortThe port on the proxy server to connect to.
- proxyProxyTypeThe type of the proxy server.
- proxyRequestHeadersContains HTTP request headers for WebTunnel and HTTP proxy.
- proxyResponseBodyContains the HTTP or HTTPS (WebTunnel) proxy response body.
- proxyResponseHeadersContains response headers received from an HTTP or HTTPS (WebTunnel) proxy server.
- proxyUseIPv6Specifies whether IPv6 should be used when connecting through the proxy.
- proxyUseProxyEnables or disables proxy-driven connection.
- proxyUsernameSpecifies the username credential for proxy authentication.
- revocationCheckSpecifies the kind(s) of revocation check to perform.
- signatureIndexThe index of the signature to update.
- signedAttributeCountThe number of records in the SignedAttribute arrays.
- signedAttributeOID:(int)signedAttributeIndexThe object identifier of the attribute.
- signedAttributeValue:(int)signedAttributeIndexThe value of the attribute.
- signingCertBytesReturns raw certificate data in DER format.
- signingCertHandleAllows to get or set a 'handle', a unique identifier of the underlying property object.
- signingChainCountThe number of records in the SigningChain arrays.
- signingChainBytes:(int)signingChainIndexReturns raw certificate data in DER format.
- signingChainHandle:(int)signingChainIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- socketDNSModeSelects the DNS resolver to use: the class's (secure) built-in one, or the one provided by the system.
- socketDNSPortSpecifies the port number to be used for sending queries to the DNS server.
- socketDNSQueryTimeoutThe timeout (in milliseconds) for each DNS query.
- socketDNSServersThe addresses of DNS servers to use for address resolution, separated by commas or semicolons.
- socketDNSTotalTimeoutThe timeout (in milliseconds) for the whole resolution process.
- socketIncomingSpeedLimitThe maximum number of bytes to read from the socket, per second.
- socketLocalAddressThe local network interface to bind the socket to.
- socketLocalPortThe local port number to bind the socket to.
- socketOutgoingSpeedLimitThe maximum number of bytes to write to the socket, per second.
- socketTimeoutThe maximum period of waiting, in milliseconds, after which the socket operation is considered unsuccessful.
- socketUseIPv6Enables or disables IP protocol version 6.
- timestampServerThe address of the timestamping server.
- TLSClientCertCountThe number of records in the TLSClientCert arrays.
- TLSClientCertBytes:(int)tLSClientCertIndexReturns raw certificate data in DER format.
- TLSClientCertHandle:(int)tLSClientCertIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- TLSServerCertCountThe number of records in the TLSServerCert arrays.
- TLSServerCertBytes:(int)tLSServerCertIndexReturns raw certificate data in DER format.
- TLSServerCertHandle:(int)tLSServerCertIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- TLSAutoValidateCertificatesSpecifies whether server-side TLS certificates should be validated automatically using internal validation rules.
- TLSBaseConfigurationSelects the base configuration for the TLS settings.
- TLSCiphersuitesA list of ciphersuites separated with commas or semicolons.
- TLSECCurvesDefines the elliptic curves to enable.
- TLSForceResumeIfDestinationChangesWhether to force TLS session resumption when the destination address changes.
- TLSPreSharedIdentityDefines the identity used when the PSK (Pre-Shared Key) key-exchange mechanism is negotiated.
- TLSPreSharedKeyContains the pre-shared for the PSK (Pre-Shared Key) key-exchange mechanism, encoded with base16.
- TLSPreSharedKeyCiphersuiteDefines the ciphersuite used for PSK (Pre-Shared Key) negotiation.
- TLSRenegotiationAttackPreventionModeSelects renegotiation attack prevention mechanism.
- TLSRevocationCheckSpecifies the kind(s) of revocation check to perform.
- TLSSSLOptionsVarious SSL (TLS) protocol options, set of cssloExpectShutdownMessage 0x001 Wait for the close-notify message when shutting down the connection cssloOpenSSLDTLSWorkaround 0x002 (DEPRECATED) Use a DTLS version workaround when talking to very old OpenSSL versions cssloDisableKexLengthAlignment 0x004 Do not align the client-side PMS by the RSA modulus size.
- TLSTLSModeSpecifies the TLS mode to use.
- TLSUseExtendedMasterSecretEnables Extended Master Secret Extension, as defined in RFC 7627.
- TLSUseSessionResumptionEnables or disables TLS session resumption capability.
- TLSVersionsTh SSL/TLS versions to enable by default.
- trustedCertCountThe number of records in the TrustedCert arrays.
- trustedCertBytes:(int)trustedCertIndexReturns raw certificate data in DER format.
- trustedCertHandle:(int)trustedCertIndexAllows to get or set a 'handle', a unique identifier of the underlying property object.
- unsignedAttributeCountThe number of records in the UnsignedAttribute arrays.
- unsignedAttributeOID:(int)unsignedAttributeIndexThe object identifier of the attribute.
- unsignedAttributeValue:(int)unsignedAttributeIndexThe value of the attribute.
- validationLogContains the complete log of the certificate validation routine.

Method List


The following is the full list of the methods of the class with short descriptions. Click on the links for further details.

- archiveArchives the signature.
- configSets or retrieves a configuration setting.
- countersignCountersigns the existing signature.
- countersignExternalCountersigns the existing signature using an external signing facility.
- extractAsyncDataExtracts user data from the DC signing service response.
- signCreates a new CAdES signature over the provided data.
- signAsyncBeginInitiates asynchronous (DC) signing.
- signAsyncEndCompletes the asynchronous signing operation.
- signExternalSigns the document using an external signing facility.
- timestampAdds a timestamp to the signature.
- upgradeUpgrades existing CAdES to a new level.

Event List


The following is the full list of the events fired by the class with short descriptions. Click on the links for further details.

- onErrorInformation about errors during CAdES signing.
- onExternalSignHandles remote or external signing initiated by the SignExternal method or other source.
- onNotificationThis event notifies the application about an underlying control flow event.
- onTLSCertValidateThis event is fired upon receipt of the TLS server's certificate, allowing the user to control its acceptance.

Configuration Settings


The following is a list of configuration settings for the class with short descriptions. Click on the links for further details.

AddReferencesToAllUsedCertsAndRevInfoWhether to include all certificates and revocation references in CompleteCertificateRefs attribute.
AddReferencesToIrrevocableCertsWhether references to irrevocable certificates should be included in CompleteCertificateRefs attribute.
AddReferenceToSigningCertWhether a reference to the signing certificate should be included in CompleteCertificateRefs attribute.
AllowPartialValidationInfoWhether to allow for missing validation info.
CmsOptAnnexKArchiveTimestampV2ModeToggles use of Annex K method of calculating validation timestamp hashes.
CmsOptCheckATSHashIndexElementsEnables extra checks when processing ATSHashIndex attribute.
CmsOptCompareRDNAsStringsEnforces comparison of RDN elements as text strings, rather than their byte encodings.
CmsOptDigitPADSSCompatibilityEnables Digit PADSS compatibility mode.
CmsOptForceSigningCertificateV2UsageEnforces use of signing-certificate-v2 attribute.
CmsOptIgnoreDERReqInArchiveTimestampsSwitches off DER encoding requirement for archival timestamps.
CmsOptImzagerMIMCompatibilityEnables Imzager MIM compatibility mode.
CmsOptIncludeCertToAttributesRegulates whether to include the signing certificate to the signature as the signing-certificate attribute.
CmsOptIncludeCertToMessageRegulates whether to include the signing certificate and its chain to the CMS.
CmsOptInsertContentTypeRegulates whether the content-type time attribute should be included in the signature structure.
CmsOptInsertMessageDigestsRegulates whether the message-digest signed attribute should be included in the signature structure.
CmsOptInsertSigningTimeRegulates whether the signing-time attribute should be included in the signature structure.
CmsOptSkipEnvContentInfoOnSigArchivalExcludes hashing of enveloped content when calculating an archival timestamp.
CmsOptUseATSHashIndexV1Enables use of ATSHashIndexV1 attribute.
CmsOptUseGeneralizedTimeFormatEnables or disables encoding of the signing-time attribute using ASN.1 GENERALIZEDTIME type.
CmsOptUseGenericSigAlgorithmOIDsEnables use of generic signature algorithm OIDs in the signature.
CmsOptUsePlainContentForTimestampHashesMakes CAdESSigner ignore ASN.1 content formatting when calculating timestamp hashes.
ContentTypeThe content type of the CMS message.
DeepCountersignatureValidationWhether to validate countersignatures.
DeepTimestampValidationWhether to perform deep validation of all timestamps.
ForceCompleteChainValidationWhether to check the CA certificates when the signing certificate is invalid.
ForceCompleteChainValidationForTrustedWhether to continue with the full validation up to the root CA certificate for mid-level trust anchors.
GracePeriodSpecifies a grace period to apply during revocation information checks.
IgnoreChainValidationErrorsDon't stop on chain validation errors.
IgnoreOCSPNoCheckExtensionWhether OCSP NoCheck extension should be ignored.
IgnoreSystemTrustWhether trusted Windows Certificate Stores should be treated as trusted.
ImplicitlyTrustSelfSignedCertificatesWhether to trust self-signed certificates.
PolicyExplicitTextThe explicit text of the user notice.
PolicyUNNumbersThe noticeNumbers part of the NoticeReference CAdES attribute.
PolicyUNOrganizationThe organization part of the NoticeReference qualifier.
PromoteLongOCSPResponsesWhether long OCSP responses are requested.
ReportInvalidTimestampsWhether to raise errors for invalid timestamps.
SchemeParamsThe algorithm scheme parameters to employ.
SkipValidationTimestampedSignaturesWhether to validate signatures with validation timestamps.
SuppressValuesInCMakes CAdESSigner not add certificate and revocation values to its C-level signatures.
TempPathPath for storing temporary files.
TLSChainValidationDetailsContains the advanced details of the TLS server certificate validation.
TLSChainValidationResultContains the result of the TLS server certificate validation.
TLSClientAuthRequestedIndicates whether the TLS server requests client authentication.
TLSValidationLogContains the log of the TLS server certificate validation.
TolerateMinorChainIssuesWhether to tolerate minor chain issues.
TspHashAlgorithmSets a specific hash algorithm for use with the timestamping service.
TspReqPolicySets a request policy ID to include in the timestamping request.
UseArchivalTimestampV3Whether to stick to archival timestamp V3 in the new signatures.
UseMicrosoftCTLEnables or disables automatic use of Microsoft online certificate trust list.
UsePSSWhether to use RSASSA-PSS algorithm.
UseSystemCertificatesEnables or disables the use of the system certificates.
UseUndefSizeToggles the use of indefinite/definite ASN.1 tag length encoding.
UseValidationCacheEnables or disable the use of the product-wide certificate chain validation cache.
CheckKeyIntegrityBeforeUseEnables or disable private key integrity check before use.
CookieCachingSpecifies whether a cookie cache should be used for HTTP(S) transports.
CookiesGets or sets local cookies for the class (supported for HTTPClient, RESTClient and SOAPClient only).
DefDeriveKeyIterationsSpecifies the default key derivation algorithm iteration count.
EnableClientSideSSLFFDHEEnables or disables finite field DHE key exchange support in TLS clients.
GlobalCookiesGets or sets global cookies for all the HTTP transports.
HttpUserAgentSpecifies the user agent name to be used by all HTTP clients.
LogDestinationSpecifies the debug log destination.
LogDetailsSpecifies the debug log details to dump.
LogFileSpecifies the debug log filename.
LogFiltersSpecifies the debug log filters.
LogFlushModeSpecifies the log flush mode.
LogLevelSpecifies the debug log level.
LogMaxEventCountSpecifies the maximum number of events to cache before further action is taken.
LogRotationModeSpecifies the log rotation mode.
MaxASN1BufferLengthSpecifies the maximal allowed length for ASN.1 primitive tag data.
MaxASN1TreeDepthSpecifies the maximal depth for processed ASN.1 trees.
OCSPHashAlgorithmSpecifies the hash algorithm to be used to identify certificates in OCSP requests.
UseOwnDNSResolverSpecifies whether the client classes should use own DNS resolver.
UseSharedSystemStoragesSpecifies whether the validation engine should use a global per-process copy of the system certificate stores.
UseSystemOAEPAndPSSEnforces or disables the use of system-driven RSA OAEP and PSS computations.
UseSystemRandomEnables or disables the use of the OS PRNG.

Copyright (c) 2022 /n software inc. - All rights reserved.
SecureBlackbox 2020 iOS Edition - Version 20.0 [Build 8166]