Sascha Kiefer > Win32-Crypt > Win32::Crypt::API

Download:
Win32-Crypt-0.00_004.tar.gz

Dependencies

Annotate this POD

Module Version: 0.00_004   Source  

NAME ^

Win32::Crypt::API - Perl interface to functions that assist in working with Microsoft's CryptoAPI

SYNOPSIS ^

    use Win32::Crypt::API;

    my $capi = Win32::Crypt::API->new;

DESCRIPTION ^

Application programming interface that enables application developers to add authentication, encoding, and encryption to Win32-based applications.

METHODS ^

new

    my $cryptapi = Win32::Crypt::API->new;

constant_names

Returns a list of all available constants. It can either be called as a class

    Win32::Crypt::API->constant_names;

or an object method.

    $cryptapi->constant_names;

CRYPTOGRAPHIC SERVICE PROVIDER FUNCTIONS ^

Applications use service provider functions to connect and disconnect a cryptographic service provider (CSP).

CryptAcquireContext( phProv, pszContainer, pszProvider, dwProvType, dwFlags )

The CryptAcquireContext function is used to acquire a handle to a particular key container within a particular cryptographic service provider (CSP). This returned handle is used in calls to CryptoAPI functions that use the selected CSP.

This function first attempts to find a CSP with the characteristics described in the dwProvType and pszProvider parameters. If the CSP is found, the function attempts to find a key container within the CSP matching the name specified by the pszContainer parameter. To acquire the context and the key container of a private key associated with the public key of a certificate, use CryptAcquireCertificatePrivateKey.

With the appropriate setting of dwFlags, this function can also create and destroy key containers and can provide access to a CSP with a temporary key container if access to a private key is not required.

    BOOL WINAPI CryptAcquireContext(
        HCRYPTPROV *phProv,
        LPCTSTR pszContainer,
        LPCTSTR pszProvider,
        DWORD dwProvType,
        DWORD dwFlags
    );
Parameters
phProv

[out] Pointer to a handle of a cryptographic service provider (CSP).

pszContainer

[in] Key container name. This is a zero terminated string that identifies the key container to the CSP. This name is independent of the method used to store the keys. Some CSPs store their key containers internally (in hardware), some use the system registry, and others use the file system. When dwFlags is set to CRYPT_VERIFYCONTEXT, pszContainer must be set to zero.

When pszContainer is zero, a default key container name is used. For example, the Microsoft Base Cryptographic Provider uses the logon name of the user currently logged on as the key container name. Other CSPs can also have default key containers that can be acquired in this way.

Applications must not use the default key container to store private keys. When multiple applications use the same container, one application can change or destroy the keys that another application needs to have available. If applications use key containers linked to the application the risk is reduced of other applications tampering with keys necessary for proper function.

An application can obtain the name of the key container in use by reading the PP_CONTAINER value with the CryptGetProvParam function.

pszProvider

[in] zero terminated string specifying the name of the CSP to be used.

If this parameter is zero, the user default provider is used. For more information, see "Cryptographic Service Provider Contexts". For a list of available cryptographic providers, see "Cryptographic Provider Names".

An application can obtain the name of the CSP in use by reading the PP_NAME CSP value in the dwParam parameter with the CryptGetProvParam function.

Due to changing export control restrictions, the default CSP can change between operating system releases. To ensure interoperability on different operating system platforms, the CSP should be explicitly set using this parameter instead of using the default CSP.

dwProvType

[in] Specifies the type of provider to acquire. Defined provider types are discussed in "Cryptographic Provider Types".

dwFlags

[in] Flag values. This parameter is usually set to zero, but some applications set one or more of the following flags.

CRYPT_VERIFYCONTEXT

This option is intended for applications that do not use public/private key pairs, such as applications that perform only hashing and symmetric encryption. Only applications that create signatures or decrypt messages need access to a private key. All other applications should consider setting this flag. When this flag is set, the application has no access to the private keys of public/private key pairs, and the pszContainer parameter must be set to zero. In Windows 2000 and later, when this flag is set, temporary public key pairs can be created, but they are not persisted.

When CryptAcquireContext is called, many CSPs require input from the owning user before granting access to the private keys in the key container. For example, the private keys can be encrypted, requiring a password from the user before they can be used. However, if the CRYPT_VERIFYCONTEXT flag is specified, access to the private keys is not required and the user interface can be bypassed.

CRYPT_NEWKEYSET

Creates a new key container with the name specified by pszContainer. If pszContainer is zero, a key container with the default name is created.

CRYPT_MACHINE_KEYSET

By default, keys and key containers are stored as user keys. For Base Providers, this means that user key containers are stored in the user's profile. A key container created without this flag can only be accessed by the user creating the key container and a user with administration privileges.

The CRYPT_MACHINE_KEYSET flag can be combined with all of the other flags to indicate that the key container of interest is a machine key container and the CSP treats it as such. For Base Providers, this means that the keys are stored locally on the computer that created the key container. If a key container is to be a machine container, the CRYPT_MACHINE_KEYSET flag must be used with all calls to CryptAcquireContext that reference the machine container. The key container created with CRYPT_MACHINE_KEYSET can only be accessed by its creator and by user with administrator privileges unless access rights to the container are granted using CryptSetProvParam.

The CRYPT_MACHINE_KEYSET flag is useful when the user is accessing from a service or user account that did not log on interactively When key containers are created, most CSPs do not automatically create any public/private key pairs. These keys must be created as a separate step with the CryptGenKey function.

CRYPT_DELETEKEYSET

Delete the key container specified by pszContainer. If pszContainer is zero, the key container with the default name is deleted. All key pairs in the key container are also destroyed. When this flag is set, the value returned in phProv is undefined, and thus, the CryptReleaseContext function need not be called afterwards.

CRYPT_SILENT

The application requests that the CSP not display any user interface (UI) for this context. If the CSP must display the UI to operate, the call fails and the NTE_SILENT_CONTEXT error code is set as the last error. In addition, if calls are made to CryptGenKey with the CRYPT_USER_PROTECTED flag with a context that has been acquired with the CRYPT_SILENT flag, the calls fail and the CSP sets NTE_SILENT_CONTEXT.

CRYPT_SILENT is intended for use with applications for which the UI cannot be displayed by the CSP.

This flag is supported with Microsoft® Windows® 2000 or later. It is not supported in Windows 95, Windows 98, Windows Millennium or Microsoft® Internet Explorer version 5.0.

Return Values

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, the return value is zero (FALSE). For extended error information, call Win32::GetLastError().

The error codes prefaced by NTE are generated by the particular CSP being used. Some possible error codes follow.

ERROR_BUSY ( 170L )

Some CSPs set this error if the CRYPT_DELETEKEYSET flag value is set and another thread or process is using this key container.

ERROR_INVALID_PARAMETER ( 87L )

One of the parameters contains an invalid value. This is most often an invalid pointer.

ERROR_NOT_ENOUGH_MEMORY ( 8L )

The operating system ran out of memory during the operation.

NTE_BAD_FLAGS ( 0x80090009L )

The dwFlags parameter has an invalid value.

NTE_BAD_KEYSET( 0x80090016L )

The key container could not be opened. A common cause of this error is that the key container does not exist. To create a key container, call CryptAcquireContext using the CRYPT_NEWKEYSET flag. This error code can also indicate that access to an existing key container is denied. Access rights to the container can be granted by the key set creator using CryptSetProvParam.

NTE_BAD_KEYSET_PARAM( 0x8009001FL )

The pszContainer or pszProvider parameter is set to an invalid value.

NTE_BAD_PROV_TYPE( 0x80090014L )

The value of the dwProvType parameter is out of range. All provider types must be from 1 to 999, inclusive.

NTE_BAD_SIGNATURE( 0x80090006L )

The provider DLL signature could not be verified. Either the DLL or the digital signature has been tampered with.

NTE_EXISTS( 0x8009000FL )

The dwFlags parameter is CRYPT_NEWKEYSET, but the key container already exists.

NTE_KEYSET_ENTRY_BAD( 0x8009001AL )

The pszContainer key container was found but is corrupt.

NTE_KEYSET_NOT_DEF( 0x80090019L )

The key container specified by pszContainer does not exist or the requested provider does not exist.

NTE_NO_MEMORY( 0x8009000EL )

The CSP ran out of memory during the operation.

NTE_PROV_DLL_NOT_FOUND( 0x8009001EL )

The provider DLL file does not exist or is not on the current path.

NTE_PROV_TYPE_ENTRY_BAD( 0x80090018L )

The provider type specified by dwProvType is corrupt. This error can relate to either the user default CSP list or the computer default CSP list.

NTE_PROV_TYPE_NO_MATCH( 0x8009001BL )

The provider type specified by dwProvType does not match the provider type found. Note that this error can only occur when pszProvider specifies an actual CSP name.

NTE_PROV_TYPE_NOT_DEF( 0x80090017L )

No entry exists for the provider type specified by dwProvType.

NTE_PROVIDER_DLL_FAIL( 0x8009001DL )

The provider DLL file could not be loaded or failed to initialize.

NTE_SIGNATURE_FILE_BAD( 0x8009001CL )

An error occurred while loading the DLL file image, prior to verifying its signature.

Remarks

None.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 and later.

Windows 95/98/Me: Included in Windows 95 OSR2 and later.

