PUCHAR
AdvPKIEntityCreateSelfSignedCertEncoding
    (
        ANSC_HANDLE                 hThisObject,
        BOOLEAN                     bHasKeyIdentifier,
        PULONG                      pLength
    )
{
    PPKI_CLIENT_ENTITY              pThisObject  = (PPKI_CLIENT_ENTITY)hThisObject;
    PANSC_ASN1_OBJECT               pCert;
    PUCHAR                          pEncoding;

    if( hThisObject == NULL || pLength == NULL)
    {
        return NULL;
    }

    pCert = (PANSC_ASN1_OBJECT)pThisObject->CreateSelfSignedCert(pThisObject,bHasKeyIdentifier);

    if( pCert == NULL)
    {
        return NULL;
    }

    pEncoding =  pCert->GetEncodedData(pCert, pLength);

    pCert->AsnFree(pCert);

    return pEncoding;

}
ANSC_HANDLE
AdvPKIEntityExportPKCS12Handle
    (
        ANSC_HANDLE                 hThisObject,
        PCHAR                       pPassword,
        BOOLEAN                     bExportCA
    )
{
    PPKI_CLIENT_ENTITY              pThisObject  = (PPKI_CLIENT_ENTITY)hThisObject;
    PANSC_ASN1_PFX                  pPKCS12      = NULL;
    PANSC_ASN1_OBJECT               pCert;
    PSINGLE_LINK_ENTRY              pSListEntry;
    PUCHAR                          pEncoding,pKeyEncoding;
    ULONG                           length, keyLength;

    /* create the pkcs12 object */
    pPKCS12 = (PANSC_ASN1_PFX)AnscAsn1CreatePFX(NULL);

    if( pPKCS12 == NULL)
    {
        return NULL;
    }

    if( bExportCA)
    {
        /* export the CA one by one */
        pSListEntry =   AnscSListGetFirstEntry(&pThisObject->sCAList);

        while( pSListEntry != NULL)
        {
            pCert      = ACCESS_ANSC_ASN1_OBJECT(pSListEntry);
            pSListEntry = AnscSListGetNextEntry(pSListEntry);

            if( pCert != NULL)
            {
                pEncoding = pCert->GetEncodedData(pCert, &length);

                if( pEncoding != NULL)
                {
                    pPKCS12->AddCertificate
                        (
                            pPKCS12,
                            pEncoding,
                            length
                        );

                    AnscFreeMemory(pPKCS12);
                }
            }              
        }
    }

    /* export the user's certificate */
    if( pThisObject->ExportInfo
            (
                pThisObject,
                &pEncoding,
                &length,
                &pKeyEncoding,
                &keyLength
            ) == ANSC_STATUS_SUCCESS
       )
    {
        pPKCS12->AddCertAndKeyInfo(pPKCS12, pEncoding, length, pKeyEncoding, keyLength);

        if( pEncoding != NULL)
        {
            AnscFreeMemory(pEncoding);
        }

        if( pKeyEncoding != NULL)
        {
            AnscFreeMemory(pKeyEncoding);
        }
    }

    /* encrypt it */
    pPKCS12->EncryptAndSign
         (
            pPKCS12,
            pThisObject->pUtilityApi,
            pPassword
         );

    return pPKCS12;
}