Redistributable: Requires Internet Explorer 3.02 or later on Windows 95.

CryptContextAddRef( hProv, pdwReserved, dwFlags )

The CryptContextAddRef function adds one to the reference count of an HCRYPTPROV cryptographic service provider (CSP) handle. This function should be used if the CSP handle is included as a member of any structure passed to another function. The CryptReleaseContext function should be called when the CSP handle is no longer needed.

    BOOL WINAPI CryptContextAddRef(
        HCRYPTPROV hProv,
        DWORD *pdwReserved,
        DWORD dwFlags
    );
Parameters
hProv

[in] HCRYPTPROV handle for which the reference count is being incremented. This handle must have already been created using CryptAcquireContext.

pdwReserved

[in] Reserved for future use and must be zero.

dwFlags

[in] Reserved for future use and must be zero.

Return Values

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, the return value is zero (FALSE). For extended error information, call Win32::GetLastError(). One possible error code is the following.

ERROR_INVALID_PARAMETER

One of the parameters contains an invalid value. This is most often an invalid pointer.

Remarks

The CryptContextAddRef function is used to increase the reference count on a HCRYPTPROV handle so that multiple calls to CryptReleaseContext are required to actually release the handle.

Requirements

Windows NT/2000/XP: Included in Windows 2000 and later.

Windows 95/98/Me: Included in Windows 98 and later.

CryptEnumProviders( dwIndex, pdwReserved, dwFlags, pdwProvType, pszProvName, pcbProvName )

The CryptEnumProviders function retrieves the first or next available cryptographic service providers (CSPs). Used in a loop, this function can retrieve in sequence all of the CSPs available on a computer.

Possible CSPs include Microsoft Base Cryptographic Provider version 1.0 and Microsoft Enhanced Cryptographic Provider version 1.0.

    BOOL WINAPI CryptEnumProviders(
        DWORD dwIndex,
        DWORD *pdwReserved,
        DWORD dwFlags,
        DWORD *pdwProvType,
        LPTSTR pszProvName,
        DWORD *pcbProvName
    );
Parameters
dwIndex

[in] Index of the next provider to be enumerated.

pdwReserved

[in] Reserved for future use and must be zero.

dwFlags

[in] Reserved for future use and must be zero.

pdwProvType

[out] Address of the DWORD value designating the type of the enumerated provider.

pszProvName

[out] Pointer to a buffer that receives the data from the enumerated provider. This is a string including the terminating NULL character.

This parameter can be zero to set the size of the name for memory allocation purposes. For more information, see "Retrieving Data of Unknown Length".

pcbProvName

[in/out] Pointer to a DWORD value specifying the size, in bytes, of the buffer pointed to by the pszProvName parameter. When the function returns, the DWORD value contains the number of bytes stored in the buffer.

Note: When processing the data returned in the buffer, applications must use the actual size of the data returned. The actual size can be slightly smaller than the size of the buffer specified on input. (On input, buffer sizes are usually specified large enough to ensure that the largest possible output data fits in the buffer.) On output, the variable pointed to by this parameter is updated to reflect the actual size of the data copied to the buffer.

Return Values

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, the return value is zero (FALSE). For extended error information, call Win32::GetLastError.

The error codes prefaced by NTE are generated by the particular CSP being used. Some possible error codes follow.

ERROR_MORE_DATA

The pszProvName buffer was not large enough to hold the provider name.

ERROR_NO_MORE_ITEMS

There are no more items to enumerate.

ERROR_NOT_ENOUGH_MEMORY

The operating system ran out of memory.

NTE_BAD_FLAGS

The dwFlags parameter has an unrecognized value.

NTE_FAIL

Something was wrong with the type registration.

Remarks

CryptEnumProviders is used to enumerate the providers on a computer. The provider types can be enumerated by using CryptEnumProviderTypes.

Requirements

Windows NT/2000/XP: Included in Windows 2000 and later.

Windows 95/98/Me: Included in Windows 98 and later.

CryptEnumProviderTypes

Parameters
Return Values
Remarks
Requirements

CryptGetDefaultProvider

Parameters
Return Values
Remarks
Requirements

CryptGetProvParam

Parameters
Return Values
Remarks
Requirements

CryptInstallDefaultContext

Parameters
Return Values
Remarks
Requirements

CryptReleaseContext

Parameters
Return Values
Remarks
Requirements

CryptSetProvider

Parameters
Return Values
Remarks
Requirements

CryptSetProviderEx

Parameters
Return Values
Remarks
Requirements

CryptSetProvParam

Parameters
Return Values
Remarks
Requirements

CryptUninstallDefaultContext

Parameters
Return Values
Remarks
Requirements

CERTIFICATE STORE FUNCTIONS ^

A user site can, over time, collect many certificates. Typically, a site has certificates for the user of the site, and other certificates describing those individuals and entities with whom the user communicates. For each entity, there can be more than one certificate. For each individual certificate, there should be a chain of verifying certificates that provides a trail back to a trusted root certificate. Certificate stores and their related functions provide functionality to store, retrieve, enumerate, verify, and use the information stored in the certificates.

The following functions are used to work with the certificate stores, themselves.

CertAddStoreToCollection( hCollectionStore, hSiblingStore, dwUpdateFlag, dwPriority )

The CertAddStoreToCollection function adds a sibling certificate store to a collection certificate store. When a certificate store has been added to a collection store, all of the certificates, CRLs, and CTLs in the store that has been added to the collection store can be retrieved by find or enumerate function calls using the collection store.

    BOOL WINAPI CertAddStoreToCollection(
        HCERTSTORE hCollectionStore,
        HCERTSTORE hSiblingStore,
        DWORD dwUpdateFlag,
        DWORD dwPriority
    );
Parameters
hCollectionStore

[in] Handle of a certificate store.

hSiblingStore

[in/optional] Handle of a sibling store to be added to the collection store. For more information, see the Remarks section later in this topic.

dwUpdateFlag

[in] Indicates whether certificates, CRLs, and CTLs can be added to the new sibling store member of the collection store. Set dwUpdateFlag to CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG to enable addition or to zero to disable additions.

dwPriority

[in] Sets a priority level of the new store in the collection, with zero being the lowest priority. If zero is passed for this parameter, the specified store is appended as the last store in the collection. The priority levels of the stores in a collection determine the order in which the stores are enumerated, and the search order of the stores when attempting to retrieve a certificate, CRL, or CTL. Priority levels also determine to which store of a collection a new certificate, CRL, or CTL is added. For further information, see the Remarks section later in this topic.

Return Values

If the function succeeds, a new store is added to the collection of stores and the return value is TRUE.

If the function fails, the store was not added and the return value is FALSE.

Remarks

A collection store has the same HCERTSTORE handle as a single store; thus, almost all functions that apply to any certificate store also apply to any collection store. Enumeration and search processes span all of the stores in a collection store; however, functions such as CertAddCertificateLinkToStore that add links to stores cannot be used with collection stores.

When a certificate, CRL, or CTL is added to a collection store, the list of sibling stores in the collection is searched in priority order to find the first store that allows adding. Adding is enabled if C ERT_PHYSICAL_STORE_ADD_ENABLE_FLAG was set in the CertAddStoreToCollection call. With any function that adds elements to a store, if a store that allows adding does not return success, the addition function continues on to the next store without providing notification.

When a collection store and its sibling stores are closed with CertCloseStore using CERT_CLOSE_STORE_FORCE_FLAG, the collection store must be closed before its sibling stores. If CERT_CLOSE_STORE_FORCE_FLAG is not used, the stores can be closed in any order.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertAddCertificateLinkToStore( hCertStore, pCertContext, dwAddDisposition, ppStoreContext )

The CertAddCertificateLinkToStore function adds a link in a certificate store to a certificate context in a different store. Instead of creating and adding a duplicate of the certificate context, this function adds a link to the original certificate.

    BOOL WINAPI CertAddCertificateLinkToStore(
        HCERTSTORE hCertStore,
        PCCERT_CONTEXT pCertContext,
        DWORD dwAddDisposition,
        PCCERT_CONTEXT *ppStoreContext
    );
Parameters
hCertStore

[in] Handle to the certificate store where the link is to be added.

pCertContext

[in] Pointer to the CERT_CONTEXT structure to be linked.

dwAddDisposition

[in] Specifies the action if a matching certificate or a link to a matching certificate already exists in the store. Currently defined disposition values and their uses are as follows.

CERT_STORE_ADD_ALWAYS

The function makes no check for an existing matching certificate or link to a matching certificate. A new certificate is always added to the store. This can lead to duplicates in a store.

CERT_STORE_ADD_NEW

If a matching certificate or a link to a matching certificate exists, the operation fails. Win32::GetLastError() returns the CRYPT_E_EXISTS code.

CERT_STORE_ADD_REPLACE_EXISTING

If a link to a matching certificate exists, that existing link is deleted and a new link is created and added to the store. If no matching certificate or link to a matching certificate exists, one is added.

CERT_STORE_ADD_USE_EXISTING

If a matching certificate or a link to a matching certificate exists, the existing certificate is used. The function does not fail, but no new link is added. If no matching certificate or link to a matching certificate exists, a new link is added.

ppStoreContext

[out/optional] Pointer to a pointer to a copy of the link created. The ppStoreContext parameter can be NULL to indicate that a copy of the link is not needed. If a copy of the link is created, that copy must be freed using CertFreeCertificateContext.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. For extended error information, call Win32::GetLastError(). Some possible error codes follow.

CRYPT_E_EXISTS

For a dwAddDisposition parameter of CERT_STORE_ADD_NEW, the certificate already exists in the store.

E_INVALIDARG

An invalid disposition value was specified in the dwAddDisposition parameter.

Remarks

Because the link provides access to the original certificate context, setting an extended property in the linked certificate context changes that extended property in the certificate's original location and in any other links to that certificate.

Links cannot be added to a store opened as a collection. Stores opened as collections include all stores opened with CertOpenSystemStore or CertOpenStore using CERT_STORE_PROV_SYSTEM or CERT_STORE_PROV_COLLECTION. For additional information, see CertAddStoreToCollection.

If links are used and CertCloseStore is called with CERT_CLOSE_STORE_FORCE_FLAG, the store using links must be closed before the store containing the original contexts is closed. If CERT_CLOSE_STORE_FORCE_FLAG is not used, the two stores can be closed in either order.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertCloseStore( hCertStore, dwFlags )

The CertCloseStore function closes a certificate store handle and reduces the reference count on the store. There needs to be a corresponding call to CertCloseStore for each successful call to the CertOpenStore or CertDuplicateStore functions.

    BOOL WINAPI CertCloseStore(
        HCERTSTORE hCertStore,
        DWORD dwFlags
    );
Parameters
hCertStore

[in] Handle of the certificate store to be closed.

dwFlags

[in] Typically, this parameter uses the default value zero. The default is to close the store with memory remaining allocated for contexts that have not been freed. In this case, no check is made to determine whether memory for contexts remains allocated.

Set flags can force the freeing of memory for all of a store's certificate, CRL, and CTL contexts when the store is closed. Flags can also be set that check whether all of the store's certificate, CRL, and CTL contexts have been freed. The following values are defined.

CERT_CLOSE_STORE_CHECK_FLAG

Checks for nonfreed certificate, CRL, and CTL contexts. A returned error code indicates that one or more store elements is still in use. This flag should only be used as a diagnostic tool in the development of applications.

CERT_CLOSE_STORE_FORCE_FLAG

Forces the freeing of memory for all contexts associated with the store. This flag can be safely used only when the store is opened in a function and neither the store handle nor any of its contexts are passed to any called functions. For details, see the Remarks section later in this topic.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. For extended error information, call Win32::GetLastError().

If CERT_CLOSE_STORE_CHECK_FLAG is not set or if it is set and all contexts associated with the store have been freed, the return value is TRUE.

If CERT_CLOSE_STORE_CHECK_FLAG is set and memory for one or more contexts associated with the store remains allocated, the return value is FALSE. The store is always closed even when the function returns FALSE.

Win32::GetLastError() is set to CRYPT_E_PENDING_CLOSE if memory for contexts associated with the store remains allocated. Any existing value returned by Win32::GetLastError() is preserved unless CERT_CLOSE_STORE_CHECK_FLAG is set.

Remarks

While a certificate store is open, contexts from that store can be retrieved or duplicated. When a context is retrieved or duplicated, its reference count is incremented. When a context is freed by passing it to a search or enumeration function as a previous context or by using CertFreeCertificateContext, CertFreeCRLContext, or CertFreeCTLContext, its reference count is decremented. When a context's reference count reaches zero, memory allocated for that context is automatically freed. When the memory allocated for a context has been freed, any pointers to that context become invalid.

By default, memory used to store contexts with reference count greater than zero is not freed when a certificate store is closed. References to those contexts remain valid; however, this can cause "memory leaks." Also, any changes made to the properties of a context after the store has been closed are not persisted.

To force the freeing of memory for all contexts associated with a store, set CERT_STORE_CLOSE_FORCE_FLAG. With this flag set, memory for all contexts associated with the store is freed and all pointers to certificate, CRL, or CTL contexts associated with the store become invalid. This flag should only be set when the store is opened in a function and neither the store handle nor any of its contexts were ever passed to any called functions.

The status of reference counts on contexts associated with a store can be checked when the store is closed by using CERT_CLOSE_STORE_CHECK_FLAG. When this flag is set, and all certificate, CRL, or CTL contexts have not been released, the function returns FALSE and Win32::GetLastError() returns CRYPT_E_PENDING_CLOSE. Note that the store is still closed when FALSE is returned and the memory for any active contexts is not freed.

If CERT_STORE_NO_CRYPT_RELEASE_FLAG was not set when the store was opened, closing a store releases its CSP handle.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP3 and later.

Windows 95/98/Me: Included in Windows 95 OSR2 and later.

Redistributable: Requires Internet Explorer 3.02 or later on Windows NT 4.0.

CertControlStore( hCertStore, dwFlags, dwCtrlType, dwCtrlType )

The CertControlStore function allows an application to be notified when there is a difference between the contents of a cached store in use and the contents of that store as it is persisted to storage. Differences can occur as another process makes a change that affects the store as it is persisted.

The CertControlStore function can be used to synchronize a cached store if necessary, and provides a means to commit changes made in the cached store to persisted storage. Additional functionality is planned.

    BOOL WINAPI CertControlStore(
        HCERTSTORE hCertStore,
        DWORD dwFlags,
        DWORD dwCtrlType,
        void const *dwCtrlType
    );
Parameters
hCertStore

[in] Handle of the certificate store.

dwFlags

[in] If the dwCtrlType parameter is set to CERT_STORE_CTRL_COMMIT, the following dwFlags are defined:

CERT_STORE_CTRL_COMMIT_FORCE_FLAG

Forces the contents of the cache memory store to be copied to permanent storage even if the cache has not been changed.

CERT_STORE_CTRL_COMMIT_CLEAR_FLAG

Inhibits the copying the contents of the cache memory store to permanent storage even when the store is closed.

CERT_STORE_CTRL_INHIBIT_DUPLICATE_HANDLE_FLAG

Inhibits a duplicate handle of the event HANDLE. If this flag is set, CertControlStore with CERT_STORE_CTRL_CANCEL_NOTIFY passed must be called for this event HANDLE before closing the hCertStore handle.

If dwCtrlType is set to CERT_STORE_CTRL_NOTIFY_CHANGE or CERT_STORE_CTRL_RESYNC, the dwFlags parameter is not used and must be set to zero.

dwCtrlType

[in] Control action to be taken by CertControlStore. The interpretations of pvCtrlPara and dwFlags depend on the value of dwCtrlType. Currently, the following three actions are defined:

CERT_STORE_CTRL_RESYNC

The cached store is resynchronized and made to match the persisted store.

CERT_STORE_CTRL_NOTIFY_CHANGE

A signal is returned in the space pointed to by pvCtrlPara to indicate that the current contents of the cached store differ from the store's persisted state.

CERT_STORE_CTRL_COMMIT

Any changes made to the cached store are copied to persisted storage. If no changes were made since the cached store was opened or since the last commit, the call is ignored. The call is also ignored if the store provider is a provider that automatically persists changes immediately.

CERT_STORE_CTRL_AUTO_RESYNC

At the start of every enumeration or find store call, a check is made to determine whether or not a change has been made in the store. If the store h as changed, a re-synchronization is done. This check is only done on first enumeration or find calls, when the pPrevContext is zero.

The pvCtrPara member is not used and must be set to zero.

CERT_STORE_CTRL_CANCEL_NOTIFY

Cancels notification signaling of the event HANDLE passed in a previous CERT_STORE_CTRL_NOTIFY_CHANGE or CERT_STORE_CTRL_RESYNC. The pvCtrlPara parameter points to the event HANDLE to be canceled.

pvCtrlPara

[in] If dwCtrlType is CERT_STORE_NOTIFY_CHANGE, pvCtrlPara is set to the address of a handle where the system signals the notification change event when a change from the persisted state of the store is detected. The handle must be initialized with a call to the function CreateEvent. The pvCtrlPara parameter can be set to NULL for registry-based stores. If pvCrtlPara is zero, an internal notification change event is created and registered to be signaled. Using the internal notification change event allows resynchronization operations only if the store was changed.

If dwCtrlType is CERT_STORE_CTRL_RESYNC, set pvCtrlPara to the address of the event handle to be signaled on the next change in the persisted store. Typically, this address is the address of the event handle passed with CERT_STORE_CTRL_NOTIFY_CHANGE during initialization. The event handle passed is rearmed. If pvCtrlPara is set to zero, no event is rearmed.

If dwCtrlType CERT_STORE_CTRL_COMMIT, pvCtrlPara is not used and must be set to zero.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. For extended error information, call Win32::GetLastError().

If dwCtrlType is CERT_STORE_NOTIFY_CHANGE, the function returns TRUE if a handle for the event signal was successfully set up. The function returns FALSE if the event handle was not set up.

If dwCtrlType is CERT_STORE_CTRL_RESYNC, the function returns TRUE if the resynchronization succeeded and FALSE if the resynchronization failed.

If dwCtrlType is CERT_STORE_CTRL_COMMIT, the function returns TRUE to indicate the successful completion of the commit to persisted storage and FALSE if the commit failed.

Some providers might not support specific control types. In these cases, CertControlStore returns FALSE and GetLastError is set to the ERROR_NOT_SUPPORTED code.

Remarks

Resynchronization of a store can be done at any time. It need not follow a signaled notification change event.

CERT_STORE_CTRL_NOTIFY_CHANGE is supported on registry based store providers by using the RegNotifyChangeKeyValue function.

CertControlStore using CERT_STORE_CTRL_NOTIFY_CHANGE is called once for each event handle to be passed with CERT_STORE_CTRL_RESYNC. These calls using CERT_STORE_CTRL_NOTIFY_CHANGE must be made after each event is created and not after an event has been signaled.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertDuplicateStore( hCertStore )

The CertDuplicateStore function duplicates a store handle by incrementing the store's reference count.

    HCERTSTORE WINAPI CertDuplicateStore(
        HCERTSTORE hCertStore
    );
Parameters
hCertStore

[in] Handle of the certificate store for which the reference count is being incremented.

Return Values

Currently, a copy is not made of the handle, and the returned handle is the same as the handle that was input. If zero is passed in, the called function will raise an access violation (AV) exception.

Remarks

None.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP3 and later.

Windows 95/98/Me: Included in Windows 95 OSR2 and later.

Redistributable: Requires Internet Explorer 3.02 or later on Windows NT 4.0.

CertEnumPhysicalStore( pvSystemStore, dwFlags, pvArg, pfnEnum )

The CertEnumPhysicalStore function retrieves the physical store on a computer. The function calls the provided callback function for each physical store found.

    BOOL WINAPI CertEnumPhysicalStore(
        const void *pvSystemStore,
        DWORD dwFlags,
        void *pvArg,
        PFN_CERT_ENUM_PHYSICAL_STORE pfnEnum
    );
Parameters
pvSystemStore

[in] If CERT_SYSTEM_STORE_RELOCATE_FLAG is set in dwFlags, pvSystemStore points to a CERT_SYSTEM_STORE_RELOCATE_PARA structure that indicates both the name and the location of the system store to be enumerated. Otherwise, pvSystemStore is a pointer to a Unicode string that names the system store whose physical stores are to be enumerated. For details on prefixing a ServiceName or ComputerName to the system store name, see CertRegisterSystemStore.

dwFlags

[in] Specifies the location of the system store. The following flag values are defined.

  • CERT_SYSTEM_STORE_CURRENT_USER
  • CERT_SYSTEM_STORE_CURRENT_SERVICE
  • CERT_SYSTEM_STORE_LOCAL_MACHINE
  • CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY
  • CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY
  • CERT_SYSTEM_STORE_SERVICES
  • CERT_SYSTEM_STORE_USERS
  • CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE

In addition, CERT_SYSTEM_STORE_RELOCATE_FLAG can be combined using a bitwise-OR operation with any of the high-word location flags.

pvArg

[in] Pointer to a void that allows the application to declare, define, and initialize a structure to hold any information to be passed to the callback enumeration function.

pfnEnum

[in] Pointer to the callback function used to show the details for each physical store. This callback function determines the content and format for the presentation of information on each physical store. The application must provide the callback function and declare the following signature:

    BOOL WINAPI CertEnumPhysicalStoreCallback(
        const void *pvSystemStore,
        DWORD dwFlags,
        LPCWSTR pwszStoreName,
        PCERT_SYSTEM_STORE_INFO pStoreInfo,
        void *pvReserved,
        void *pvArg
    );

The pvArg parameter passed to the callback function is the pvArg pointer passed to CertEnumPhysicalStore.

Return Values

If the function succeeds and another physical store was found, the return value is TRUE.

If the function fails and another physical store was not found, the return value is FALSE. For extended error information, call GetLastError.

If the system store location only supports system stores and does not support physical stores, the function returns FALSE and Win32::GetLastError() returns the ERROR_NOT_SUPPORTED code.

Remarks

To use CertEnumPhysicalStore, an application must declare and define the ENUM_ARG structure and an enumeration callback function.

To access a remote store, the security permissions in the registry keys on that remote computer must be set to allow access. For more information on setting security permissions in a Windows registry, see MSDN Article ID Q155363.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertEnumSystemStore( dwFlags, pvSystemStoreLocationPara, pvArg, pfnEnum )

The CertEnumSystemStore function retrieves the system store available. The function calls the provided callback function for each system store found.

    BOOL WINAPI CertEnumSystemStore(
        DWORD dwFlags,
        void *pvSystemStoreLocationPara,
        void *pvArg,
        PFN_CERT_ENUM_SYSTEM_STORE pfnEnum
    );
Parameters
dwFlags

[in] Specifies the location of the system store. The following flag values are defined.

  • CERT_SYSTEM_STORE_CURRENT_USER
  • CERT_SYSTEM_STORE_CURRENT_SERVICE
  • CERT_SYSTEM_STORE_LOCAL_MACHINE
  • CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY
  • CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY
  • CERT_SYSTEM_STORE_SERVICES
  • CERT_SYSTEM_STORE_USERS
  • CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE

In addition, CERT_SYSTEM_STORE_RELOCATE_FLAG can be combined using a bitwise-OR operation with any of the high-word location flags.

pvSystemStoreLocationPara

in/optional] If CERT_SYSTEM_STORE_RELOCATE_FLAG is set in the dwFlags parameter, pvSystemStoreLocationPara points to a CERT_SYSTEM_STORE_RELOCATE_PARA structure that indicates both the name and the location of the system store. Otherwise, pvSystemStoreLocationPara is a pointer to a Unicode string that names the system store. For CERT_SYSTEM_STORE_LOCAL_MACHINE or CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY, pvSystemStoreLocationPara can optionally be set to a Unicode computer name for enumerating local computer stores on a remote computer, for example "\\ComputerName" or "ComputerName". The leading "\\" backslashes are optional in the ComputerName.

For CERT_SYSTEM_STORE_SERVICES or CERT_SYSTEM_STORE_USERS, if pvSystemStoreLocationPara is zero, the function enumerates both the service/user names and the stores for each service/user name. Otherwise, pvSystemStoreLocationPara is a Unicode string specifying a remote computer name and/or service/user name, for example "ServiceName,""\\ComputerName," or "ComputerName\."

If only the ComputerName is specified, it must have either the leading "\\" backslashes or a trailing backslash. Otherwise, it is interpreted as the ServiceName or UserName.

pvArg

[in] Pointer to a void allowing the application to declare, define, and initialize a structure to hold any information to be passed to the callback enumeration function.

pfnEnum

[in] Pointer to the callback function used to show the details for each system store. This callback function determines the content and format for the presentation of information on each system store. The application must provide the callback function and must declare it with the following signature:

    BOOL WINAPI CertEnumSystemStoreCallback(
        const void *pvSystemStore,
        DWORD dwFlags,
        PCERT_SYSTEM_STORE_INFO pStoreInfo,
        void *pvReserved,
        void *pvArg
    );

The pvArg parameter passed by CertEnumSystemStore to the callback function is the pvArg pointer passed to CertEnumSystemStore.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To use CertEnumSystemStore, the application must declare and define the ENUM_ARG structure and an enumeration callback function.

To access a remote store, the security permissions in the registry keys on that remote computer must be set to allow access. For more information on setting security permissions in a Windows registry, see MSDN Article ID Q155363.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertEnumSystemStoreLocation( dwFlags, pvArg, pgnEnum )

The CertEnumSystemStoreLocation function retrieves all of the system store locations. The function calls the provided callback function for each system store location found.

    BOOL WINAPI CertEnumSystemStoreLocation(
        DWORD dwFlags,
        void *pvArg,
        PFN_CERT_ENUM_SYSTEM_STORE_LOCATION pfnEnum
    );
Parameters
dwFlags

[in] Reserved for future use and must be zero.

pvArg

in] Pointer to a void allowing the application to declare, define, and initialize a structure to hold any information to be passed to the callback enumeration function.

pfnEnum

[in] Pointer to the callback function used to show the details for each store location. This callback function determines the content and format for the presentation of information on each store location. The callback function must be provided by the application and must be declared with the following signature:

    BOOL WINAPI CertEnumStoreLocationCallback(
        LPCWSTR pvszStoreLoocations
        DWORD dwFlags,
        void *pvReserved,
        void *pvArg
    );

The pvArg parameter passed to the callback function is the pvArg pointer passed to CertEnumSystemStoreLocation.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To use CertEnumSystemStoreLocation, an application must declare and define the ENUM_ARG structure and an enumeration callback function.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertGetStoreProperty( hCertStore, dwPropId, pvData, pcbData )

The CertGetStoreProperty function retrieves a store property.

    BOOL CertGetStoreProperty(
        HCERTSTORE hCertStore,
        DWORD dwPropId,
        void *pvData,
        DWORD *pcbData
    );
Parameters
hCertStore

[in] Handle of an open certificate store.

dwPropId

[in] Indicates one of a range of store properties. There is one predefined store property, CERT_STORE_LOCALIZED_NAME_PROP_ID, the localized name of the store.

User defined properties must be outside the current range of values for predefined context properties. Currently, user-defined dwPropId values begin at 4,096.

pvData

[out] Pointer to a buffer that receives the data as determined by dwPropId. For CERT_STORE_LOCALIZED_NAME_PROP_ID, this is the localized name of the store, and pvData points to a zero terminated Unicode, wide-character string. For other dwPropIds, pvData points to an array of bytes.

This parameter can be zero to set the size of this information for memory allocation purposes. For more information, see "Retrieving Data of Unknown Length".

pcbData

[in/out] Pointer to a DWORD value that specifies the size, in bytes, of the pvData buffer. When the function returns, the DWORD value contains the number of bytes stored in the buffer.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

If the store property is found, the function returns TRUE, pvData points to the property, and pcbData points to the length of the string. If the store property is not found, the function returns FALSE and Win32::GetLastError() returns CRYPT_E_NOT_FOUND.

Remarks

Store property identifiers are properties applicable to an entire store. They are not properties on an individual certificate, CRL, or CTL context. Currently, no store properties are persisted.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertOpenStore( lpszStoreProvider, dwMsgAndCertEncodingType, hCryptProv, dwFlags, pvPara )

The CertOpenStore function opens a certificate store using a specified store provider type. While this function can open a certificate store for most purposes, CertOpenSystemStore is recommended to open the most common certificate stores. CertOpenStore is required for more complex options and special cases.

    HCERTSTORE WINAPI CertOpenStore(
        LPCSTR lpszStoreProvider,
        DWORD dwMsgAndCertEncodingType,
        HCRYPTPROV hCryptProv,
        DWORD dwFlags,
        const void *pvPara
    );
Parameters
lpszStoreProvider

[in] Specifies the store provider type. The following predefined store provider types furnish most common application needs.

  • CERT_STORE_PROV_MEMORY
  • CERT_STORE_PROV_FILENAME
  • CERT_STORE_PROV_SYSTEM
  • CERT_STORE_PROV_PKCS7
  • CERT_STORE_PROV_SERIALIZED
  • CERT_STORE_PROV_COLLECTION
  • CERT_STORE_PROV_SYSTEM_REGISTRY
  • CERT_STORE_PROV_PHYSICAL
  • CERT_STORE_PROV_SMART_CARD
  • CERT_STORE_PROV_LDAP

The store provider type passed in lpszStoreProvider determines the type of the parameter passed in pvPara and the use and meaning of the high word of the dwFlags parameter.

For more information, please check http://msdn.mircosoft.com.

dwMsgAndCertEncodingType

[in] Applicable only to the CERT_STORE_PROV_PKCS7 or CERT_STORE_PROV_FILENAME provider types. For all other provider types, this parameter is unused and should be set to zero.

Both a certificate and a message encoding type are required for the CERT_STORE_PROV_PKCS7 and CERT_STORE_PROV_FILENAME provider types. The LOWORD specifies the encoding type of certificates, CRLs, and CTLs in the cryptographic message. The HIWORD specifies the encoding type of the message. Encoding types are specified by combining the two encoding types with a bitwise-OR operation.

The most common encoding types are used by passing

    X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
hCryptProv

[in] Handle to a cryptographic provider. Passing zero in this parameter causes an appropriate, default provider to be used. Using the default provider is recommended. The default or specified cryptographic provider is used for all store functions that verify the signature of a subject certificate or CRL.

dwFlags

[in] These values consist of high-word and low-word values combined using a bitwise-OR operation. The low-word portion of dwFlags controls a variety of general characteristics of the certificate store opened. This portion can be used with all store provider types. Currently defined low-word values are:

CERT_STORE_CREATE_NEW_FLAG

A new store is created if one did not exist. The function fails if the store already exists.

If neither CERT_STORE_OPEN_EXISTING_FLAG nor CERT_STORE_CREATE_NEW_FLAG is set, a store is opened if it exists or is created and opened if it did not already exist.

CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG

The closing of a store's provider cannot be done when CertCloseStore is called but will be deferred if certificates, CRLs, or CTLs obtained from the store are still in use. The store is actually closed when the last certificate, CRL, or CTL obtained from the store is freed. Any changes made to properties of these certificates, CRLs, and CTLs, even after the call to CertCloseStore, are persisted.

If this flag is not set and certificates, CRLs, or CTLs obtained from the store are still in use, the properties of those certificates, CRLs, and CTLs can be changed, but those changes are not persisted. Setting this flag causes those changes to be persisted.

Note that setting this flag causes extra overhead in doing context duplications and free operations.

If CertCloseStore is called with CERT_CLOSE_STORE_FORCE_FLAG, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG is ignored.

When this flag is set and a non-zero hCryptProv value is passed, that provider will continue to be used even after the call to CertCloseStore.

CERT_STORE_DELETE_FLAG

The store is deleted instead of being opened. CertOpenStore returns zero for both success and failure of the deletion. To determine the success of the deletion, call Win32::GetLastError, which returns zero if the store was deleted and a nonzero value if it was not deleted.

CERT_STORE_ENUM_ARCHIVED_FLAG

Overrides the default procedure of skipping in enumerations all certificates with the CERT_ARCHIVED_PROP_ID property set. If this flag is set, an enumeration of the certificates in the store lists all of the certificates in the store, including those that have the CERT_ARCHIVED_PROP_ID property.

CERT_STORE_MANIFOLD_FLAG

Certificates are checked for their manifold extension. When certificates are found with the same manifold extension, the "older" certificates are archived by setting their CERT_ARCHIVED_PROP_ID properties.

CERT_STORE_NO_CRYPT_RELEASE_FLAG

This flag is not used when the zero is passed in the hCryptProv parameter and the default CSP is used. The flag is valid when a non-zero CSP handle is passed as the hCryptProv parameter. Setting this flag prevents the automatic release of a non-default CSP when the certificate store is closed.

CERT_STORE_OPEN_EXISTING_FLAG

Only an existing store can be opened. If the store does not exist, the function fails.

CERT_STORE_READONLY_FLAG

Any attempt to change the contents of the store results in an error. When this flag is set and a registry based store provider is being used, the registry subkeys are opened by using RegOpenKey with KEY_READ_ACCESS. Otherwise, the registry subkeys are created by using RegCreateKey with KEY_ALL_ACCESS.

CERT_STORE_SET_LOCALIZED_NAME_FLAG

If this flag is supported, the provider sets the store's CERT_STORE_LOCALIZED_NAME_PROP_ID property. The localized name can be retrieved by calling CertGetStoreProperty with dwPropID set to CERT_STORE_LOCALIZED_NAME_PROP_ID. This flag is supported for providers of types CERT_STORE_PROV_FILENAME, CERT_STORE_PROV_SYSTEM, CERT_STORE_PROV_SYSTEM_REGISTRY, and CERT_STORE_PROV_PHYSICAL.

CERT_STORE_UPDATE_KEYID_FLAG

Within CurrentUser and LocalMachine, lists of key identifiers exist. These key identifiers have properties much like the properties of certificates. If the CERT_STORE_UPDATE_KEYID_FLAG is set, then for every key identifier in the store's location that has a CERT_KEY_PROV_INFO_PROP_ID property, that property is automatically updated from the key identifier property CERT_KEY_PROV_INFO_PROP_ID or the CERT_KEY_IDENTIFIER_PROP_ID of the certificate related to that key identifier.

CERT_STORE_BACKUP_RESTORE_FLAG

Uses the thread's SE_BACKUP_NAME and SE_RESTORE_NAME privileges to open registry or file-based system stores. If the thread does not have these privileges, CertOpenStore fails with an access denied error.

The CERT_STORE_PROV_SYSTEM, CERT_STORE_PROV_SYSTEM_REGISTER, and CERT_STORE_PROV_PHYSICAL provider types use the following high words of dwFlags to specify system store registry locations:

  • CERT_SYSTEM_STORE_CURRENT_SERVICE
  • CERT_SYSTEM_STORE_CURRENT_USER
  • CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY
  • CERT_SYSTEM_STORE_LOCAL_MACHINE
  • CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE
  • CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY
  • CERT_SYSTEM_STORE_SERVICES
  • CERT_SYSTEM_STORE_USERS

A system store location opens, by default, relative to the HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE or HKEY_USERS predefined registry key.

The following high-word flags override this default behavior.

CERT_SYSTEM_STORE_RELOCATE_FLAG

When set, pvPara must pass a pointer to a CERT_SYSTEM_STORE_RELOCATE_PARA structure rather than a string. The structure indicates both the name of the store and its location in the registry.

CERT_SYSTEM_STORE_UNPROTECTED_FLAG

By default, when the CurrentUser "Root" store is opened, any SystemRegistry roots not on the protected root list are deleted from the cache before CertOpenStore returns. When this flag is set, this default is overridden and all of the roots in the SystemRegistry are returned and no check of the protected root list is made.

The CERT_STORE_PROV_REGISTRY provider uses the following high-word flags.

CERT_REGISTRY_STORE_SERIALIZED_FLAG

The CERT_STORE_PROV_REG provider saves certificates, CRLs, and CTLs in a single, serialized store subkey instead of performing the default save operation. The default is that each certificate, CRL, or CTL is saved as a separate registry subkey under the appropriate subkey.

This flag is mainly used for stores downloaded from the GPT, such as the CurrentUserGroupPolicy and LocalMachineGroupPolicy stores.

When CERT_REGISTRY_STORE_SERIALIZED_FLAG is set, store additions, deletions, or property changes are not persisted until there is a call to either CertCloseStore or CertControlStore using CERT_STORE_CTRL_COMMIT.

CERT_REGISTRY_STORE_REMOTE_FLAG

The key passed in pvPara points to a registry key on a remote computer. To access a registry key on a remote computer, security permissions on the remote computer must be set to allow access. For further details, see the Remarks section later in this topic.

The file provider types, CERT_STORE_PROV_FILE and CERT_STORE_PROV_FILENAME, use the CERT_FILE_STORE_COMMIT_ENABLE high word flag. Setting this flag commits any additions to the store or any changes made to properties of contexts in the store to the file store either when CertCloseStore is called or when CertControlStore is called with CERT_STORE_CONTROL_COMMIT.

CertOpenStore fails with E_INVALIDARG if both CERT_FILE_STORE_COMMIT_ENABLE and CERT_STORE_READONLY_FLAG are set in dwFlags.

The CERT_STORE_PROV_LDAP provider type uses the following high word flags.

CERT_LDAP_STORE_SIGN_FLAG

To provide integrity required by some applications, digitally sign all LDAP traffic to and from a Windows 2000 LDAP server using the Kerberos authentication protocol.

CERT_LDAP_STORE_AREC_EXCLUSIVE_FLAG

Performs an A-Record-only DNS lookup on the URL named in the pvPara parameter. This prevents bogus DNS queries from being generated when resolving URL host names. Use this flag when passing a hostname as opposed to a domain name for the pvPara parameter.

pvPara

[in] Pointer to a VOID that can point to data of different data types depending on the provider being used. Detailed information about the type and content to be passed in pvPara is specified in the descriptions of the available providers.

Return Values

If the function succeeds, the return value is a handle to the certificate store.

If the function fails, the return value is zero. For extended error information, call Win32::GetLastError().

Remarks

A system store is a collection consisting of one or more physical sibling stores. For each system store, there are predefined physical sibling stores. After opening a system store such as MY at CERT_SYSTEM_STORE_CURRENT_USER, CertOpenStore is called to open of all of the physical stores in the system store collection. Each of these physical stores is added to the system store collection using CertAddStoreToCollection. All certificates, CRLs, and CTLs in those physical stores are available through the logical system store collection.

The following system store locations can be opened remotely:

  • CERT_SYSTEM_STORE_LOCAL_MACHINE
  • CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY
  • CERT_SYSTEM_STORE_SERVICES
  • CERT_SYSTEM_STORE_USERS

System store locations are opened remotely by prefixing the store name in the string passed to pvPara with the computer name. Examples of remote system store names are:

  • ComputerName\CA
  • \\ComputerName\CA
  • ComputerName\ServiceName\Trust
  • \\ComputerName\ServiceName\Trust

To access a remote store, the security permissions in the registry keys on the remote computer must be set to allow access. For more information on setting security permissions in a Windows registry, see MSDN Article ID Q155363.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP3 and later.

Windows 95/98/Me: Included in Windows 95 OSR2 and later.

Redistributable: Requires Internet Explorer 3.02 or later on Windows NT 4.0.

CertOpenSystemStore( hProv, szSubsystemProtocol )

The CertOpenSystemStore function is a simplified function used to open the most common system certificate store. To open certificate stores with more complex requirements, such as file-based or memory-based stores, use CertOpenStore.

    HCERTSTORE WINAPI CertOpenSystemStore(
        HCRYPTPROV hProv,
        LPCTSTR szSubsystemProtocol
    );
Parameters
hProv

[in] HCRYPTPROV handle of a cryptographic service provider (CSP). Set hProv to zero to use the default CSP. If hProv is not zero, it must be a CSP handle created using CryptAcquireContext.

szSubsystemProtocol

[in] String naming a system store. Some example system stores are listed here:

"CA"

Certification authority certificates.

"MY"

A certificate store holding "My" certificates with their associated private keys.

"ROOT"

Root certificates.

"SPC"

Software publisher certificates.

Note: If the system store name provided in this parameter is not the name of an existing system store, a new system store will be created and used. CertEnumSystemStore can be used to list the names of existing system stores.

Return Values

If the function succeeds, the return value is a handle to the certificate store.

If the function fails, the return value is zero. For extended error information, call Win32::GetLastError().

Note: Errors from the called function CertOpenStore are propagated to this function.

Remarks

After the system store is opened, all the standard certificate store functions can be used to manipulate the certificates.

After use, the store should be closed by using CertCloseStore.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP3 and later.

Windows 95/98/Me: Included in Windows 95 OSR2 and later.

Redistributable: Requires Internet Explorer 3.02 or later on Windows NT 4.0.

CertRegisterPhysicalStore( pvSystemStore, dwFlags, pwszStoreName, pStoreInfo, pvReserved )

The CertRegisterPhysicalStore function adds a physical store to a registry system store collection.

    BOOL WINAPI CertRegisterPhysicalStore(
        const void *pvSystemStore,
        DWORD dwFlags,
        LPCWSTR pwszStoreName,
        PCERT_PHYSICAL_STORE_INFO pStoreInfo,
        void *pvReserved
    );
Parameters
pvSystemStore

in] System store collection to which the physical store is added. This parameter points either to a zero terminated Unicode string or to a CERT_SYSTEM_STORE_RELOCATE_PARA structure. For details on using the structure and on adding a ServiceName or ComputerName before the system store name string, see CertRegisterSystemStore.

dwFlags

[in] The high word of the dwFlags parameter specifies the location of the system store. For details on defined high-word flags and prepending ServiceName, UserNames, and ComputerNames to the system store name, see CertRegisterSystemStore.

The following low-word flags are also defined and can be combined with high-word flags using a bitwise-OR operation.

CERT_SYSTEM_STORE_RELOCATE_FLAG

The system store is not in its default registry location and the pvSystemStore parameter must be a pointer to a CERT_SYSTEM_STORE_RELOCATE_PARA structure.

CERT_STORE_CREATE_NEW_FLAG

The function fails if the physical store already exists in the store location.

pwszStoreName

[in] Pointer to a Unicode string naming the physical store to be added to the system store collection.

pStoreInfo

[in] Pointer to a CERT_PHYSICAL_STORE_INFO structure providing basic information about the physical store.

pvReserved

[in] Reserved for future use and must be set to zero.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To access a remote store, the security permissions in the registry keys on that remote computer must be set to allow access. For more information on setting security permissions in a Windows registry, see MSDN Article ID Q155363.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertRegisterSystemStore( pvSystemStore, dwFlags, pStoreInfo, pvReserved )

The CertRegisterSystemStore function registers a system store.

    BOOL WINAPI CertRegisterSystemStore(
        const void *pvSystemStore,
        DWORD dwFlags,
        PCERT_SYSTEM_STORE_INFO pStoreInfo,
        void *pvReserved
    );
Parameters
pvSystemStore

[in] Identifies the system store to be registered. If CERT_SYSTEM_STORE_RELOCATE_FLAG is set in the dwFlags parameter, pvSystemStore points to a CERT_SYSTEM_STORE_RELOCATE_PARA structure. Otherwise, it points to a zero terminated Unicode string naming the system store.

With appropriate settings in dwFlags, the identified store can be a system store on a remote local computer. Stores on remote computers can be registered with the computer name as a prefix to the name of the system store. For example, a remote local computer store can be registered with pvSystemStore pointing to the string "\\ComputerName\Trust" or "ComputerName\Trust".

Leading "\\" backslashes are optional before a ComputerName.

dwFlags

[in] The high word of the dwFlags parameter is used to specify the location of the system store. The following high-word values are defined.

CERT_SYSTEM_STORE_CURRENT_SERVICE

pvSystemStore can be a system store name that is prefixed with the ServiceName.

CERT_SYSTEM_STORE_CURRENT_USER

pvSystemStore can be a system store name that is prefixed with the UserName.

CERT_SYSTEM_STORE_LOCAL_MACHINE

pvSystemStore can be a system store that is on a remote computer.

CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY

pvSystemStore is a group policy store and can be on a remote computer.

CERT_SYSTEM_STORE_SERVICES

pvSystemStore must be a system store name prefixed with the ServiceName.

CERT_SYSTEM_STORE_USERS

pvSystemStore must be a system store name that is prefixed with the UserName.

Stores on remote computers can be registered for CERT_SYSTEM_STORE_LOCAL_MACHINE, CERT_SYSTEM_STORE_SERVICES, CERT_SYSTEM_STORE_USERS, or CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY.

The following low-word values are also defined and can be combined using a bitwise-OR operation with high-word values.

CERT_SYSTEM_STORE_RELOCATE_FLAG

The system store is not in its default register location and pvSystemStore must be a pointer to a CERT_SYSTEM_STORE_RELOCATE_PARA structure.

CERT_STORE_CREATE_NEW_FLAG

The function fails if the system store already exists in the store location.

pStoreInfo

[in] Reserved for future use and must be set to zero.

pvReserved

[in] Reserved for future use and must be set to zero.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To access a remote store, the security permissions in the registry keys on that remote computer must be set to allow access. For more information on setting security permissions in a Windows registry, see MSDN Article ID Q155363.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertRemoveStoreFromCollection( hCollectionStore, hSiblingStore )

The CertRemoveStoreFromCollection function removes a sibling certificate store from a collection store.

    void WINAPI CertRemoveStoreFromCollection(
        HCERTSTORE hCollectionStore,
        HCERTSTORE hSiblingStore
    );
Parameters
hCollectionStore

[in] Handle of the collection certificate store.

hSiblingStore

[in] Handle of the sibling certificate store to be removed from the collection store.

Return Values

None.

Remarks

None.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertSaveStore( hCertStore, dwMsgAndCertEncodingType, dwSaveAs, dwSaveTo, pvSaveToPara, dwFlags )

The CertSaveStore function saves the certificate store to a file or to a memory BLOB.

    BOOL WINAPI CertSaveStore(
        HCERTSTORE hCertStore,
        DWORD dwMsgAndCertEncodingType,
        DWORD dwSaveAs,
        DWORD dwSaveTo,
        void *pvSaveToPara,
        DWORD dwFlags
    );
Parameters
hCertStore

[in] Handle of the certificate store to be saved.

dwMsgAndCertEncodingType

[in] Specifies the certificate and message encoding types. Encoding is used only when dwSaveAs is CERT_STORE_SAVE_AS_PKCS7. Otherwise, the dwMsgAndCertEncodingType parameter is not used.

Note: When needed, both a certificate and message encoding type are required and are specified by combining them with a bitwise-OR operation, as shown in the following example:

    X509_ASN_ENCODING | PKCS_7_ASN_ENCODING
dwSaveAs

[in] Specifies whether the store can be saved as a serialized store containing properties in addition to encoded certificates, CRL, and CTLs (CERT_STORE_SAVE_AS_STORE), or as a PKCS #7 signed message that does not include additional properties (CERT_STORE_SAVE_AS_PKCS7).

Note that the CERT_KEY_CONTEXT_PROP_ID property and the related CERT_KEY_PROV_HANDLE_PROP_ID and CERT_KEY_SPEC_PROP_ID values are not saved to a serialized store.

The dwEncodingType parameter specifies the message encoding type when dwSaveAs is set to CERT_STORE_SAVE_AS_PKCS7.

dwSaveTo

[in] Along with the pvSaveToPara parameter, specifies where to save the store as follows.

When dwSaveTo is set to CERT_STORE_SAVE_TO_FILE, the function saves the store to the specified file. The file's handle is passed in the pvSaveToPara parameter. After a successful save operation, the file pointer is positioned after the last write operation.

When dwSaveTo is set to CERT_STORE_SAVE_TO_MEMORY, the function saves the store to the memory BLOB passed in pvSaveToPara. Before use, the memory BLOB's pbData and cbData members must be initialized. Upon return, cbData is updated with the actual length. For a length-only calculation, pbData must be set to zero. If <pbData> is not zero and cbData is not large enough, the function returns FALSE with a last error code of ERROR_MORE_DATA.

When dwSaveTo is set to CERT_STORE_SAVE_TO_FILENAME the function opens the file, saves to it, and closes it.

pvSaveToPara

[in/out] Pointer used to save the store. May be a file handle or a pointer to a MEMORY_BLOB structure.

dwFlags

[in] Reserved for future use and must be zero.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE. For extended error information, call Win32::GetLastError().

Note that CreateFile or WriteFile errors can be propagated to this function. One possible error code is CRYPT_E_FILE_ERROR which indicates that an error occurred while writing to the file.

Remarks

None.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP3 and later.

Windows 95/98/Me: Included in Windows 95 OSR2 and later.

Redistributable: Requires Internet Explorer 3.02 or later on Windows NT 4.0.

CertSetStoreProperty( hCertStore, dwPropId, dwFlags, pvData )

The CertSetStoreProperty function sets a store property.

    BOOL CertSetStoreProperty(
        HCERTSTORE hCertStore,
        DWORD dwPropId,
        DWORD dwFlags,
        const void *pvData
    );
Parameters
hCertStore

[in] Handle for the certificate store.

dwPropId

[in] Indicates one of a range of store properties. Values for user-defined properties must be outside the current range of predefined context property values. Currently, user-defined pwPropId values begin at 4,096. There is one predefined store property, CERT_STORE_LOCALIZED_NAME_PROP_ID, the localized name of the store.

dwFlags

[in] Reserved for future use and must be zero.

pvData

[in] The type definition for pvData depends on the dwPropId value. If dwPropId is CERT_STORE_LOCALIZED_NAME_PROP_ID, pvData points to a CRYPT_DATA_BLOB structure. The pbData member of that structure is a pointer to a zero terminated Unicode character string. The cbData member of that structure is a DWORD value holding the length of the string.

For user-defined dwPropId values, pvData is a pointer to an encoded PCRYPT_DATA_BLOB.

If a value already exists for the selected property, the old value is replaced.

Calling this function with pvData set to zero deletes a property.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

Store property identifiers are properties applicable to an entire store. They are not properties for an individual certificate, CRL, or CTL context. Currently, no store properties are persisted.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertUnregisterPhysicalStore( pvSystemStore, dwFlags, pwszStoreName )

The CertUnregisterPhysicalStore function removes a physical store from a specified system store collection. CertUnregisterPhysicalStore can also be used to delete the physical store.

    BOOL WINAPI CertUnregisterPhysicalStore(
        const void *pvSystemStore,
        DWORD dwFlags,
        LPCWSTR pwszStoreName
    );
Parameters
pvSystemStore

[in] Pointer to an identifier of the system store collection from which the physical store is to be removed. It is either to a zero terminated Unicode string or to a CERT_SYSTEM_STORE_RELOCATE_PARA structure. For details on using the structure and on prepending a ServiceName or ComputerName to the system store name string, see CertRegisterSystemStore.

dwFlags

[in] The high word of the dwFlags parameter specifies the location of the system store. For details on defined high-word flags and on prepending ServiceName, UserNames, and ComputerNames to the system store name, see CertRegisterSystemStore.

The following low-word values are also defined. They can be combined using bitwise-OR operations with high-word values.

CERT_SYSTEM_STORE_RELOCATE_FLAG

The system store is not in its default registry location and pvSystemStore must be a pointer to a CERT_SYSTEM_STORE_RELOCATE_PARA structure.

CERT_STORE_DELETE_FLAG

The physical store is first removed from the system store collection and is then deleted.

pwszStoreName

[in] zero terminated Unicode string naming the physical store.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To access a remote store, the security permissions in the registry keys on that remote computer must be set to allow access. For more information on setting security permissions in a Windows registry, see MSDSN Article ID Q155363.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CertUnregisterSystemStore( pvSystemStore, dwFlags )

The CertUnregisterSystemStore function unregisters a specified system store.

    BOOL WINAPI CertUnregisterSystemStore(
        const void *pvSystemStore,
        DWORD dwFlags
    );
Parameters
pvSystemStore

[in] Identifies the system store to be unregistered. It points either to a zero terminated Unicode string or to a CERT_SYSTEM_STORE_RELOCATE_PARA structure. For details on using the structure and on prepending a ServiceName or ComputerName to the system store name string, see CertRegisterSystemStore.

dwFlags

[in] The high word of the dwFlags parameter specifies the location of the system store. For details on defined high-word flags and on prepending ServiceName, UserNames, and ComputerNames to the system store name, see CertRegisterSystemStore.

The following low-word values are also defined and can be combined with high-word values using a bitwise-OR operation.

CERT_SYSTEM_STORE_RELOCATE_FLAG

The system store is not in its default registry location and pvSystemStore must be a pointer to a CERT_SYSTEM_STORE_RELOCATE_PARA structure.

CERT_STORE_DELETE_FLAG

The system store is deleted after it has been unregistered.

Return Values

If the function succeeds, the return value is TRUE.

If the function fails, the return value is FALSE.

Remarks

To access a remote store, the security permissions in the registry keys on that remote computer must be set to allow access. For more information on setting security permissions in a Windows registry, see MSDN Article ID Q155363.

Requirements

Windows NT/2000/XP: Included in Windows NT 4.0 SP4 and later.

Windows 95/98/Me: Unsupported.

CONSTANTS ^

Here is a overview over all available constants.

They can be imported to your namespace one by one, like

    use Win32::Crypt::API qw/ CERT_STORE_ADD_NEW CERT_STORE_PROV_FILENAME /;

or all at once

    use Win32::Crypt::API ':consts';

If you do not like to pollute your own namespace, you can call any constant

    Win32::Crypt::API::CERT_STORE_ADD_USE_EXISTING

as usual.

APPENDIX ^

Cryptographic Service Provider Contexts

The first CryptoAPI function called by an application that uses any cryptographic APIs is the CryptAcquireContext function. This function returns a handle to a particular CSP which includes the specification of a particular key container within the CSP. This key container is either a specifically requested key container or it is the default key container for the currently logged-on user.

CryptAcquireContext can also create a new key container.

A cryptographic service provider (CSP) has both a name and a type. For example, the name of one of the CSPs currently shipped with the operating system is Microsoft Base Cryptographic Provider. It is an PROV_RSA_FULL type provider. The name of each provider is unique; the provider type is not.

When an application calls CryptAcquireContext to obtain a CSP handle, it specifies a provider type and, optionally, a provider name. If both a type and a name are specified, the function loads the CSP with the matching provider type and provider name. The function returns the CSP's handle which provides access to both the CSP and to a key container within the CSP.

When an application calls CryptAcquireContext and specifies a provider type but no provider name, the function looks for a named provider, first checking a list of default named providers associated with the logged-on user and, if that fails, from a list of default named providers associated with the computer. After the provider name has been determined, the CryptAcquireContext function searches for the CSP for that provider, loads it, and returns its handle.

Cryptographic Provider Names

The following cryptographic service provider (CSP) names are defined: These constants are used with the CryptAcquireContext and CryptSetProvider functions.

MS_DEF_PROV

"Microsoft Base Cryptographic Provider v1.0"

MS_ENHANCED_PROV

"Microsoft Enhanced Cryptographic Provider "

MS_STRONG_PROV

"Microsoft Strong Cryptographic Provider"

MS_DEF_RSA_SIG_PROV

"Microsoft RSA Signature Cryptographic Provider"

MS_DEF_RSA_SCHANNEL_PROV

"Microsoft RSA SChannel Cryptographic Provider"

MS_DEF_DSS_PROV

"Microsoft Base DSS Cryptographic Provider"

MS_DEF_DSS_DH_PROV

"Microsoft Base DSS and Diffie-Hellman Cryptographic Provider"

MS_ENH_DSS_DH_PROV

"Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider"

MS_DEF_DH_SCHANNEL_PROV

"Microsoft DH SChannel Cryptographic Provider"

MS_SCARD_PROV

"Microsoft Base Smart Card Cryptographic Provider"

Cryptographic Provider Types

The field of cryptography is large and growing. There are many different standard data formats and protocols. These are generally organized into groups or families, each of which has its own set of data formats and way of doing things. Even if two families use the same algorithm (for example, the RC2 block cipher), they will often use different padding schemes, different key lengths, and different default modes. CryptoAPI is designed so that a CSP provider type represents a particular family.

When an application connects to a CSP of a particular type, each of the CryptoAPI functions will, by default, operate in a way prescribed by the family that corresponds to that CSP type. An application's choice of provider type specifies the following items:

Key exchange algorithm

Each provider type specifies one and only one key exchange algorithm. Every CSP of a particular type must implement this algorithm. Applications specify the key exchange algorithm to use by selecting a CSP of the appropriate provider type.

Digital signature algorithm

Each provider type specifies one and only one digital signature algorithm. Every CSP of a particular type must implement this algorithm. Applications specify the digital signature algorithm to use by selecting a CSP of the appropriate provider type.

Key BLOB formats

The provide type determines the format of the key BLOB used to export keys from the CSP and to import keys into a CSP.

Digital signature format

The provider type determines the digital signature format. This ensures that a signature produced by a CSP of a given provider type can be verified by any CSP of the same provider type.

Session key derivation scheme

The provider type determines the method used to derived a session key from a hash.

Key length

Some provider types specify the length of public/private key pairs and the session keys.

Default modes

The provider type often specifies default modes for various options, such as the block encryption cipher mode or the block encryption padding method.

Some advanced application might connect to more than one CSP at a time, but most application generally use only a single CSP.

There are currently a number of predefined provider types. The next sections provide information on the following provider types:

Even though some CSP types might be partially compatible with others, two or more applications that need to exchange keys and encrypted messages should use CSPs of the same type.

A custom CSP writer can define a new provider type. However, the CSP writer is then responsible for distributing the new provider type to the authors of any applications that are to use it.

Retrieving Data of Unknown Length

Many functions return a potentially large amount of data to an address provided as one of the parameters by the application program. In all these cases, the operation is performed in a similar, if not identical, fashion. The parameter that points to the location of the returned data will use the notation convention where "pb" or "pv" are the first two characters of the parameter name. Another parameter will have "pcb" as the first three characters of the parameter name. This parameter represents the size, in bytes, of the data that will be returned to the "pb" or "pv" location. For example, consider the following function specification:

    BOOL WINAPI SomeFunction(
        PCCRL_CONTEXT pCrlContext,  // in
        DWORD dwPropId,             // in
        BYTE *pbData,               // out
        DWORD *pcbData              // in/out
    );

In this example pbData is a pointer to the location where the data will be returned, and pcbData is the size, in bytes, of the returned data.

Note: The companion parameter to the "pcb" parameter may sometimes carry a slightly different prefix, such as "p" or "pv". Also, for companion parameters using the combination of prefixes "pwsz" and "pcch", the "pcch" parameter is the count in characters (Unicode or ASCII, as applicable), of the returned data.

If the buffer specified by pbData parameter is not large enough to hold the returned data, the function sets the ERROR_MORE_DATA code (which can be seen by calling Win32::GetLastError()), and stores the required buffer size, in *bytes, into the variable pointed to by pcbData.

If zero is input for pbData and pcbData is non-zero, no error is returned and the function returns the size of the needed memory buffer, in bytes, in the variable pointed to by pcbData. This lets an application determine the size of, and the best way to allocate, a buffer for the returned data.

Note: When zero is input for pbData to determine the size needed to ensure that the returned data fits in the specified buffer, the second call to the function (which populates the buffer with the desired data) may not use the whole buffer. After the second call, the actual size of the data returned is contained in pcbData. Use this size when processing the data.

The following example code demonstrates how input and output parameters might be implemented for this purpose:

    #!/usr/bin/perl

    use strict;
    use Win32::Crypt ':consts';

    use constant MY_ENCODING_TYPE => (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING);

    # Set up SomeFunction variables.
    my $pCrlContext; # Initialized elsewhere
    my $dwPropId;    # Initialized elsewhere
    my $cbData;
    my $pbData;

    # Call SomeFunction to set cbData, the size of
    # the buffer needed for pbData.

    if(SomeFunction($pCrlContext, $dwPropId, 0, $cbData)) {
        print "The function succeeded.\n";
    } else {
        # The function call failed. Handle the error.
        HandleError("Function call failed.");
    }

    # The call succeeded; the size for the needed buffer, in bytes,
    # now resides in cbData.

    # Malloc memory for the size of the message.

    $pbData = "\0" x $cbData;

    # The space for the buffer has been allocated.
    # Call SomeFunction to fill the buffer with the data.

    if(SomeFunction($pCrlContext, $dwPropId, $pbData, $cbData)) {
        print "The function succeeded.\n";
    } else {
        # The function call failed. Handle the error.
        HandleError("Function call failed.");
    }

    # The function succeeded; the data is now in the buffer
    # pointed to by pbData. Note that $cbData is
    # updated with the actual size of the data returned. Use this size
    # to process bytes of $pbData.



    # This example uses the function HandleError, a simple error
    # handling function, to print an error message to the standard error
    # (STDERR) file and exit the program.
    # For most applications, replace this function with one
    # that does more extensive error reporting.
    sub HandleError {
        require Win32;

        print STDERR "An error occurred in running the program.\n";
        print STDERR $_[0], "\n";
        print STDERR sprintf("Error number %x.\n", Win32::GetLastError());
        print STDERR "Program terminating.\n";
        exit 1;
    }

An Alternate Procedure

A performance gain may be realized in dealing with in/out parameters by preallocating a buffer for the returned "pb" data without querying the function involved for the exact size "cb" needed. When the preallocated buffer is at least as big as the "cb" required, a performance savings is realized because the function is only called once, producing the returned data placed in the "pb" specified buffer. If the preallocated buffer is not large enough to hold the data, then the function fails and there is no performance gain.

The following example code demonstrates how a preallocated buffer can be used to provide a performance gain:

    # Assume SomeFunction (from the previous example) is called
    # repetitively by an application, and that a buffer size of
    # 50 bytes will handle the output for all but a few cases.

    # Set up SomeFunction variables.

    my $pCrlContext; # Initialized elsewhere.
    my $dwPropId;    # Initialized elsewhere.

    # Preallocate a 50 byte buffer, and
    # use that buffer in a call to SomeFunction that produces the
    # desired output data most of the time.
    # However, the case where more than 50 bytes are required for the
    # output data must be handled as well. For that case, use the cb
    # returned by the failed call to SomeFunction to allocate a bigger
    # buffer.
    # After the allocation of additional bytes for the buffer, a second
    # call to SomeFunction using the larger buffer is then made.

    # Assume variables $pCrlContext and $dwPropId have been declared and
    # initialized elsewhere.

    my $dwTries = 0;    # the number of times the function has been tried
    my $fMore=1;        # flag indicating the function needs to be tried
    my $cbData = 50;
    my $pbData;

    # Begin processing. This loop is executed at most twice.

    while($fMore) {
        $pbdata = "\0" x $cbData;

        # Memory has been allocated. Try the function.

        if(SomeFunction($pCrlContext, $dwPropId, $pbData, $cbData)) {
            # The function succeeded. Exit the loop.

            print "The function succeeded. Exit the loop.\n";
            $fMore = 0;
        }
        else
        {
            require Win32;

            # If the error was not that the buffer was not big enough,
            # exit the loop having failed.

            if(Win32::GetLastError() != ERROR_MORE_DATA)
            {
                HandleError("General function failure.");
            }
            # If the error was that there was that there was not enough
            # space in the buffer, try a second but not a third time.
            if( ++$dwtries > 1 )
            {
                HandleError("Function call failed twice ");
            }
        }
    }  // ends loop

    # If the loop runs to completion, the function succeeded either
    # the first or the second time through. In either case, cbData is
    # updated with the actual size of the data returned.
    # Use this size when processing $pbData.

    # Process $pbData here as needed.

SEE ALSO ^

Project Page: http://sourceforge.net/projects/perlwin32crypt/

MSDN Home Page: http://msdn.mircosoft.com/

AUTHOR ^

Sascha Kiefer, esskar@cpan.org

COPYRIGHT AND LICENSE ^

Copyright (C) 2006 Sascha Kiefer

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

syntax highlighting: