7¤0ìõj%.J˜CãÀÀŠ†‚Båƒ†���At$P§;]·ñ[¤ÿH7nÛßk	a¶ý³�ßÝèãs b ÿíßÛfÿQi(ë*=÷Ø3 
‰L&”Œã €"™“P%òx,”9)
BÆc1Æd"  4V—™d
                   IsSigned - see if message contains a signed submessage
 *
 * If the CMS message has a SignedData with a signature (not just a SignedData)
 * return true; false otherwise.  This can/should be called before calling
 * VerifySignature, which will always indicate failure if no signature is
 * present, but that does not mean there even was a signature!
 * Note that the content itself can be empty (detached coECCurve_SECG_CHAR2_113R1 */
    /* ECCurve_WTLS_5 == ECCurve_X9_62_CHAR2_PNB163V1 */
    /* ECCurve_WTLS_6 == ECCurve_SECG_PRIME_112R1 */
    /* ECCurve_WTLS_7 == ECCurve_SECG_PRIME_160R1 */
    ECCurve_WTLS_8, /* not supported */
    ECCurve_WTLS_9, /* not supported */
    /* ECCurve_WTLS_10 == ECCurve_NIST_K233 */
    /* ECCurve_WTLS_11 == ECCurve_NIST_B233 */
    /* ECCurve_WTLS_12 == ECCurve_NIST_P224 */

    ECCurve25519,
    ECCurve_Ed25519,

    ECCurve_pastLastCurve
} ECCurveName;

/* Aliased named curves */

#define ECCurvLONG ulSeedLen          /* length of seed material */
);
#endif

/* C_GenerateRandom generates random data. */
CK_PKCS11_FUNCTION_INFO(C_GenerateRandom)
#ifdef CK_NEED_ARG_LIST
(
    CK_SESSION_HANDLE hSession, /* the session's handle */
    CK_BYTE_PTR RandomData,     /* receives the random data */
    CK_ULONG ulRandomLen        /* # of bytes to generate */
);
#endif

/* Parallel function management */

/* C_GetFunctionStatus is a legacy function; it obtains an
 * updated status of a function running in parallel with an
 * applic* the data to sign */
    CK_ULONG ulDataLen,          /* count of bytes to sign */
    CK_BYTE_PTR pSignature,      /* gets the signature */
    CK_ULONG_PTR pulSignatureLen /* gets signature length */
);
#endif

/* Verifying signatures and MACs */

/* C_VerifyInit initializes a verification operation, where the
 * signature is an appendix to the data, and plaintext cannot
 *  cannot be recovered from the signature (e.g. DSA). */
CK_PKCS11_FUNCTION_INFO(C_VerifyInit)
#ifdef CK_NEED_ARG_LIST
(
    CK_SESSION_HANDLE hSession,  /* th   /* handle of encryption key */
);
#endif

/* C_Encrypt encrypts single-part data. */
CK_PKCS11_FUNCTION_INFO(C_Encrypt)
#ifdef CK_NEED_ARG_LIST
(
    CK_SESSION_HANDLE hSession,      /* session's handle */
    CK_BYTE_PTR pData,               /* the plaintext data */
    CK_ULONG ulDataLen,              /* bytes of plaintext */
    CK_BYTE_PTR pEncryptedData,      /* gets ciphertext */
    CK_ULONG_PTR pulEncryptedDataLen /* gets c-text size */
);
#endif

/* C_EncryptUpdate continues a multiple-part encryption
 * operation. */
C/* the SO's initial PIN */
    CK_ULONG ulPinLen,     /* length in bytes of the PIN */
    CK_UTF8CHAR_PTR pLabel /* 32-byte token label (blank padded) */
);
#endif

/* C_InitPIN initializes the normal user's PIN. */
CK_PKCS11_FUNCTION_INFO(C_InitPIN)
#ifdef CK_NEED_ARG_LIST
(
    CK_SESSION_HANDLE hSession, /* the session's handle */
    CK_UTF8CHAR_PTR pPin,       /* the normal user's PIN */
    CK_ULONG ulPinLen           /* length in bytes of the PIN */
);
#endif

/* C_SetPIN modifies the PIN of the user who is logged in. */
CK here:
     *
     *  EncryptInit,
     *  DecryptInit,
     *  DigestInit,
     *  SignInit,
     *  SignRecoverInit;
     *  VerifyInit,
     *  VerifyRecoverInit;
     *
     * The key-management routines are
     *
     *  GenerateKey
     *  GenerateKeyPair
     *  WrapKey
     *  UnwrapKey
     *  DeriveKey
     *
     * All of these routines based on the Cryptoki API;
     * see PKCS#11 for further information.
     */

    /*
     */
    NSSCKMDCryptoOperation *(PR_CALLBACK *EncryptInit)(
        NSSCKMDMechanism *mdMechani const NSSItem *inputBuffer,
        NSSItem *outputBuffer);

    /*
     * This routine is called by the Framework to complete the
     * next step in a signing/verification/digest operation.
     * This routine is optional; if unimplemented, the respective
     * update call with fail with CKR_FUNCTION_FAILED
     * Update should not be implemented for encryption/decryption
     * mechanisms.
     */
    CK_RV(PR_CALLBACK *DigestUpdate)
    (
        NSSCKMDCryptoOperation *mdCryptoOperation,
        NSSCKFWCryptoOperation *fwCryy if the Module does not handle session
     * objects, and if none of its tokens have token objects.  The
     * NSSCKFWFindObjects pointer has an NSSArena that may be used for
     * storage for the life of this "find" operation.  This routine may
     * return NULL upon error.  If the Module can determine immediately
     * that the search will not find any matching objects, it may return
     * NULL, and specify CKR_OK as the error.
     */
    NSSCKMDFindObjects *(PR_CALLBACK *FindObjectsInit)(
        NSSCKMDSession *mdSessioance *fwInstance,
        CK_MECHANISM_TYPE which,
        CK_RV *pError);

    /*
     * This object may be extended in future versions of the
     * NSS Cryptoki Framework.  To allow for some flexibility
     * in the area of binary compatibility, this field should
     * be NULL.
     */
    void *null;
};

/*
 * NSSCKMDSession
 *
 * This is the basic handle for a session on a PKCS#11 Token.  It
 * is created by NSSCKMDToken->OpenSession, and may be obtained
 * from the Framework's corresponding NSSCKFWSession object.  It
 * conRUE if the normal user's PIN on this
     * token has been initialised.  This routine is optional; if
     * unimplemented, CK_FALSE is assumed.
     */
    CK_BBOOL(PR_CALLBACK *GetUserPinInitialized)
    (
        NSSCKMDToken *mdToken,
        NSSCKFWToken *fwToken,
        NSSCKMDInstance *mdInstance,
        NSSCKFWInstance *fwInstance);

    /*
     * This routine returns CK_TRUE if a successful save of a
     * session's cryptographic operations state ~always~ contains
     * all keys needed to restore the state of the sessi sixty-four bytes are
     * significant.  This routine is optional.  The string
     * returned is never freed; if dynamically generated,
     * the space for it should be allocated from the NSSArena
     * that may be obtained from the NSSCKFWInstance.  This
     * routine may return NULL upon error; however if *pError
     * is CKR_OK, the NULL will be considered the valid response.
     */
    NSSUTF8 *(PR_CALLBACK *GetSlotDescription)(
        NSSCKMDSlot *mdSlot,
        NSSCKFWSlot *fwSlot,
        NSSCKMDInstance *mdInstancct.
 * It contains a pointer for use by the Module, to store any
 * instance-related data, and it contains the EPV for a set of
 * routines which the Module may implement for use by the Framework.
 * Some of these routines are optional; others are mandatory.
 */

struct NSSCKMDInstanceStr {
    /*
     * The Module may use this pointer for its own purposes.
     */
    void *etc;

    /*
     * This routine is called by the Framework to initialize
     * the Module.  This routine is optional; if unimplemented,
     * it won't be caROR_RX_MALFORMED_NEW_SESSION_TICKET = (SSL_ERROR_BASE + 110),

    SSL_ERROR_DECOMPRESSION_FAILURE         = (SSL_ERROR_BASE + 111),
    SSL_ERROR_RENEGOTIATION_NOT_ALLOWED     = (SSL_ERROR_BASE + 112),
    SSL_ERROR_UNSAFE_NEGOTIATION            = (SSL_ERROR_BASE + 113),

    SSL_ERROR_RX_UNEXPECTED_UNCOMPRESSED_RECORD = (SSL_ERROR_BASE + 114),

    SSL_ERROR_WEAK_SERVER_EPHEMERAL_DH_KEY  = (SSL_ERROR_BASE + 115),

    SSL_ERROR_NEXT_PROTOCOL_DATA_INVALID    = (SSL_ERROR_BASE + 116),

    SSL_ERROR_FEATURE_NOT_SUPPORTED_FOR_SSL2 =R_BASE + 18),
    SSL_ERROR_EXPIRED_CERT_ALERT            = (SSL_ERROR_BASE + 19),

    SSL_ERROR_SSL_DISABLED                  = (SSL_ERROR_BASE + 20),
    SSL_ERROR_FORTEZZA_PQG                  = (SSL_ERROR_BASE + 21),
                                            /* error 21 is obsolete */
    SSL_ERROR_UNKNOWN_CIPHER_SUITE          = (SSL_ERROR_BASE + 22),
    SSL_ERROR_NO_CIPHERS_SUPPORTED          = (SSL_ERROR_BASE + 23),
    SSL_ERROR_BAD_BLOCK_PADDING             = (SSL_ERROR_BASE + 24),
    SSL_ERROR_RX_RECORD_TOO_LONG     ndle
 *    certificate DB of the cert that is being checked
 *  CERTOCSPResponse *response
 *    the OCSP response we want to retrieve status from.
 *  CERTOCSPCertID *certID
 *    the ID we want to look for from the response.
 *  CERTCertificate *signerCert
 *    the certificate that was used to sign the OCSP response.
 *    must be obtained via a call to CERT_VerifyOCSPResponseSignature.
 *  PRTime time
 *    The time at which we're checking the status for.
 *  PRBool *certIDWasConsumed
 *    In and Out parameter.
 *    If certIDhod.h
 *
 * RevocationMethod Object
 *
 */

#ifndef _PKIX_REVOCATIONMETHOD_H
#define _PKIX_REVOCATIONMETHOD_H

#include "pkixt.h"
#include "pkix_revocationchecker.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct pkix_RevocationMethodStruct pkix_RevocationMethod;

/* Local revocation check function prototype definition.
 * Revocation methods capable of checking revocation though local
 * means(cache) should implement this prototype. */
typedef PKIX_Error *
pkix_LocalRevocationCheckFn(PKIX_PL_Cert *cert, PKIX_PL_Cert *issueificate |cert| will have its
 * revocation status checked via OCSP according to the global OCSP settings.
 *
 * OCSP checking is always skipped when certUsage is certUsageStatusResponder.
 */
#define CERT_VERIFYCERT_SKIP_OCSP 1

/* Interface function for libpkix cert validation engine:
 * cert_verify wrapper. */
SECStatus cert_VerifyCertChainPkix(CERTCertificate* cert, PRBool checkSig,
                                   SECCertUsage requiredUsage, PRTime time,
                                   void* wincx, CERTVerifyLog* log,
       ERRMACRO(CERTSELECTOR), \
   ERRMACRO(CERTSTORE), \
   ERRMACRO(CERTVFYPKIX), \
   ERRMACRO(COLLECTIONCERTSTORECONTEXT), \
   ERRMACRO(COMCERTSELPARAMS), \
   ERRMACRO(COMCRLSELPARAMS), \
   ERRMACRO(CONTEXT), \
   ERRMACRO(CRL), \
   ERRMACRO(CRLDP), \
   ERRMACRO(CRLENTRY), \
   ERRMACRO(CRLSELECTOR), \
   ERRMACRO(CRLCHECKER), \
   ERRMACRO(DATE), \
   ERRMACRO(EKUCHECKER), \
   ERRMACRO(ERROR), \
   ERRMACRO(FATAL), \
   ERRMACRO(FORWARDBUILDERSTATE), \
   ERRMACRO(GENERALNAME), \
   ERRMACRO(HASHTABLE), \
   ERRMACRO(HTTPCE(OCSPREQUEST), \
    TYPEMACRO(OCSPRESPONSE), \
    TYPEMACRO(OID), \
    TYPEMACRO(REVOCATIONCHECKER), \
    TYPEMACRO(PROCESSINGPARAMS), \
    TYPEMACRO(PUBLICKEY), \
    TYPEMACRO(RESOURCELIMITS), \
    TYPEMACRO(RWLOCK), \
    TYPEMACRO(SIGNATURECHECKERSTATE), \
    TYPEMACRO(SOCKET), \
    TYPEMACRO(STRING), \
    TYPEMACRO(TARGETCERTCHECKERSTATE), \
    TYPEMACRO(TRUSTANCHOR), \
    TYPEMACRO(VALIDATEPARAMS), \
    TYPEMACRO(VALIDATERESULT), \
    TYPEMACRO(VERIFYNODE), \
    TYPEMACRO(X500NAME)

#define TYPEMACRO(type) PKIX_eateByHostAndPort(
        PKIX_Boolean isServer,
        PRIntervalTime timeout,
        char *hostname,
        PRUint16 portnum,
        PRErrorCode *pStatus,
        PKIX_PL_Socket **pSocket,
        void *plContext);

/* Do not use these functions directly; use their callback variants instead
 *      static PKIX_Error *
 *      pkix_pl_Socket_Listen(
 *              PKIX_PL_Socket *socket,
 *              PKIX_UInt32 backlog,
 *              void *plContext);
 *      
 *      static PKIX_Error *
 *      pkix_pl_Socket_Accept(
h
 * (corresponding to a particular certificate in the chain).
 * PKIX_ValidateResult_GetPolicyTree returns the root node of the valid policy
 * tree. Other nodes can be accessed using the getChildren and getParents
 * functions, and individual elements of a node can be accessed with the
 * appropriate gettors. Once created, a PolicyNode is immutable.
 */

/*
 * FUNCTION: PKIX_PolicyNode_GetChildren
 * DESCRIPTION:
 *
 *  Retrieves the List of PolicyNodes representing the child nodes of the
 *  Policy Node pointed to by "node" and Slot *
nssSlotList_GetBestSlotForAlgorithmsAndParameters(
    nssSlotList *slotList,
    NSSAlgorithmAndParameters **ap);

NSS_EXTERN PRBool
nssToken_IsPresent(
    NSSToken *token);

NSS_EXTERN nssSession *
nssToken_GetDefaultSession(
    NSSToken *token);

NSS_EXTERN PRStatus
nssToken_GetTrustOrder(
    NSSToken *tok);

NSS_EXTERN PRStatus
nssToken_NotifyCertsNotVisible(
    NSSToken *tok);

NSS_EXTERN PRStatus
nssToken_TraverseCertificates(
    NSSToken *token,
    nssSession *sessionOpt,
    nssTokenSearchType searchType,
    PSUTF8 *tokenName);

NSS_EXTERN PRInt32
nssModule_GetCertOrder(
    NSSModule *module);

/* NSSSlot
 *
 * nssSlot_Destroy
 * nssSlot_AddRef
 * nssSlot_GetName
 * nssSlot_IsTokenPresent
 * nssSlot_IsPermanent
 * nssSlot_IsFriendly
 * nssSlot_IsHardware
 * nssSlot_Refresh
 * nssSlot_GetModule
 * nssSlot_GetToken
 * nssSlot_Login
 * nssSlot_Logout
 * nssSlot_SetPassword
 * nssSlot_CreateSession
 */

NSS_EXTERN PRStatus
nssSlot_Destroy(
    NSSSlot *slot);

NSS_EXTERN NSSSlot *
nssSlot_AddRef(
    NSSSlot *slot);

NSS_EXTERN void
nssSloplate)

const SEC_ASN1Template SEC_UTF8StringTemplate[] = {
    { SEC_ASN1_UTF8_STRING | SEC_ASN1_MAY_STREAM, 0, NULL, sizeof(SECItem) }
};

SEC_ASN1_CHOOSER_IMPLEMENT(SEC_UTF8StringTemplate)

/* XXX See comment below about SGN_DecodeDigestInfo -- keep this static! */
/* XXX Changed from static -- need to change name? */
const SEC_ASN1Template sgn_DigestInfoTemplate[] = {
    { SEC_ASN1_SEQUENCE,
      0, NULL, sizeof(SGNDigestInfo) },
    { SEC_ASN1_INLINE,
      offsetof(SGNDigestInfo, digestAlgorithm),
      SECOID_AlgorithmIDTeis set, the key is extractable
 * and can be wrapped.  If the PK11_ATTR_UNEXTRACTABLE flag is set,
 * the key is not extractable, and certain attributes of the key
 * cannot be revealed in plaintext outside the token (just like a
 * sensitive key).  If neither flag is set, it is token-specific
 * whether the key is extractable or not.
 *
 * These two flags specify the value of the PKCS #11 CKA_EXTRACTABLE
 * attribute.
 */
#define PK11_ATTR_EXTRACTABLE 0x00000100L
#define PK11_ATTR_UNEXTRACTABLE 0x00000200L

/* Cryptographic moduleken insertion and removal events.
 * SECMOD_END_WAIT - SECMOD_CancelWait has been called while the module is
 *  waiting in SECMOD_WaitForAnyTokenEvent. SECMOD_WaitForAnyTokenEvent
 *  should return immediately to it's caller.
 */
#define SECMOD_END_WAIT 0x01
#define SECMOD_WAIT_SIMULATED_EVENT 0x02
#define SECMOD_WAIT_PKCS11_EVENT 0x04

struct SECMODModuleListStr {
    SECMODModuleList *next;
    SECMODModule *module;
};

struct PK11SlotListStr {
    PK11SlotListElement *head;
    PK11SlotListElement *tail;
    PZLock *lock;
};

sruct pkix_ClassTable_EntryStruct {
        char *description;
        PKIX_UInt32 objCounter;
        PKIX_UInt32 typeObjectSize;
        PKIX_PL_DestructorCallback destructor;
        PKIX_PL_EqualsCallback equalsFunction;
        PKIX_PL_HashcodeCallback hashcodeFunction;
        PKIX_PL_ToStringCallback toStringFunction;
        PKIX_PL_ComparatorCallback comparator;
        PKIX_PL_DuplicateCallback duplicateFunction;
};

/*
 * PKIX_ERRORCLASSNAMES is an array of strings, with each string holding a
 * descriptive name for an erESPONSE_DEBUG_ARG(expr, arg) \
        PKIX_DEBUG_ARG(expr, arg)
#else
#define PKIX_OCSPRESPONSE_DEBUG(expr)
#define PKIX_OCSPRESPONSE_DEBUG_ARG(expr, arg)
#endif

#if PKIX_HTTPDEFAULTCLIENTDEBUG
#define PKIX_HTTPDEFAULTCLIENT_DEBUG(expr) \
        PKIX_DEBUG(expr)
#define PKIX_HTTPDEFAULTCLIENT_DEBUG_ARG(expr, arg) \
        PKIX_DEBUG_ARG(expr, arg)
#else
#define PKIX_HTTPDEFAULTCLIENT_DEBUG(expr)
#define PKIX_HTTPDEFAULTCLIENT_DEBUG_ARG(expr, arg)
#endif

#if PKIX_HTTPCERTSTORECONTEXTDEBUG
#define PKIX_HTTPCERTSTORECONTEXT_DEBUGX_CERTNAMECONSTRAINTSCHECKERSTATE_DEBUG_ARG(expr, arg)
#endif

#if PKIX_SUBJALTNAMECHECKERSTATEDEBUG
#define PKIX_SUBJALTNAMECHECKERSTATE_DEBUG(expr) \
        PKIX_DEBUG(expr)
#define PKIX_SUBJALTNAMECHECKERSTATE_DEBUG_ARG(expr, arg) \
        PKIX_DEBUG_ARG(expr, arg)
#else
#define PKIX_SUBJALTNAMECHECKERSTATE_DEBUG(expr)
#define PKIX_SUBJALTNAMECHECKERSTATE_DEBUG_ARG(expr, arg)
#endif

#if PKIX_CERTPOLICYQUALIFIERDEBUG
#define PKIX_CERTPOLICYQUALIFIER_DEBUG(expr) \
        PKIX_DEBUG(expr)
#define PKIX_CERTPOLICYQUALIFIER_DEBUG_lse
#define PKIX_DEBUG(expr)
#endif

/* Logging doesn't support DEBUG with ARG: cannot convert control and arg */
#define PKIX_DEBUG_ARG(expr, arg) \
    do { \
	(void) printf("(%s: ", myFuncName); \
	(void) printf(expr, arg); \
    } while (0)

#if PKIX_FATALDEBUG
#define PKIX_FATAL_DEBUG(expr) \
        PKIX_DEBUG(expr)
#define PKIX_FATAL_DEBUG_ARG(expr, arg) \
        PKIX_DEBUG_ARG(expr, arg)
#else
#define PKIX_FATAL_DEBUG(expr)
#define PKIX_FATAL_DEBUG_ARG(expr, arg)
#endif

#if PKIX_REFCOUNTDEBUG
#define PKIX_REF_COUNT_DEBUG(e PKIX_CHECK_ONLY_FATAL(func, descNum) \
    do { \
	pkixTempErrorReceived = PKIX_FALSE; \
	pkixErrorResult = (func); \
	if (pkixErrorResult) { \
            TRACE_CHECK_FAILURE((func), PKIX_ErrorText[descNum]) \
	    pkixTempErrorReceived = PKIX_TRUE; \
	    pkixErrorClass = pkixErrorResult->errClass; \
            if (pkixErrorClass == PKIX_FATAL_ERROR) { \
	         goto cleanup; \
	    } \
	    PKIX_DECREF(pkixErrorResult); \
	} \
    } while (0)

#define PKIX_LOG_ERROR(descNum) \
    _PKIX_LOG_ERROR(descNum, PKIX_LOGGER_LEVEL_ived;
    PKIX_ERRORCLASS    aPkixErrorClass;
    PKIX_UInt32        aPkixType;
    PKIX_PL_Object    *aLockedObject;
    PKIX_List         *aPkixErrorList;
} PKIX_StdVars;

#ifdef PKIX_STDVARS_POINTER
#define myFuncName                  stdVars->aMyFuncName
#define pkixErrorResult             stdVars->aPkixErrorResult
#define pkixTempResult              stdVars->aPkixTempResult
#define pkixReturnResult            stdVars->aPkixReturnResult
#define pkixErrorCode               stdVars->aPkixErrorCode
#define pkixErrorReceived       TION_DEL 2
#define SECMOD_MODULE_DB_FUNCTION_RELEASE 3
typedef char **(PR_CALLBACK *SECMODModuleDBFunc)(unsigned long function,
                                                 char *parameters, void *moduleSpec);

/* softoken slot ID's */
#define SFTK_MIN_USER_SLOT_ID 4
#define SFTK_MAX_USER_SLOT_ID 100
#define SFTK_MIN_FIPS_USER_SLOT_ID 101
#define SFTK_MAX_FIPS_USER_SLOT_ID 127

/* Module Interface. This is the old NSS private module interface, now exported
 * as a PKCS #11 v3 interface. It's interface name is
 * "Vendor NSS ModS12_PBE_SHA512_HMAC_KEY_GEN (CKM_NSS + 32)

#define CKM_NSS_CHACHA20_CTR (CKM_NSS + 33)

/* IKE mechanisms now defined in PKCS #11, use those instead now */
#define CKM_NSS_IKE_PRF_PLUS_DERIVE (CKM_NSS + 34)
#define CKM_NSS_IKE_PRF_DERIVE (CKM_NSS + 35)
#define CKM_NSS_IKE1_PRF_DERIVE (CKM_NSS + 36)
#define CKM_NSS_IKE1_APP_B_PRF_DERIVE (CKM_NSS + 37)

#define CKM_NSS_PUB_FROM_PRIV (CKM_NSS + 40)

/* SP800-108 NSS mechanism with support for data object derivation */
#define CKM_NSS_SP800_108_COUNTER_KDF_DERIVE_DATA (CKM_NSS + 42)
#define CKA_NSS_TRUST 0x80000001L

/* FAKE PKCS #11 defines */
#define CKM_FAKE_RANDOM 0x80000efeUL
#define CKM_INVALID_MECHANISM 0xffffffffUL
#define CKT_INVALID_TYPE 0xffffffffUL

/*
 * NSS-defined crypto mechanisms
 *
 */
#define CKM_NSS (CKM_VENDOR_DEFINED | NSSCK_VENDOR_NSS)

#define CKM_NSS_AES_KEY_WRAP (CKM_NSS + 1)
#define CKM_NSS_AES_KEY_WRAP_PAD (CKM_NSS + 2)

/* HKDF key derivation mechanisms. See CK_NSS_HKDFParams for documentation. */
#define CKM_NSS_HKDF_SHA1 (CKM_NSS + 3)
#define CKM_NSS_HKDF_SHA256 (CKM_NSS + 4)
#defld be inlined to prevent storage creation, but will fail
 *       when constant values are expected (like switch statements).
 *  enum types do not seem to pay attention to the deprecated attribute.
 *
 *  That leaves typedefs. We declare new types that we then deprecate, then
 *  cast the resulting value to the deprecated type in the #define, thus
 *  producting the warning when the #define is used.
 *
 *  To make this work with the C preprocessor, we first include a
 *  _NSS_DEPRECATE_DEFINE_TYPE(type, name, message) declaration Time DER_TimeToUTCTime_Util
#define DER_UTCDayToAscii DER_UTCDayToAscii_Util
#define DER_UTCTimeToAscii DER_UTCTimeToAscii_Util
#define DER_UTCTimeToTime DER_UTCTimeToTime_Util
#define NSS_PutEnv NSS_PutEnv_Util
#define NSSBase64_DecodeBuffer NSSBase64_DecodeBuffer_Util
#define NSSBase64_EncodeItem NSSBase64_EncodeItem_Util
#define NSSBase64Decoder_Create NSSBase64Decoder_Create_Util
#define NSSBase64Decoder_Destroy NSSBase64Decoder_Destroy_Util
#define NSSBase64Decoder_Update NSSBase64Decoder_Update_Util
#define NSSBase64Encoder_Cickname: Output parameter that may contain the renamed nickname.
 * arg: The user data that was passed to SEC_PKCS12DecoderRenameCertNicknames.
 *
 * If the callback accept that NSS will use a nickname based on the
 * default_nickname (potentially resolving conflicts), then the callback
 * must set *new_nickname to NULL.
 *
 * If the callback wishes to override the nickname, it must set *new_nickname
 * to a new SECItem which should be allocated using
 *     SECITEM_AllocItem(NULL, NULL, LENGTH_OF_NEW_NICKNAME + 1)
 * new_nickname-LARE(SEC_EnumeratedTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_PointerToEnumeratedTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_SequenceOfAnyTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_SequenceOfObjectIDTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_SkipTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_UniversalStringTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_PrintableStringTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_T61StringTemplate)
SEC_ASN1_CHOOSER_DECLARE(SEC_PointerToGeneralizedTimeTemplate)
SEC_END_PROTOS
#endif /* _SECASN1_H_ */
/* -*- Mode: C; tab-width: 8 -*-*/
/* T
 * primitive types
 */
extern PRBool SEC_ASN1IsTemplateSimple(const SEC_ASN1Template *theTemplate);

/************************************************************************/

/*
 * Generic Templates
 * One for each of the simple types, plus a special one for ANY, plus:
 *  - a pointer to each one of those
 *  - a set of each one of those
 *  - a sequence of each one of those
 *
 * Note that these are alphabetical (case insensitive); please add new
 * ones in the appropriate place.
 */

extern const SEC_ASN1Template SEC_AnyTemplaubject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef CK_H
#define CK_H

/*
 * ck.h
 *
 * This header file consolidates all header files needed by the source
 * files implementing the NSS Cryptoki Framework.  This makes managing
 * the source files a bit easier.
 */

/* Types */

#ifndef NSSBASET_H
#include "nssbaset.h"
#endif /* NSSBASET_H */

#ifndef NSSCKT_H
#include "nssckt.h"
#endif /* NSSCKT_H */
 the criterion's policies. If "params" has this criterion set,
 *  but the List of OIDs is empty, then a certificate's CertificatePolicies
 *  extension must include at least some policy.
 *
 *  If "params" does not have this criterion set, this function stores NULL at
 *  "pPolicy", in which case all certificates are considered to match this
 *  criterion.
 *
 *  Note that the List returned by this function is immutable.
 *
 * PARAMETERS:
 *  "params"
 *      Address of ComCertSelParams object whose policy criterion (if any) is
 **plContext);


/*
 * FUNCTION: PKIX_ComCertSelParams_GetKeyUsage
 * DESCRIPTION:
 *
 *  Retrieves a PKIX_UInt32 (if any) representing the key usage criterion that
 *  is set in the ComCertSelParams object pointed to by "params" and stores it
 *  at "pKeyUsage". In order to match against this criterion, a certificate
 *  must allow the criterion's key usage values. Note that a certificate that
 *  has no KeyUsage extension implicity allows all key usages. Note also that
 *  this functions supports a maximum of 32 key usage bits.
 *
:
 *
 *  Sets the basic constraints criterion of the ComCertSelParams object
 *  pointed to by "params" using the integer value of "minPathLength". In
 *  order to match against this criterion, there are several possibilities.
 *
 *  1) If the criterion's minimum path length is greater than or equal to zero,
 *  a certificate must include a BasicConstraints extension with a pathLen of
 *  at least this value.
 *
 *  2) If the criterion's minimum path length is -2, a certificate must be an
 *  end-entity certificate.
 *
 *  3) If th:
 *  "params"
 *      Address of ComCertSelParams object whose subject public key
 *      algorithm identifier criterion is to be set. Must be non-NULL.
 *  "algId"
 *      Address of OID used to set criterion
 *      (or NULL to disable the criterion).
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Not Thread Safe - assumes exclusive access to "params"
 *  (see Thread Safety Definitions in Programmer's Guide)
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns a CertSelector Error lParams object
 *  pointed to by "params" using a List of GeneralNames pointed to by "names".
 *  In order to match against this criterion, a certificate must contain all or
 *  at least one of the criterion's subject alternative names (depending on the
 *  result of PKIX_ComCertSelParams_GetMatchAllSubjAltNames). The default
 *  behavior requires a certificate to contain all of the criterion's subject
 *  alternative names in order to match.
 *
 *  If "names" is NULL, all certificates are considered to match this
 *  criterion.
 *f PKIX_Error *
(*PKIX_CertSelector_MatchCallback)(
        PKIX_CertSelector *selector,
        PKIX_PL_Cert *cert,
        void *plContext);

/*
 * FUNCTION: PKIX_CertSelector_Create
 * DESCRIPTION:
 *
 *  Creates a new CertSelector using the Object pointed to by
 *  "certSelectorContext" (if any) and stores it at "pSelector". As noted
 *  above, by default, the MatchCallback is set to point to the default
 *  implementation provided by libpkix, which understands how to process
 *  ComCertSelParams objects. This is overridden if telector_SetCommonCertSelectorParams.
 * Any common parameter that is not set is assumed to be disabled, which means
 * the default MatchCallback implementation will select all certificates
 * without regard to that particular disabled parameter. For example, if the
 * SerialNumber parameter is not set, MatchCallback will not filter out any
 * certificate based on its serial number. As such, if no parameters are set,
 * all are disabled and any certificate will match. If a parameter is
 * disabled, its associated PKIX_ComCertSelParathm. If successful, this function returns NULL and stores the
 *  ValidateResult at "pResult", which holds additional information, such as
 *  the policy tree and the target's public key. If unsuccessful, an Error is
 *  returned. Note: This function does not currently support non-blocking I/O.
 *
 *  If "pVerifyTree" is non-NULL, a chain of VerifyNodes is created which
 *  tracks the results of the validation. That is, either each node in the
 *  chain has a NULL Error component, or the last node contains an Error
 *  which indicaD_MLKEM768X25519 = 389,

    SEC_OID_TLS_REQUIRE_EMS = 390,

    SEC_OID_TOTAL
} SECOidTag;

#define SEC_OID_SECG_EC_SECP192R1 SEC_OID_ANSIX962_EC_PRIME192V1
#define SEC_OID_SECG_EC_SECP256R1 SEC_OID_ANSIX962_EC_PRIME256V1
#define SEC_OID_PKCS12_KEY_USAGE SEC_OID_X509_KEY_USAGE

/* fake OID for DSS sign/verify */
#define SEC_OID_SHA SEC_OID_MISS_DSS

typedef enum {
    INVALID_CERT_EXTENSION = 0,
    UNSUPPORTED_CERT_EXTENSION = 1,
    SUPPORTED_CERT_EXTENSION = 2
} SECSupportExtenTag;

struct SECOidDataStr {
    SECItem oid;
    S_OID_PKIX_REGINFO_CERT_REQUEST = 145,
    SEC_OID_EXT_KEY_USAGE_SERVER_AUTH = 146,
    SEC_OID_EXT_KEY_USAGE_CLIENT_AUTH = 147,
    SEC_OID_EXT_KEY_USAGE_CODE_SIGN = 148,
    SEC_OID_EXT_KEY_USAGE_EMAIL_PROTECT = 149,
    SEC_OID_EXT_KEY_USAGE_TIME_STAMP = 150,
    SEC_OID_OCSP_RESPONDER = 151,

    /* Netscape Algorithm OIDs */
    SEC_OID_NETSCAPE_SMIME_KEA = 152,

    /* Skipjack OID -- ### mwelch temporary */
    SEC_OID_FORTEZZA_SKIPJACK = 153,

    /* PKCS 12 V2 oids */
    SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC4 = 15EC_OID_DES_CBC = 10,
    SEC_OID_DES_OFB = 11,
    SEC_OID_DES_CFB = 12,
    SEC_OID_DES_MAC = 13,
    SEC_OID_DES_EDE = 14,
    SEC_OID_ISO_SHA_WITH_RSA_SIGNATURE = 15,
    SEC_OID_PKCS1_RSA_ENCRYPTION = 16,
    SEC_OID_PKCS1_MD2_WITH_RSA_ENCRYPTION = 17,
    SEC_OID_PKCS1_MD4_WITH_RSA_ENCRYPTION = 18,
    SEC_OID_PKCS1_MD5_WITH_RSA_ENCRYPTION = 19,
    SEC_OID_PKCS1_SHA1_WITH_RSA_ENCRYPTION = 20,
    SEC_OID_PKCS5_PBE_WITH_MD2_AND_DES_CBC = 21,
    SEC_OID_PKCS5_PBE_WITH_MD5_AND_DES_CBC = 22,
    SEC_OID_PKCS5_PBE_WITH_SHA1_AND_Dto by
 *  "fmtIndicator" and stores it at "pString". If the format is PKIX_ESCASCII
 *  the "stringLen" parameter is ignored and the string extends until a zero
 *  byte is  found. Once created, a String object is immutable.
 *
 *  Valid formats are:
 *      PKIX_ESCASCII
 *      PKIX_ESCASCII_DEBUG
 *      PKIX_UTF8
 *      PKIX_UTF8_NULL_TERM
 *      PKIX_UTF16
 *
 * PARAMETERS:
 *  "fmtIndicator"
 *      Format that "stringRep" is encoded with. Must be non-NULL.
 *  "stringRep"
 *      Address of encoded string representation. M *
 *  Creates a duplicate copy of the Object pointed to by "object" using the
 *  callback registered for "object"'s type and stores the copy at
 *  "pNewObject". Changes to the new object will not affect the original and
 *  vice versa.
 *
 *  Note that if "object" is immutable, the Duplicate callback function simply
 *  needs to increment the reference count on "object" and return a reference
 *  to "object".
 *
 * PARAMETERS:
 *  "object"
 *      Address of Object to be duplicated. Must be non-NULL.
 *      The DuplicateCallbaceturn PKIX_FALSE if the objects are of different
 *  types, other callbacks may be capable of comparing objects of different
 *  types [which may correctly result in cases where Equals(first, second)
 *  differs from Equals(second, first)].
 *
 * PARAMETERS:
 *  "firstObject"
 *      Address of the first Object to compare. Must be non-NULL.
 *      The EqualsCallback for this Object will be called.
 *  "secondObject"
 *      Address of the second Object to compare. Must be non-NULL.
 *  "pResult"
 *      Address where Boolean will should call InvalidateCache whenever changes are made to
 *  the object's state (after creation). If an error occurs during allocation,
 *  "pObject" will be set to NULL. If "size" equals zero, this function creates
 *  an Object with a reference count of 1, and places a pointer to unallocated
 *  memory at "pMemory".
 *
 * PARAMETERS:
 *  "type"
 *      The type code of this object. See pkixt.h for codes. The type code
 *      must be previously registered with PKIX_PL_Object_RegisterType().
 *  "size"
 *      The number of bytes tion.
 *
 *  This function deallocates any memory used by the Portability Layer (PL)
 *  component of the libpkix library and shuts down any ongoing operations.
 *  This function should only be called once. If it is called more than once,
 *  the behavior is undefined.
 *
 *  No PKIX_* types and functions should be used after this function is called
 *  and returns successfully.
 *
 * PARAMETERS:
 *  "platformInitNeeded"
 *      Boolean value of whether PKIX initialized NSS: PKIX_TRUE if we
 *      called nssInit, PKIX_FALSE otherw  void *cbArg, PRBool forceLogin, void *pwArg);

/* fetch multiple CRLs for a specific issuer */
SECStatus pk11_RetrieveCrls(CERTCrlHeadNode *nodes, SECItem *issuer,
                            void *wincx);

/* set global options for NSS PKCS#11 module loader */
SECStatus pk11_setGlobalOptions(PRBool noSingleThreadedModules,
                                PRBool allowAlreadyInitializedModules,
                                PRBool dontFinalizeModules);

/* return whether NSS is allowed to call C_Finalize */
PRBool pk11_getFinaliilock log module. Similarly, you will
**    need to set the environment variable NSPR_LOG_FILE to specify
**    the filename to receive the recorded data. See prlog.h for usage.
**    Example:
**
**        export NSPR_LOG_MODULES=nssilock:6
**        export NSPR_LOG_FILE=xxxLogfile
**
** Operation:
**    nssilock wraps calls to NSPR's PZLock and PZMonitor functions
**    with similarly named functions: PZ_NewLock(), etc. When NSS is
**    built with lock instrumentation enabled, the PZ* functions are
**    compiled into NSS; when lattedAscii CERT_UTCTime2FormattedAscii

/*
** Convert from a PRTime Generalized time value to a formatted ascii value. The
** caller is responsible for deallocating the returned buffer.
*/
extern char *CERT_GenTime2FormattedAscii(PRTime genTime, char *format);

/*
** decode a SECItem containing either a SEC_ASN1_GENERALIZED_TIME
** or a SEC_ASN1_UTC_TIME
*/

extern SECStatus DER_DecodeTimeChoice(PRTime *output, const SECItem *input);

/* encode a PRTime to an ASN.1 DER SECItem containing either a
   SEC_ASN1_GENERALIZED_TIME or a SL_LdapCertStore_Create(
        PKIX_PL_LdapClient *client,
        PKIX_CertStore **pCertStore,
        void *plContext);
#endif /* !NSS_PKIX_NO_LDAP */

/* PKIX_PL_NssContext
 *
 * A PKIX_PL_NssContext provides an example showing how the "plContext"
 * argument, that is part of every libpkix function call, can be used.
 * The "plContext" is the Portability Layer Context, which can be used
 * to communicate layer-specific information from the application to the
 * underlying Portability Layer (while bypassing the Portable Code, wh what values might be appropriate for the bindname
 *  and authentication fields, which are currently implemented as char strings
 *  supplied by the caller. (If this changes, the API and possibly the templates
 *  will have to change.) Therefore the Client_Create API contains a BindAPI
 *  structure, a union, which will have to be revised and extended when this
 *  area of the protocol is better understood.
 *
 * PARAMETERS:
 *  "hostname"
 *      Address of the hostname to be used for the socket connection. Must be
 *      non-NU the request is suspended for non-blocking I/O, a platform-dependent
 *  context is stored at "pNBIOContext" and NULL is stored at "pCerts". This
 *  return is referred to as the WOULDBLOCK state. Note that the caller must
 *  check for a non-NULL value at "pNBIOContext", to distinguish this state from
 *  the "no such extension" return described in the first paragraph. (The
 *  alternative would be to return an empty List, but it seemed wrong to incur
 *  the overhead of creating and destroying an empty List for the most common
 *Name_CreateFromCERTName(
        SECItem *derName,
        CERTName *name,
        PKIX_PL_X500Name **pName,
        void *plContext);


/*
 * TYPE: PKIX_PL_X500Name_Match
 * DESCRIPTION:
 *  Checks whether the X500Name pointed to by "firstX500Name" MATCHES the
 *  X500Name pointed to by "secondX500Name" and stores the boolean result at
 *  "pResult". Two X500Names MATCH if they meet the conditions specified by
 *  RFC 3280 (section 4.1.2.4). Namely:
 *
 *      "This specification requires only a subset of the name comparison
 *   (
        PKIX_PL_CRL *crl,
        PKIX_PL_Date *date,
        PKIX_Boolean *pResult,
        void *plContext);

/*
 * FUNCTION: PKIX_PL_CRL_VerifySignature
 * DESCRIPTION:
 *
 *  Verifies the signature on the CRL pointed to by "crl" using the PublicKey
 *  pointed to by "pubKey". If the signature doesn't verify, a PKIX_Error
 *  pointer is returned.
 *
 * PARAMETERS:
 *  "crl"
 *      Address of CRL whose signature is to be verified. Must be non-NULL.
 *  "pubKey"
 *      Address of a Public Key used to verify the signature. MustNCTION: PKIX_PL_InfoAccess_GetLocationType
 * DESCRIPTION:
 *
 *  Stores the type of location of the Information Access from "infoAccess" and
 *  returns in "pType".
 *
 *  SubjectInfoAccess ::=
 *    AccessDescription ::= SEQUENCE {
 *        accessMethod     OBJECT IDENTIFIER,
 *        accessLocation   GeneralName
 *    }
 *
 * PARAMETERS:
 *  "infoAccess"
 *      Address of PKIX_PL_InfoAccess that has the access data.
 *      Must be non-NULL.
 *  "pType"
 *      Address where access location type will be stored and returned.
 hecks the Cert specified by "cert" to determine, in a manner that depends
 *  on the underlying platform, whether it is trusted, and stores the result in
 *  "pTrusted". If a certificate is trusted it means that a chain built to that
 *  certificate, and satisfying all the usage, policy, validity, and other
 *  tests, is a valid chain and the End Entity certificate from which it was
 *  built can be trusted.
 *
 *  If the Certificate is not intrinsically trustworthy, it still might end up a
 *  component in a successful chain.
 *
 turns a Cert Error if the function fails in a non-fatal way.
 *  Returns a Fatal Error if the function fails in an unrecoverable way.
 */
PKIX_Error *
PKIX_PL_Cert_GetInhibitAnyPolicy(
        PKIX_PL_Cert *cert,
        PKIX_Int32 *pSkipCerts,
        void *plContext);

/* policy processing functions */

/*
 * FUNCTION: PKIX_PL_Cert_AreCertPoliciesCritical
 * DESCRIPTION:
 *
 *  Checks whether the certificate policies extension of the Cert pointed to
 *  by "cert" is critical and stores the Boolean result at "pCritical". If
 *  "c is immutable.
 *
 *  certificatePolicies ::= SEQUENCE SIZE (1..MAX) OF PolicyInformation
 *
 *  PolicyInformation ::= SEQUENCE {
 *      policyIdentifier   CertPolicyId,
 *      policyQualifiers   SEQUENCE SIZE (1..MAX) OF
 *                              PolicyQualifierInfo OPTIONAL }
 *
 *  PolicyQualifierInfo ::= SEQUENCE {
 *      policyQualifierId  PolicyQualifierId,
 *      qualifier       ANY DEFINED BY policyQualifierId }
 *
 * PARAMETERS:
 *  "policyInfo"
 *      Address of CertPolicyInfo whose policy qualifiers List is to
PKIX_PL_Cert_GetSubjectAltNames(
        PKIX_PL_Cert *cert,
        PKIX_List **pSubjectAltNames,  /* list of PKIX_PL_GeneralName */
        void *plContext);

/*
 * FUNCTION: PKIX_PL_Cert_GetAllSubjectNames
 * DESCRIPTION:
 *
 *  Retrieves a pointer to the List of GeneralNames (each GeneralName
 *  representing a subject DN or a subject alternative name found in the
 *  subject alternative names extension of the Cert pointed to by "cert") and
 *  stores it at "pAllSubjectNames".If the Subject DN of "cert" is empty and
 *  it doe  PKIX_PL_Cert *cert,
        PKIX_PL_ByteArray **pAuthKeyId,
        void *plContext);

/*
 * FUNCTION: PKIX_PL_Cert_GetSubjectKeyIdentifier
 * DESCRIPTION:
 *
 *  Retrieves a pointer to a ByteArray representing the subject key identifier
 *  extension of the Cert pointed to by "cert" and stores it at "pSubjKeyId".
 *  If "cert" does not have a SubjectKeyIdentifier extension, this function
 *  stores NULL at "pSubjKeyId".
 *
 *  SubjectKeyIdentifier ::= KeyIdentifier
 *
 * PARAMETERS:
 *  "cert"
 *      Address of Cert whose subjeGER
 *
 *  Validity ::= SEQUENCE {
 *      notBefore       Time,
 *      notAfter        Time }
 *
 *  Time ::= CHOICE {
 *      utcTime         UTCTime,
 *      generalTime     GeneralizedTime }
 *
 *  UniqueIdentifier  ::=  BIT STRING
 *
 *  SubjectPublicKeyInfo  ::=  SEQUENCE  {
 *      algorithm               AlgorithmIdentifier,
 *      subjectPublicKey        BIT STRING  }
 *
 *  Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
 *
 *  Extension  ::=  SEQUENCE  {
 *      extnID          OBJECT IDENTIFIER,
 *      critical        BOUND,
        SEND_PENDING,
        RECV,
        RECV_PENDING,
        RECV_INITIAL,
        RECV_NONINITIAL,
        ABANDON_PENDING
} LdapClientConnectStatus;

struct PKIX_PL_LdapDefaultClientStruct {
        PKIX_PL_LdapClient vtable;
        LdapClientConnectStatus connectStatus;
        PKIX_UInt32 messageID;
        PKIX_PL_HashTable *cachePtr;
        PKIX_PL_Socket *clientSocket;
        PRPollDesc pollDesc;
        void *callbackList; /* cast this to (PKIX_PL_Socket_Callback *) */
        LDAPBindAPI *bindAPI;
   for the context's
 * state, it will receive the state.
 * If the buffer is not large enough (or NULL), then a new buffer will
 * be allocated with PORT_Alloc.
 * In either case, the state will be returned as a buffer, and the length
 * of the state will be given in *stateLen.
 */
unsigned char *
PK11_SaveContextAlloc(PK11Context *cx,
                      unsigned char *preAllocBuf, unsigned int pabLen,
                      unsigned int *stateLen);

SECStatus PK11_RestoreContext(PK11Context *cx, unsigned char *save, int len);
SECSincx);
CK_OBJECT_HANDLE PK11_FindObjectForCert(CERTCertificate *cert,
                                        void *wincx, PK11SlotInfo **pSlot);
SECStatus PK11_TraverseCertsForNicknameInSlot(SECItem *nickname,
                                              PK11SlotInfo *slot, SECStatus (*callback)(CERTCertificate *, void *),
                                              void *arg);
CERTCertList *PK11_ListCerts(PK11CertListType type, void *pwarg);
CERTCertList *PK11_ListCertsInSlot(PK11SlotInfo *slot);
CERTSignedCrl *PK11_ImportCRL(        void *wincx);
/*
 * The attrFlags is the logical OR of the PK11_ATTR_XXX bitflags.
 * These flags apply to the private key.  The PK11_ATTR_TOKEN,
 * PK11_ATTR_SESSION, PK11_ATTR_MODIFIABLE, and PK11_ATTR_UNMODIFIABLE
 * flags also apply to the public key.
 */
SECKEYPrivateKey *PK11_GenerateKeyPairWithFlags(PK11SlotInfo *slot,
                                                CK_MECHANISM_TYPE type, void *param, SECKEYPublicKey **pubk,
                                                PK11AttrFlags attrFlags, void *wincx);
SECKE           int keySize, CK_FLAGS flags, PRBool isPerm);

/*
 * unwrap a new key with a private key.
 *  PK11_PubUnwrap returns a key which can do exactly one operation, and is
 * ephemeral (session key).
 *  PK11_PubUnwrapWithFlagsPerm is the same as PK11_PubUnwrap except you can
 * use * CKF_ flags to enable more than one operation, and optionally make
 * the key permanent (token key).
 */
PK11SymKey *PK11_PubUnwrapSymKey(SECKEYPrivateKey *key, SECItem *wrapppedKey,
                                 CK_MECHANISM_TYPE target, CK_ATTK_MECHANISM_TYPE PK11_MapSignKeyType(KeyType keyType);

/**********************************************************************
 *                   Symmetric, Public, and Private Keys
 **********************************************************************/
void PK11_FreeSymKey(PK11SymKey *key);
PK11SymKey *PK11_ReferenceSymKey(PK11SymKey *symKey);
PK11SymKey *PK11_ImportDataKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, PK11Origin origin,
                               CK_ATTRIBUTE_TYPE operation, SECItem *key, void *wincx);
PK11ent.
 *   PK11TokenRemoved - returned when the token is not present and we are
 *     waiting for a PK11TokenChangeOrRemovalEvent. The next event to look for
 *     is a PK11TokenPresentEvent.
 */
PK11TokenStatus PK11_WaitForTokenEvent(PK11SlotInfo *slot, PK11TokenEvent event,
                                       PRIntervalTime timeout, PRIntervalTime pollInterval, int series);

PRBool PK11_NeedPWInit(void);
PRBool PK11_TokenExists(CK_MECHANISM_TYPE);
SECStatus PK11_GetModInfo(SECMODModule *mod, CK_INFO *info);
char *PK11_GetModu  This must match the key type.
**	"wincx" void pointer to the window context
*/
extern VFYContext *VFY_CreateContext(SECKEYPublicKey *key, SECItem *sig,
                                     SECOidTag sigAlg, void *wincx);
/*
** Create a signature verification context.
**	"key" the public key to verify with
**	"sig" the encrypted signature data if sig is NULL then
**	   VFY_EndWithSignature must be called with the correct signature at
**	   the end of the processing.
**	"pubkAlg" specifies the cryptographic signing algorithm to use SECOidTag algtag, SECItem *result, SECItem *digest);

/*
** DER sign a single block of data using private key encryption and the
** MD5 hashing algorithm. This routine first computes a digital signature
** using SEC_SignData, then wraps it with an CERTSignedData and then der
** encodes the result.
**	"arena" is the memory arena to use to allocate data from
** 	"result" the final der encoded data (memory is allocated)
** 	"buf" the input data to sign
** 	"len" the amount of data to sign
** 	"pk" the private key to encrypt with
*/
e.h"

/*
** An array of these structures defines a BER/DER encoding for an object.
**
** The array usually starts with a dummy entry whose kind is SEC_ASN1_SEQUENCE;
** such an array is terminated with an entry where kind == 0.  (An array
** which consists of a single component does not require a second dummy
** entry -- the array is only searched as long as previous component(s)
** instruct it.)
*/
typedef struct sec_ASN1Template_struct {
    /*
    ** Kind of item being decoded/encoded, including tags and modifiers.
    */
    unskix_pl_pk11certstore.h"
#include "pkix_pl_socket.h"
#ifndef NSS_PKIX_NO_LDAP
#include "pkix_pl_ldapcertstore.h"
#include "pkix_pl_ldaprequest.h"
#include "pkix_pl_ldapresponse.h"
#endif /* !NSS_PKIX_NO_LDAP */
#include "pkix_pl_nsscontext.h"
#include "pkix_pl_httpcertstore.h"
#include "pkix_pl_httpdefaultclient.h"
#include "pkix_pl_infoaccess.h"
#include "pkix_sample_modules.h"

#define MAX_DIGITS_32 (PKIX_UInt32) 10

#define PKIX_PL_NSSCALL(type, func, args)  \
        PKIX_ ## type ## _DEBUG_ARG("( Calling %s).\n", #func); \
     to find fresh info, it's a failure.
 *     This setting overrides the CERT_REV_M_FAIL_ON_MISSING_FRESH_INFO
 *     flag on all methods.
 */
#define CERT_REV_MI_NO_OVERALL_INFO_REQUIREMENT 0UL
#define CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE 2UL

typedef struct {
    /*
     * The size of the array that cert_rev_flags_per_method points to,
     * meaning, the number of methods that are known and defined
     * by the caller.
     */
    PRUint32 number_of_defined_methods;

    /*
     * A pointer to an array of integers.
     
     * will be combined with the pre-existing trusted roots, but only
     * for the certificate validation being performed.
     * If no value has been supplied via cert_pi_trustAnchors, this has
     * no effect.
     * The default value is true, meaning if this is not supplied, only
     * trust anchors supplied via cert_pi_trustAnchors are trusted.
     * Specified in value.scalar.b */
    cert_pi_max /* SPECIAL: signifies maximum allowed value,
                 *  can increase in future releases */
} CERTValParamInType;

/*
 asonRemoveFromCRL = 8,
    crlEntryReasonPrivilegeWithdrawn = 9,
    crlEntryReasonAaCompromise = 10
} CERTCRLEntryReasonCode;

/* If we needed to extract the general name field, use this */
/* General Name types */
typedef enum CERTGeneralNameTypeEnum {
    certOtherName = 1,
    certRFC822Name = 2,
    certDNSName = 3,
    certX400Address = 4,
    certDirectoryName = 5,
    certEDIPartyName = 6,
    certURI = 7,
    certIPAddress = 8,
    certRegisterID = 9
} CERTGeneralNameType;

typedef struct OtherNameStr {
    SECItem name;
 NICKNAMES_SERVER 3
#define SEC_CERT_NICKNAMES_CA 4

struct CERTCertNicknamesStr {
    PLArenaPool *arena;
    void *head;
    int numnicknames;
    char **nicknames;
    int what;
    int totallen;
};

struct CERTIssuerAndSNStr {
    SECItem derIssuer;
    CERTName issuer;
    SECItem serialNumber;
};

/* X.509 v3 Key Usage Extension flags */
#define KU_DIGITAL_SIGNATURE (0x80) /* bit 0 */
#define KU_NON_REPUDIATION (0x40)   /* bit 1 */
#define KU_KEY_ENCIPHERMENT (0x20)  /* bit 2 */
#define KU_DATA_ENCIPHERMENT (0x10) /* bit 3 */
ession.
     * XXX - need an api to set these
     */
    PRBool keepSession;         /* keep this cert for entire session*/
    PRBool timeOK;              /* is the bad validity time ok? */
    CERTOKDomainName *domainOK; /* these domain names are ok */

    /*
     * these values can change when the cert changes state.  These state
     * changes include transitions from temp to perm or vice-versa, and
     * changes of trust flags
     */
    PRBool isperm;
    PRBool istemp;
    char *nickname;
    char *dbnickname;
    structT_H_

#include "prclist.h"
#include "pkcs11t.h"
#include "seccomon.h"
#include "secmodt.h"
#include "secoidt.h"
#include "plarena.h"
#include "prcvar.h"
#include "nssilock.h"
#include "prio.h"
#include "prmon.h"

/* Stan data types */
struct NSSCertificateStr;
struct NSSTrustDomainStr;

/* Non-opaque objects */
typedef struct CERTAVAStr CERTAVA;
typedef struct CERTAttributeStr CERTAttribute;
typedef struct CERTAuthInfoAccessStr CERTAuthInfoAccess;
typedef struct CERTAuthKeyIDStr CERTAuthKeyID;
typedef struct CERTBasicConstraintsStrF_ControlGetAuthenticatorControlValue CRMF_ControlGetPKIArchiveOptions CRMF_DestroyPKIArchiveOptions CRMF_ControlGetRegTokenControlValue CRMF_CertRequestGetExtensionAtIndex CRMF_CertRequestGetNumberOfExtensions crmf_copy_cert_extension                *   üÿÿÿÿÿÿÿ          ,   üÿÿÿÿÿÿÿ4          -   üÿÿÿÿÿÿÿT          .   üÿÿÿÿÿÿÿ#          ,   üÿÿÿÿÿÿÿ9          0   üÿÿÿÿÿÿÿ{          1   üÿÿÿÿÿÿÿ          ,   üÿÿÿÿÿÿÿ2          0   üÿÿÿÿÿÿÿY          1   üÿÿÿÿÿÿÿ'          4   üÿÿÿÿÿÿÿU          5   üÿÿÿÿÿÿÿ(               HƒìdH‹%(   H‰D$1ÀH…ÿt7H‹wH…öt.1ÿH‰âè    …Àu H‹$H‹T$dH+%(   uHƒÄÃ€    1Àëàè           H…ÿtHƒ8 tHƒÇ0é     1ÀÃ     H…ÿt‹‡€   Ã@ 1ÀÃ     H…ÿt;HƒìH‰|$è    ƒøuH‹|$Hƒ tHƒÄé     1ÀHƒÄÃf„     1ÀÃ     H…ÿtcSH‰ûHƒìè    ƒøuA¿€   è    H‰ÂH…Àt1ÿH‰ÞH‰D$è    H‹T$…ÀuHƒÄH‰Ð[ÃfD  H‰×è    1ÒHƒÄH‰Ð[ÃD  1ÀÃ     H…ÿtKH…ötFUH‰õSH‰ûHƒìè    ƒøu(H‹SH‹    ¶ 8•À¶À‰E 1ÀHƒÄ[]ÃfD  ¸ÿÿÿÿëì�¸ÿÿÿÿÃ  H…ÿtKƒuESH‰óè    HƒøÿtH…Àt!Hƒøt¸ÿÿÿÿ[Ã@ Ç   1À[ÃfD  Ç   1ÀëîfD  ¸ÿÿÿÿÃ  1ÀH…ÿt‹GÃ     H    �   
         #       ¯            3       Ù            V       ÿ                      cmmf_create_witness_and_challenge SEC_ASN1EncodeInteger_Util PORT_ArenaAlloc_Util PK11_HashBuf PORT_Free_Util SECITEM_FreeItem_Util _GLOBAL_OFFSET_TABLE_ CMMFRandTemplate SEC_ASN1EncodeItem_Util SECKEY_PublicKeyStrength PK11_GetBestSlotWithAttributes PK11_ImportPublicKey PK11_ImportSymKey PK11_PubWrapSymKey PK11_FreeSlot PK11_FreeSymKey SECITEM_CopyItem_Util crmf_get_public_value __stack_chk_fail CMMF_CreatePOPODecKeyChallContent POdeInteger_Util CMMF_DestroyCertResponse CMMF_CertResponseSetPKIStatusInfoStatus cmmf_PKIStatusInfoSetStatus CMMF_CertResponseSetCertificate CMMF_CertRepContentSetCAPubs CMMF_CertifiedKeyPairGetCertificate cmmf_CertOrEncCertGetCertificate                 üÿÿÿÿÿÿÿ             üÿÿÿÿÿÿÿ6             üÿÿÿÿÿÿÿ&             üÿÿÿÿÿÿÿ:             üÿÿÿÿÿÿÿY             üÿÿÿÿÿÿÿg             üÿÿÿÿÿÿÿ–             üÿÿÿÿÿÿÿ³       *      üÿÿÿÿÿÿÿ¼             üÿÿÿÿÿÿÿá             üÿÿÿÿÿÿÿc             üÿÿÿÿÿÿÿ¡         À   	              zR x�            >    Aƒi
FM X   <       ò    B�EŒD †D(ƒD0\
(C ABBI^
(C ABBJy(C ABB<   ˜       Z   DPH�HŽUŒ�SƒM†WÃEÆSƒ†EÆMÃZ
Deƒ† d   Ø          _�BŽB �E(ŒA0†D8ƒMPŽ
8F0A(B BBBI^8C0A(B BBBAÃÆÌÍÎÏ 0   @      T    A†IƒD c
DAJNDA    t             ,   ˆ      ®    SƒG [
AJf
AIxÃ <   ¸      §    D0HƒTŒL†K�lÆEÌEÍKH0†Œ�LÆEÌEÍIA0     ø             C_OctetStringTemplate_Util SEC_ASN1DecodeItem_Util PORT_FreeArena_Util PK11_UnwrapPrivKey PK11_FreeSymKey crmf_create_encrypted_value_wrapped_privkey PK11_KeyGen PK11_PubWrapSymKey PK11_WrapPrivKey PK11_MechanismToAlgtag SECOID_SetAlgorithmID_Util CRMF_CreateEncryptedKeyWithEncryptedValue CERT_ExtractPublicKey SECKEY_DestroyPublicKey CRMF_DestroyEncryptedKey crmf_copy_pkiarchiveoptions crmf_get_pkiarchiveoptions_subtemplate SEC_UTF8StringTemplate_Util CRMFEncryptedKeyWithEncryptedValueTemplate CRMF_CertRequestSetPKIArchiveOptions Ct=¾0   H‰|$è    H‹|$H…ÀH‰Ãt[L‰âH‰Æè    …ÀuH‰] 1ÀHƒÄ[]A\Ã ¿0   è    H‰ÃH…Àt(1ÿL‰âH‰Æè    …ÀtË¾   H‰ß‰D$è    ‹D$ëº¸ÿÿÿÿë³       ATI‰ÔUH‰ýSH‰óH‹6H…ötè    …À…Ž   H‹sH…ötI�T$H‰ïè    …ÀutHƒ{ tH�SI�t$H‰ïè    …ÀuXH‹s(H…ötI�T$(H‰ïè    …Àu>Hƒ{8 tH�S0I�t$0H‰ïè    …Àu"1ÀHƒ{P t2H�SHI�t$HH‰ïè    …Àt@ H…íuM…ät
1öL‰çè    ¸ÿÿÿÿ[]A\Ã  Hƒì(H‰l$H‰õL‰d$ I‰ÔH…ÿ„£   H‰\$H‰ûè    H‰Á‹E`ƒø„×   ƒøuRH‹} H‰L$è    H‹L$H…ÀI‰$t6‹E`A‰D$`H…ÉtH‰ÎH‰ßè    H‹\$1ÀH‹l$L‹d$ HƒÄ(Ã„     H…ÉtZH‰ßH‰Îè    H‹\$¸ÿÿÿÿH‹l$L‹d$ HƒÄ(Ã€    ‹F\         &   üÿÿÿÿÿÿÿ±         '   üÿÿÿÿÿÿÿÇ            üÿÿÿÿÿÿÿÿ         &   üÿÿÿÿÿÿÿ            üÿÿÿÿÿÿÿ                      4                     X                     „                     ˜                     ¬                     À                     Ô                     ø          	                    
           $                     .symtab .strtab .shstrtab .text .data .bss .text.CRMF_CertReqMsgGetPOPType .rela.text.CRMF_DestroyGetValidity .rela.text.crmf_make_bitstring_copy .text.            @               È      `                                                 P      ˆ                          	                      Ø      5                                                   (                                   crmfget.o/      1795707891  0     0     100644  8624      `
ELF          >                    0          @     @   H…ÿtH‹GH…Àt
‹@8ÃfD  1ÀÃ     H…ÿtKSH‰ûH‹H…ÿt.è    H‹;HÇC    H…ÿtè    HÇ    1À[Ãf„     H‹;H…ÿuß1À[Ã@ 1ÀÃ     ATI‰ôUH‰ÕS‹Z‰Ú�CƒÂIÂH‰êÁøithmOidTag SECOID_SetAlgorithmID_Util CRMFCertRequestTemplate SECOID_GetAlgorithmTag_Util SEC_SignData CRMFPOPOSigningKeyTemplate CRMF_CertReqMsgSetKeyEnciphermentPOP CRMF_CertReqMsgSetKeyAgreementPOP     V             üÿÿÿÿÿÿÿ‹             üÿÿÿÿÿÿÿ             üÿÿÿÿÿÿÿ@             üÿÿÿÿÿÿÿP             üÿÿÿÿÿÿÿ�       *      üÿÿÿÿÿÿÿŒ             üÿÿÿÿÿÿÿ¨             üÿÿÿÿÿÿÿÅ             üÿÿÿÿÿÿÿñ             üÿÿÿÿÿÿÿ	            üÿÿÿÿÿÿÿ            üÿÿÿÿÿÿÿF            üÿÿÿÿÿÿÿQ            üÿÿÿ1EncodeInteger_Util crmf_encode_unsigned_integer SEC_ASN1EncodeUnsignedInteger_Util CRMF_DoesRequestHaveField CRMF_CertRequestGetNumberOfExtensions CRMF_CreateCertRequest PORT_NewArena_Util PORT_ArenaZAlloc_Util PORT_FreeArena_Util CRMF_DestroyCertRequest PORT_Free_Util crmf_template_copy_secalg PORT_ArenaMark_Util SECOID_CopyAlgorithmID_Util PORT_ArenaUnmark_Util PORT_ArenaRelease_Util PORT_SetError_Util crmf_copy_cert_name CERT_CopyName crmf_template_add_public_key SECKEY_CopySubjectPublicKeyInfo PORT_ZAlloc_Util SECKEY_DestroySu       H                                                                          0                                                                              À                                                                                                     GCC: (GNU) 16.2.0                GNU  À            À                                                                                          €       2             €                                                  K    !         @       e         	   üÿÿÿÿÿÿÿ       *      üÿÿÿÿÿÿÿ*       *      üÿÿÿÿÿÿÿ9             üÿÿÿÿÿÿÿS          	   üÿÿÿÿÿÿÿ                      <                     X                      .symtab .strtab .shstrtab .text .data .bss .rela.text.CRMF_EncodeCertReqMsg .rela.text.CRMF_EncodeCertRequest .rela.text.CRMF_EncodeCertReqMessages .comment .note.GNU-stack .note.gnu.property .rela.eh_frame                                                                                      @                                      !         nc. Licence to copy this document
 * is granted provided that it is identified as "RSA Security Inc. Public-Key
 * Cryptography Standards (PKCS)" in all material mentioning or referencing
 * this document.
 */
/*
 * reset any packing set by pkcs11p.h
 */

#if defined(_WIN32) || defined(_WINDOWS)
#ifdef __clang__
#pragma clang diagnostic ignored "-Wpragma-pack"
#endif
#ifdef _MSC_VER
#pragma warning(disable : 4103)
#endif
#pragma pack(pop, cryptoki)
#endif
!<arch>
/               1795707891  0     0     0       6794      `
   Â  Î which
 * does not confuse ctags and other related utilities.  NSPR
 * defines these macros to take the type as an argument, because
 * of certain OS requirements on platforms not supported by NSS.
 */

#define DUMMY /* dummy */
#define NSS_EXTERN extern
#define NSS_EXTERN_DATA extern
#define NSS_IMPLEMENT
#define NSS_IMPLEMENT_DATA

PR_BEGIN_EXTERN_C

/*
 * NSSError
 *
 * Calls to NSS routines may result in one or more errors being placed
 * on the calling thread's "error stack."  Every possible error that
 * may be returned from avocationNotification-notification that a
 *                          revocation has occurred.
 *
 *         6               keyUpdateWarning-update already done for the
 *                          oldCertId specified in FullCertTemplate.
 */

struct CMMFPKIStatusInfoStr {
    SECItem status;
    SECItem statusString;
    SECItem failInfo;
};

struct CMMFCertOrEncCertStr {
    union {
        CERTCertificate *certificate;
        CRMFEncryptedValue *encryptedCert;
    } cert;
    CMMFCertOrEncCertChoice choice;
    SECItem derValue;or v2.10.
 * CK_PKCS5_PBKD2_PARAMS is a structure that provides the
 * parameters to the CKM_PKCS5_PBKD2 mechanism. */
/* this structure is kept for compatibility. use _PARAMS2. */
typedef struct CK_PKCS5_PBKD2_PARAMS {
    CK_PKCS5_PBKDF2_SALT_SOURCE_TYPE saltSource;
    CK_VOID_PTR pSaltSourceData;
    CK_ULONG ulSaltSourceDataLen;
    CK_ULONG iterations;
    CK_PKCS5_PBKD2_PSEUDO_RANDOM_FUNCTION_TYPE prf;
    CK_VOID_PTR pPrfData;
    CK_ULONG ulPrfDataLen;
    CK_UTF8CHAR_PTR pPassword;
    CK_ULONG_PTR ulPasswordLen;
} CK_PKCMS CK_PTR
    CK_TLS12_MASTER_KEY_DERIVE_PARAMS_PTR;

typedef struct CK_TLS12_KEY_MAT_PARAMS {
    CK_ULONG ulMacSizeInBits;
    CK_ULONG ulKeySizeInBits;
    CK_ULONG ulIVSizeInBits;
    CK_BBOOL bIsExport; /* Unused. Must be set to CK_FALSE. */
    CK_SSL3_RANDOM_DATA RandomInfo;
    CK_SSL3_KEY_MAT_OUT_PTR pReturnedKeyMaterial;
    CK_MECHANISM_TYPE prfHashMechanism;
} CK_TLS12_KEY_MAT_PARAMS;

typedef CK_TLS12_KEY_MAT_PARAMS CK_PTR CK_TLS12_KEY_MAT_PARAMS_PTR;

typedef struct CK_TLS_KDF_PARAMS {
    CK_MECHANISM_TYPE prfMechaniES_CBC_ENCRYPT_DATA_PARAMS_PTR;

/* CK_AES_CTR_PARAMS is new for PKCS #11 v2.20 amendment 3 */
typedef struct CK_AES_CTR_PARAMS {
    CK_ULONG ulCounterBits;
    CK_BYTE cb[16];
} CK_AES_CTR_PARAMS;

typedef CK_AES_CTR_PARAMS CK_PTR CK_AES_CTR_PARAMS_PTR;

/* CK_GCM_PARAMS is new for version 2.30 */
/* There was a discrepency between the doc and the headers
 * in PKCS #11 v2.40, NSS had the doc version, but the header
 * was normative. In V3.0 they were reconsiled as the header
 * version. In NSS the header version is called CK_GCM019UL
#define CKD_BLAKE2B_512_KDF 0x0000001aUL

/* CK_ECDH1_DERIVE_PARAMS is new for v2.11.
 * CK_ECDH1_DERIVE_PARAMS provides the parameters to the
 * CKM_ECDH1_DERIVE and CKM_ECDH1_COFACTOR_DERIVE mechanisms,
 * where each party contributes one key pair.
 */
typedef struct CK_ECDH1_DERIVE_PARAMS {
    CK_EC_KDF_TYPE kdf;
    CK_ULONG ulSharedDataLen;
    CK_BYTE_PTR pSharedData;
    CK_ULONG ulPublicDataLen;
    CK_BYTE_PTR pPublicData;
} CK_ECDH1_DERIVE_PARAMS;

typedef CK_ECDH1_DERIVE_PARAMS CK_PTR CK_ECDH1_DERIVE_PARAMS_PTR;

04038UL
#define CKM_ECDH_COF_AES_KEY_WRAP 0x00004039UL
#define CKM_PUB_KEY_FROM_PRIV_KEY 0x0000403aUL

#define CKM_VENDOR_DEFINED 0x80000000UL

typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR;

/* CK_MECHANISM is a structure that specifies a particular
 * mechanism  */
typedef struct CK_MECHANISM {
    CK_MECHANISM_TYPE mechanism;
    CK_VOID_PTR pParameter;

    /* ulParameterLen was changed from CK_USHORT to CK_ULONG for
     * v2.0 */
    CK_ULONG ulParameterLen; /* in bytes */
} CK_MECHANISM;

typedef CK_MECHANISM CK_PTRKM_DSA_PARAMETER_GEN,
 * CKM_DH_PKCS_PARAMETER_GEN, and CKM_X9_42_DH_PARAMETER_GEN are
 * new for v2.11 */
#define CKM_AES_KEY_GEN 0x00001080UL
#define CKM_AES_ECB 0x00001081UL
#define CKM_AES_CBC 0x00001082UL
#define CKM_AES_MAC 0x00001083UL
#define CKM_AES_MAC_GENERAL 0x00001084UL
#define CKM_AES_CBC_PAD 0x00001085UL
/* new for v2.20 amendment 3 */
#define CKM_AES_CTR 0x00001086UL
/* new for v2.30 */
#define CKM_AES_GCM 0x00001087UL
#define CKM_AES_CCM 0x00001088UL
#define CKM_AES_CTS 0x00001089UL
/* AES-CMAC values copied from vine CKM_SHA512_256_HMAC_GENERAL 0x0000004EUL
#define CKM_SHA512_256_KEY_DERIVATION 0x0000004FUL
#define CKM_SHA512_T 0x00000050UL
#define CKM_SHA512_T_HMAC 0x00000051UL
#define CKM_SHA512_T_HMAC_GENERAL 0x00000052UL
#define CKM_SHA512_T_KEY_DERIVATION 0x00000053UL

/* new for v3.2 */
#define CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE 0x00000056UL
#define CKM_TLS12_EXTENDED_MASTER_KEY_DERIVE_DH 0x00000057UL

#define CKM_SHA3_256_RSA_PKCS 0x00000060UL
#define CKM_SHA3_384_RSA_PKCS 0x00000061UL
#define CKM_SHA3_512_RSA_PKCS 0x00000062UL
#deKM_RSA_X9_31 0x0000000BUL
#define CKM_SHA1_RSA_X9_31 0x0000000CUL
#define CKM_RSA_PKCS_PSS 0x0000000DUL
#define CKM_SHA1_RSA_PKCS_PSS 0x0000000EUL

/* new for v3.2 */
#define CKM_ML_KEM_KEY_PAIR_GEN 0x0000000fUL

#define CKM_DSA_KEY_PAIR_GEN 0x00000010UL
#define CKM_DSA 0x00000011UL
#define CKM_DSA_SHA1 0x00000012UL

/* new for v2.40 */
#define CKM_DSA_SHA224 0x00000013UL
#define CKM_DSA_SHA256 0x00000014UL
#define CKM_DSA_SHA384 0x00000015UL
#define CKM_DSA_SHA512 0x00000016UL

/* new for v3.2 */
#define CKM_ML_KEM 0x00000017UL

#_PARAM_OPTIONAL 1UL
#define CK_OTP_PARAM_MANDATORY 2UL

/* The CKF_ARRAY_ATTRIBUTE flag identifies an attribute which
   consists of an array of values. */
#define CKF_ARRAY_ATTRIBUTE 0x40000000UL

/* The following attribute types are defined: */
#define CKA_CLASS 0x00000000UL
#define CKA_TOKEN 0x00000001UL
#define CKA_PRIVATE 0x00000002UL
#define CKA_LABEL 0x00000003UL
/* new for v3.1 */
#define CKA_UNIQUE_ID 0x00000004UL

#define CKA_APPLICATION 0x00000010UL
#define CKA_VALUE 0x00000011UL

/* CKA_OBJECT_ID is new for v2.10 */
#deRRENDER 0
#define CKN_OTP_CHANGED 1

typedef CK_ULONG CK_SLOT_ID;

typedef CK_SLOT_ID CK_PTR CK_SLOT_ID_PTR;

/* CK_SLOT_INFO provides information about a slot */
typedef struct CK_SLOT_INFO {
    /* slotDescription and manufacturerID have been changed from
     * CK_CHAR to CK_UTF8CHAR for v2.10 */
    CK_UTF8CHAR slotDescription[64]; /* blank padded */
    CK_UTF8CHAR manufacturerID[32];  /* blank padded */
    CK_FLAGS flags;

    /* hardwareVersion and firmwareVersion are new for v2.0 */
    CK_VERSION hardwareVersion; /* versiContentGetPublicValue to get the public value of
 *    the key used to encrypt the witness and then use that to determine the
 *    appropriate private key.  This can be done by calling PK11_MakeIDFromPubKey
 *    and then passing that return value to PK11_FindKeyByKeyID.  The creator of
 *    the challenge will most likely be an RA that has the public key
 *    from a Cert request.  So the private key should be the private key
 *    associated with public key in that request.  This function will also
 *    verify the witness fieldhis function retrieves the certificate at
 *    CertifiedKeyPair.certOrEncCert.certificate
 *    The user must call CERT_DestroyCertificate when the return value is no
 *    longer needed.  The user must import this certificate as a token object
 *    onto PKCS#11 slot in order to make it a permanent object.  The returned
 *    certificate will be in the temporary database.
 *
 * RETURN:
 *    A pointer to the certificate contained within the certified key pair.
 *    A return value of NULL indicates an error in creating the copy o       An opaque pointer to a user-supplied argument that will be passed
 *        to the callback funtion whenever the function is called.
 * NOTES:
 *    The CMMF library will use the same DER-encoding scheme as the CRMF
 *    library.  In other words, when reading CRMF comments that pertain to
 *    encoding, those comments apply to the CMMF libray as well.
 *    The callback function will be called multiple times, each time supplying
 *    the next chunk of DER-encoded bytes.  The user must concatenate the
 *    output of each r was successful.  Any other
 *    return value indicates an error in adding certified key pair to
 *    CMMFKeyRecRepContent structure.
 */
extern SECStatus
CMMF_KeyRecRepContentSetCertifiedKeyPair(CMMFKeyRecRepContent *inKeyRecRep,
                                         CERTCertificate *inCert,
                                         SECKEYPrivateKey *inPrivKey,
                                         SECKEYPublicKey *inPubKey);

/*
 * FUNCTION: CMMF_POPODecKeyChallContentSetNextChallenge
 * INPUTS:
 *    inDecKeyChall
 *    N1 decoder and creates a
 *    CMMFPOPODecKeyRespContent structure.
 *
 * RETURN:
 *    A pointer to the CMMFPOPODecKeyRespContent structure.  A NULL return
 *    value indicates the library was unable to parse the DER.
 */
extern CMMFPOPODecKeyRespContent *
CMMF_CreatePOPODecKeyRespContentFromDER(const char *buf, long len);

/************************** Set Functions *************************/

/*
 * FUNCTION: CMMF_CertRepContentSetCertResponses
 * INPUTS:
 *    inCertRepContent
 *        The CMMFCertRepContent to operate on.
 *   security library for
 * implementing Certificate Management Message Formats (CMMF).
 *
 * This API is designed against July 1998 CMMF draft.  Please read this
 * draft before trying to use this API in an application that use CMMF.
 */
#include "seccomon.h"
#include "cmmft.h"
#include "crmf.h"

SEC_BEGIN_PROTOS

/******************* Creation Functions *************************/

/*
 * FUNCTION: CMMF_CreateCertRepContent
 * INPUTS:
 *    NONE
 * NOTES:
 *    This function will create an empty CMMFCertRepContent Structure.
 *    The cate[];
SEC_ASN1_CHOOSER_DECLARE(LDAPFilterTemplate)

/* ********************************************************************** */

#define SEC_ASN1_LDAP_STRING SEC_ASN1_OCTET_STRING

#define LDAPATTR_CACERT         (1<<0)
#define LDAPATTR_USERCERT       (1<<1)
#define LDAPATTR_CROSSPAIRCERT  (1<<2)
#define LDAPATTR_CERTREVLIST    (1<<3)
#define LDAPATTR_AUTHREVLIST    (1<<4)
#define MAX_LDAPATTRS                   5
typedef PKIX_UInt32 LdapAttrMask;

typedef enum {
        SIMPLE_AUTH                     = 0,
        KRBV42LDAP_AUThis:
 *
 * typedef CK_BYTE CK_PTR CK_BYTE_PTR;
 *
 * In a Win32 environment, it might be defined by
 *
 * #define CK_PTR *
 *
 * In a UNIX environment, it might be defined by
 *
 * #define CK_PTR *
 *
 *
 * 2. CK_DEFINE_FUNCTION(returnType, name): A macro which makes
 * an exportable PKCS #11 library function definition out of a
 * return type and a function name.  It should be used in the
 * following fashion to define the exposed PKCS #11 functions in
 * a PKCS #11 library:
 *
 * CK_DEFINE_FUNCTION(CK_RV, C_Initialize)(
 *   CK_Vntifier
 * for the external PSK. Should en external PSK have the same label
 * as a configured resumption PSK identity, the external PSK will
 * take precedence.
 *
 * If you want to enable early data, you need to also provide a
 * cipher suite for 0-RTT and a limit for the early data using
 * SSL_AddExternalPsk0Rtt(). If you want to explicitly disallow
 * certificate authentication, use SSL_AuthCertificateHook to set
 * a callback that rejects all certificate chains.
 */
#define SSL_AddExternalPsk(fd, psk, identity, identityLen, h   const PRUint8 *_hsHash, unsigned int _hsHashLen, \
                          const char *_label, unsigned int _labelLen,      \
                          CK_MECHANISM_TYPE _mech, unsigned int _keySize,  \
                          PK11SymKey **_keyp),                             \
                         (version, cipherSuite, prk,                       \
                          hsHash, hsHashLen, label, labelLen,              \
                          mech, keySize, keyp))

#define SSL_HkdfVariantExpandLabelWithMech(versioam" variant is passed instead,
 * the Label prefix used in HKDF-Expand is "dtls13" instead of "tls13 ". See
 * 7.1 of RFC 8446 and draft-ietf-tls-dtls13-34. */
typedef struct SSLAeadContextStr SSLAeadContext;

#define SSL_MakeAead(version, cipherSuite, secret,                  \
                     labelPrefix, labelPrefixLen, ctx)              \
    SSL_EXPERIMENTAL_API("SSL_MakeAead",                            \
                         (PRUint16 _version, PRUint16 _cipherSuite, \
                          PK11SymKey * _secret,* _fd, SSLResumptionTokenCallback _cb, void *_ctx), \
        (fd, cb, ctx))

/*
 * This allows setting a resumption token for a session.
 * The function returns SECSuccess iff the resumption token can be used,
 * SECFailure in any other case. The caller should remove the |token| from its
 * cache when the function returns SECFailure.
 *
 * - The |fd| argument is the socket file descriptor.
 * - The |token| is a pointer to the resumption token as byte array
 *   of length |len|.
 */
#define SSL_SetResumptionToken(fd, token, len)   n write to.  This provides NSS with
 *   a token.  This token is encrypted and integrity protected and embedded in
 *   the cookie extension of a HelloRetryRequest.  The value of this field is
 *   only used if the handler returns ssl_stateless_retry_check.  NSS allocates
 *   space for this value.
 *
 * - |retryTokenLen| is an outparam for the length of the token. If this value
 *   is not set, or set to 0, an empty token will be sent.
 *
 * - |retryTokenMax| is the size of the space allocated for retryToken. An
 *   application cd int *len, unsigned int maxLen, void *arg);

typedef SECStatus(PR_CALLBACK *SSLExtensionHandler)(
    PRFileDesc *fd, SSLHandshakeType message,
    const PRUint8 *data, unsigned int len,
    SSLAlertDescription *alert, void *arg);

#define SSL_InstallExtensionHooks(fd, extension, writer, writerArg,         \
                                  handler, handlerArg)                      \
    SSL_EXPERIMENTAL_API("SSL_InstallExtensionHooks",                       \
                         (PRFileDesc * _fd, PRUint16 _extension,      "

SEC_BEGIN_PROTOS

/* The functions in this header file are not guaranteed to remain available in
 * future NSS versions. Code that uses these functions needs to safeguard
 * against the function not being available. */

#define SSL_EXPERIMENTAL_API(name, arglist, args)                   \
    (SSL_GetExperimentalAPI(name)                                   \
         ? ((SECStatus(*) arglist)SSL_GetExperimentalAPI(name))args \
         : SECFailure)
#define SSL_DEPRECATED_EXPERIMENTAL_API \
    (PR_SetError(SSL_ERROR_UNSUPPORTED_r's symmetric capabilities to the authenticated
 * (i.e. signed) attributes of "cinfo".  This is expected to be
 * included in outgoing signed messages for email (S/MIME).
 *
 * This can only be added once; a second call will return SECFailure.
 *
 * "cinfo" should be of type signedData or signedAndEnvelopedData;
 * SECFailure will be returned if it is not.
 */
extern SECStatus SEC_PKCS7AddSymmetricCapabilities(SEC_PKCS7ContentInfo *cinfo);

/*
 * Mark that the signer's certificate and its issuing chain should
 * be included in the for validity.
 *
 * "certusage" describes the signing usage (e.g. certUsageEmailSigner)
 * XXX Maybe SECCertUsage should be split so that our caller just says
 * "email" and *we* add the "signing" part -- otherwise our caller
 * could be lying about the usage; we do not want to allow encryption
 * certs for signing or vice versa.
 *
 * "certdb" is the cert database to use for verifying the cert.
 * It can be NULL if a default database is available (like in the client).
 *
 * "digestalg" names the digest algorithm (e.g. SEC_OID_SHA_ComCRLSelParams_SetMaxCRLNumber
 * DESCRIPTION:
 *
 *  Sets the maxCRLNumber criterion of the ComCRLSelParams pointed to by
 *  "params" using a BigInt pointed to by "number". In order to match against
 *  this criterion, a CRL must have a CRL number extension whose value is less
 *  than or equal to the criterion's value.
 *
 * PARAMETERS:
 *  "params"
 *      Address of ComCRLSelParamsParams whose maxCRLNumber criterion is to be
 *      set. Must be non-NULL.
 *  "number"
 *      Address of BigInt used to set the criterion
 *  "/*
 * FUNCTION: PKIX_ComCRLSelParams_GetIssuerNames
 * DESCRIPTION:
 *
 *  Retrieves a pointer to the List of X500Names (if any) representing the
 *  issuer names criterion that is set in the ComCRLSelParams pointed to by
 *  "params" and stores it at "pNames". In order to match against this
 *  criterion, a CRL's IssuerName must match at least one of the criterion's
 *  issuer names.
 *
 *  If "params" does not have this criterion set, this function stores NULL at
 *  "pNames", in which case all CRLs are considered to match.
 *
 *n its CRL number. As such, if no parameters are set, all are
 * disabled and any CRL will match. If a parameter is disabled, its associated
 * PKIX_ComCRLSelParams_Get* function returns a default value of NULL.
 *
 * If a custom implementation is desired, the default implementation can be
 * overridden by calling PKIX_CRLSelector_SetMatchCallback. In this case, the
 * CRLSelector can be initialized with a crlSelectorContext, which is where
 * the caller can specify the desired parameters the caller wishes to match
 * against. Note CItem **values; /* data may or may not be encoded */
    /* The following fields are not part of an encoded Attribute: */
    SECOidData *typeTag;
    PRBool encoded; /* when true, values are encoded */
};

/*
 * Type of function passed to SEC_PKCS7Decode or SEC_PKCS7DecoderStart.
 * If specified, this is where the content bytes (only) will be "sent"
 * as they are recovered during the decoding.
 *
 * XXX Should just combine this with SEC_PKCS7EncoderContentCallback type
 * and use a simpler, common name.
 */
typedef void (*SEC_PKC_FindCertificatesByID(
    NSSTrustDomain *td,
    NSSItem *id,
    NSSCertificate **rvOpt,
    PRUint32 maximumOpt,
    NSSArena *arenaOpt);

NSS_EXTERN NSSCRL **
nssTrustDomain_FindCRLsBySubject(
    NSSTrustDomain *td,
    NSSDER *subject);

/* module-private nsspki methods */

NSS_EXTERN NSSCryptoContext *
nssCryptoContext_Create(
    NSSTrustDomain *td,
    NSSCallback *uhhOpt);

/* XXX for the collection */
NSS_EXTERN NSSCertificate *
nssCertificate_Create(nssPKIObject *object);

NSS_EXTERN PRStatus
nssCertificate_SetCertTrusct_HasInstance
 *
 * Query the object for a token instance.
 */
NSS_EXTERN PRBool
nssPKIObject_HasInstance(
    nssPKIObject *object,
    nssCryptokiObject *instance);

/* nssPKIObject_GetTokens
 *
 * Get all tokens which have an instance of the object.
 */
NSS_EXTERN NSSToken **
nssPKIObject_GetTokens(
    nssPKIObject *object,
    PRStatus *statusOpt);

/* nssPKIObject_GetNicknameForToken
 *
 * tokenOpt == NULL means take the first available, otherwise return the
 * nickname for the specified token.
 */
NSS_EXTERN NSSUTF8 *
nssPKain). If the builder encounters more than this maximum number of
 *  certificates when searching for the next candidate certificate, it should
 *  abort and return an Error. This parameter is only relevant for ValidateChain
 *  if it needs to internally call BuildChain (e.g. in order to build the
 *  chain to a CRL's issuer).
 *
 * PARAMETERS:
 *  "resourceLimits"
 *      Address of ResourceLimits object whose maximum fanout (number of certs)
 *      is to be set. Must be non-NULL.
 *  "maxFanout"
 *      Value of PKIX_UInt32 repreourceLimits" and stores
 *  it at "pMaxTime". This maximum time (in seconds) should not be exceeded
 *  by the function whose ProcessingParams contain this ResourceLimits object
 *  (typically ValidateChain or BuildChain). It essentially functions as a
 *  time-out value and is only appropriate if blocking I/O is being used.
 *
 * PARAMETERS:
 *  "resourceLimits"
 *      Address of ResourceLimits object whose maximum time (in seconds) is
 *      to be stored. Must be non-NULL.
 *  "pMaxTime"
 *      Address where PKIX_UInt32 will bIX_ProcessingParams_SetPolicyMappingInhibited(
        PKIX_ProcessingParams *params,
        PKIX_Boolean inhibited,
        void *plContext);


/* PKIX_ValidateParams
 *
 * PKIX_ValidateParams consists of a ProcessingParams object as well as the
 * List of Certs (certChain) that the caller is trying to validate.
 */

/*
 * FUNCTION: PKIX_ValidateParams_Create
 * DESCRIPTION:
 *
 *  Creates a new ValidateParams object and stores it at "pParams".
 *
 * PARAMETERS:
 *  "procParams"
 *      Address of ProcessingParams to be used. Mus ResourceLimits
 *  object pointed to by "resourceLimits". The ResourceLimits represent the
 *  maximum resource usage that the caller desires (such as MaxTime). The
 *  ValidateChain or BuildChain call will not exceed these maximum limits.
 *  If "resourceLimits" is NULL, no ResourceLimits are defined.
 *
 * PARAMETERS:
 *  "params"
 *      Address of ProcessingParams whose ResourceLimits are to be set.
 *      Must be non-NULL.
 *  "resourceLimits"
 *      Address of ResourceLimits to be set. If NULL, no limits are defined.
 *  "     PKIX_List **pAnchors,  /* list of TrustAnchor */
        void *plContext);
/*
 * FUNCTION: PKIX_ProcessingParams_SetTrustAnchors
 * DESCRIPTION:
 *
 * Sets user defined set of trust anchors. The handling of the trust anchors
 * may be furthered alter via PKIX_ProcessingParams_SetUseOnlyTrustAnchors.
 * By default, a certificate will be considered invalid if it does not chain
 * to a trusted anchor from this list.
 *
 * PARAMETERS:
 *  "params"
 *      Address of ProcessingParams whose List of TrustAnchors are to
 *      be stoX_Error *
PKIX_ProcessingParams_AddCertStore(
        PKIX_ProcessingParams *params,
        PKIX_CertStore *store,
        void *plContext);

/*
 * FUNCTION: PKIX_ProcessingParams_GetDate
 * DESCRIPTION:
 *
 *  Retrieves a pointer to the Date (if any) that is set in the
 *  ProcessingParams pointed to by "params" and stores it at "pDate". The
 *  Date represents the time for which the validation of the certificate chain
 *  should be determined. If "params" does not have any Date set, this function
 *  stores NULL at "pDate".
 *
 ocessingParams_SetCertChainCheckers
 * DESCRIPTION:
 *
 *  Sets the ProcessingParams pointed to by "params" with a List of
 *  CertChainCheckers pointed to by "checkers". Each CertChainChecker
 *  represents a custom certificate validation check used by
 *  PKIX_ValidateChain or PKIX_BuildChain as needed during the validation or
 *  building process. If "checkers" is NULL, no CertChainCheckers will be used.
 *
 * PARAMETERS:
 *  "params"
 *      Address of ProcessingParams whose List of CertChainCheckers is to be
 *      set. Must values for any of the
 * http_response arguments, indicating the caller is not interested in
 * those values. If the caller does provide an address, the HttpClient
 * stores at that address a pointer to the corresponding argument, at
 * the completion of the operation.
 *
 * All returned pointers will be owned by the the HttpClient
 * implementation and will remain valid until the call to
 * SEC_HttpRequest_FreeFcn.
 */
typedef SECStatus (*SEC_HttpRequest_TrySendAndReceiveFcn)(
    SEC_HTTP_REQUEST_SESSION request,
    PRPollDesc *d n.  This
 * is also the length of EC private keys and ECDSA signature components
 * r and s.
 *
 * Return 0 on failure (unknown EC domain parameters).
 */
extern int SECKEY_ECParamsToBasePointOrderLen(const SECItem *params);

/*
 * Returns the object identifier of the curve, of the provided
 * elliptic curve parameters structures.
 *
 * Return 0 on failure (unknown EC domain parameters).
 */
SECOidTag SECKEY_GetECCOid(const SECKEYECParams *params);

/* make sure the key length matches the policy for keyType */
SECStatus SECKEY_En" in the List, deletes that item from the list
 *  and moves all subsequent entries to a lower index in the list. If there is
 *  only a single element in the List and that element is deleted, then the
 *  List will be empty.
 *
 * PARAMETERS:
 *  "list"
 *      Address of List to delete from. Must be non-NULL.
 *  "index"
 *      Position in List to delete. Must be less than List's length.
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Not Thread Safe - assumes exclusive access to "list"
 *  (see 
 * specifies additional information that might be useful. Finally, an Error's
 * cause specifies the underlying Error (if any) that resulted in this Error
 * being returned, thereby allowing Errors to be chained so that an entire
 * "error stack trace" can be represented. Once created, an Error is immutable.
 *
 * Note that the Error's supplementary info must be an Object (although any
 * object type), allowing it to be reference-counted and allowing it to
 * provide the standard Object functions (Equals, Hashcode, ToString, CompaON: PKIX_GetLoggers
 * DESCRIPTION:
 *
 *  Retrieves a pointer to the List of Loggers (if any) being used for logging
 *  by libpkix and stores it at "pLoggers". If no loggers are being used, this
 *  function stores an empty List at "pLoggers".
 *
 *  Note that the List returned by this function is immutable.
 *
 * PARAMETERS:
 *  "pLoggers"
 *      Address where object pointer will be stored. Must be non-NULL.
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Conditionally Thread Safe
 *      (see T_Object pointer, callers should assume that this pointer refers to a
 * shared object. Therefore, the caller should treat this shared object as
 * read-only and should not modify this shared object. When done using the
 * shared object, the caller should release the reference to the object by
 * using the PKIX_PL_Object_DecRef function.
 *
 * While a function is executing, if its arguments (or anything referred to by
 * its arguments) are modified, free'd, or destroyed, the function's behavior
 * is undefined.
 *
 */

/* PKIX_Logge0                  0x0005
#define SRTP_NULL_HMAC_SHA1_32                  0x0006

/* DO NOT USE. (deprecated, will be removed) */
#define SSL_HL_ERROR_HBYTES                     3
#define SSL_HL_CLIENT_HELLO_HBYTES              9
#define SSL_HL_CLIENT_MASTER_KEY_HBYTES         10
#define SSL_HL_CLIENT_FINISHED_HBYTES           1
#define SSL_HL_SERVER_HELLO_HBYTES              11
#define SSL_HL_SERVER_VERIFY_HBYTES             1
#define SSL_HL_SERVER_FINISHED_HBYTES           1
#define SSL_HL_REQUEST_CERTIFICATE_HBYTES       2
#defiWITH_AES_128_CBC_SHA256     0x0040
#define TLS_RSA_WITH_CAMELLIA_128_CBC_SHA       0x0041
#define TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA    0x0042
#define TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA    0x0043
#define TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA   0x0044
#define TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA   0x0045
#define TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA   0x0046

#define TLS_DHE_DSS_WITH_RC4_128_SHA            0x0066
#define TLS_DHE_RSA_WITH_AES_128_CBC_SHA256     0x0067
#define TLS_DHE_DSS_WITH_AES_256_CBC_SHA256     0x006A
#definock;
    void *spkDigestInfo;
    CERTStatusConfig *statusConfig;
};

struct NSSCryptoContextStr {
    PRInt32 refCount;
    NSSArena *arena;
    NSSTrustDomain *td;
    NSSToken *token;
    nssSession *session;
    nssCertificateStore *certStore;
};

struct NSSTimeStr {
    PRTime prTime;
};

struct NSSCRLStr {
    nssPKIObject object;
    NSSDER encoding;
    NSSUTF8 *url;
    PRBool isKRL;
};

typedef struct NSSCRLStr NSSCRL;

struct NSSPoliciesStr;

struct NSSAlgorithmAndParametersStr;

struct NSSPKIXCertificateStr;

PR_END_EXTSSCMSCertChainMode;

/* =============================================================================
 * ENVELOPED DATA
 */
struct NSSCMSEnvelopedDataStr {
    SECItem version;
    NSSCMSOriginatorInfo *originatorInfo; /* optional */
    NSSCMSRecipientInfo **recipientInfos;
    NSSCMSContentInfo contentInfo;
    NSSCMSAttribute **unprotectedAttr;
    /* --------- local; not part of encoding --------- */
    NSSCMSMessage *cmsg; /* back pointer to message */
};
#define NSS_CMS_ENVELOPED_DATA_VERSION_REG 0 /* what we *create* */
#de*
 * Supported functions..
 */
#include <pkcs11.h>
#include "nspr.h"
#include "prtypes.h"

typedef enum {
    F_No_Function,
#undef CK_NEED_ARG_LIST
#define CK_PKCS11_FUNCTION_INFO(func) F_##func,
#include "pkcs11f.h"
#undef CK_NEED_ARG_LISt
#undef CK_PKCS11_FUNCTION_INFO
    F_SetVar,
    F_SetStringVar,
    F_NewArray,
    F_NewInitializeArgs,
    F_NewTemplate,
    F_NewMechanism,
    F_BuildTemplate,
    F_SetTemplate,
    F_Print,
    F_SaveVar,
    F_RestoreVar,
    F_Increment,
    F_Decrement,
    F_Delete,
    F_List,
    PUBLIC_MECH_RESERVED_FLAGS 0x87FF0000ul

/* These cipher flags are visible to all other libraries, */
/* But they must be converted before used in functions */
/* withing the security module */
#define PUBLIC_CIPHER_FORTEZZA_FLAG 0x00000001ul

/* warning: reserved means reserved */
#define PUBLIC_CIPHER_RESERVED_FLAGS 0xFFFFFFFEul

SEC_BEGIN_PROTOS

/*
 * the following functions are going to be deprecated in NSS 4.0 in
 * favor of the new stan functions.
 */

/* Initialization */
extern SECMODModule *SECMOD_LoadModule(char *moduleSR_BYTE)) & 0xff)))

/* This runs a function that should return SECSuccess.
 * Intended for NSS internal use only.
 * The return value is asserted in a debug build, otherwise it is ignored.
 * This is no substitute for proper error handling.  It is OK only if you
 * have ensured that the function cannot fail by other means such as checking
 * prerequisites.  In that case this can be used as a safeguard against
 * unexpected changes in a function.
 */
#ifdef DEBUG
#define PORT_CheckSuccess(f) PR_ASSERT((f) == SECSuccess)
#else
#defingle function, and (c) don't need locking.
 *   Use PORT_InitCheapArena() and PORT_DestroyCheapArena() to initialize and
 *   finalize PORTCheapArenaPools.
 *
 * All the other PORT_Arena* functions will operate safely with either
 * subclass.
 */
typedef struct PORTCheapArenaPool_str {
    PLArenaPool arena;
    PRUint32 magic; /* This is used to distinguish the two subclasses. */
} PORTCheapArenaPool;

SEC_BEGIN_PROTOS

extern void *PORT_Alloc(size_t len);
extern void *PORT_Realloc(void *old, size_t len);
extern void *PORT_ZAlloc(sKIX_Int32 inhibitAnySkipCerts;
        PKIX_PL_CertNameConstraints *nameConstraints;
        PKIX_Boolean nameConstraintsAbsent;
        PKIX_Boolean cacheFlag;
        PKIX_CertStore *store;
        PKIX_List *authorityInfoAccess; /* list of PKIX_PL_InfoAccess */
        PKIX_List *subjectInfoAccess; /* list of PKIX_PL_InfoAccess */
        PKIX_Boolean isUserTrustAnchor;
        PKIX_List *crldpList; /* list of CRL DPs based on der in nssCert arena.
                               * Destruction is needed for pkix object and
      s a Fatal Error if the function fails in an unrecoverable way.
 */
PKIX_Error *
PKIX_CertStore_GetTrustCallback(
        PKIX_CertStore *store,
        PKIX_CertStore_CheckTrustCallback *pCallback,
        void *plContext);

/*
 * FUNCTION: PKIX_CertStore_GetCertStoreContext
 * DESCRIPTION:
 *
 *  Retrieves a pointer to the Object representing the context (if any)
 *  of the CertStore pointed to by "store" and stores it at
 *  "pCertStoreContext".
 *
 * PARAMETERS:
 *  "store"
 *      Address of CertStore whose context is to be sto*plContext);

/*
 * FUNCTION: PKIX_CertStore_GetCertCallback
 * DESCRIPTION:
 *
 *  Retrieves a pointer to "store's" Cert callback function and put it in
 *  "pCallback".
 *
 * PARAMETERS:
 *  "store"
 *      The CertStore whose Cert callback is desired. Must be non-NULL.
 *  "pCallback"
 *      Address where Cert callback function pointer will be stored.
 *      Must be non-NULL.
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Thread Safe (see Thread Safety Definitions in Programmer's Guide)
 * RET*      Address where object pointer will be stored. Must be non-NULL.
 *  "plContext"
 *      Platform-specific context pointer.
 * THREAD SAFETY:
 *  Thread Safe
 *
 *  Multiple threads must be able to safely call this function without
 *  worrying about conflicts, even if they're operating on the same object.
 * RETURNS:
 *  Returns NULL if the function succeeds.
 *  Returns a CertStore Error if the function fails in a non-fatal way.
 *  Returns a Fatal Error if the function fails in an unrecoverable way.
 */
PKIX_Error *
PKIX_Ceix Programmer's Guide for detailed information
 * about how to use the libpkix library. Certain key warnings and notices from
 * that document are repeated here for emphasis.
 *
 * All identifiers in this file (and all public identifiers defined in
 * libpkix) begin with "PKIX_". Private identifiers only intended for use
 * within the library begin with "pkix_".
 *
 * A function returns NULL upon success, and a PKIX_Error pointer upon failure.
 *
 * Unless otherwise noted, for all accessor (gettor) functions that return a
 * PKIX_PUnix platforms, or fork check disabled */

#define CHECK_FORK()
#define SKIP_AFTER_FORK(x) x
#define ENABLE_FORK_CHECK()

#ifndef NO_FORK_CHECK
#define NO_FORK_CHECK
#endif

#endif

/*
 * If we were trying to be complete, we would have both FORK_SAFE
 * and non-Fork safe interfaces here. That would require doubling
 * the functions in our function list for both this and the FIPS
 * interface. Since NSS now always asks for a FORK_SAFE interface,
 * and can fall back to a non-FORK_SAFE interface, we set only
 * export one set of inteX_PL_NssContextStruct {
        SECCertificateUsage certificateUsage;
        PLArenaPool *arena;
        void *wincx;
        PKIX_UInt32 timeoutSeconds;
        PKIX_UInt32 maxResponseLength;
        PRTime crlReloadDelay;
        PRTime badDerCrlReloadDelay;
        CERTChainVerifyCallback chainVerifyCallback;
        PKIX_Boolean certSignatureCheck;
};

PKIX_Error *
pkix_pl_NssContext_GetCertUsage
        (PKIX_PL_NssContext *nssContext, SECCertificateUsage *pCertUsage);

/* XXX move the setter into the public header. */
PKIX_E     0x00L
#define PKIX_REV_M_CONTINUE_TESTING_ON_FRESH_INFO    0x20L

/*
 * All Flags are prefixed by PKIX_REV_MI_, where _MI_ indicates
 * this is a method independent flag.
 */

/*
 * This defines the order to checking.
 * EACH_METHOD_SEPARATELY means:
 *      Do all tests related to a particular allowed method
 *      (both local information and network fetching) in a single step.
 *      Only after testing for a particular method is done,
 *      then switching to the next method will happen.
 * ALL_LOCAL_INFORMATION_FIRST meaeturn a boolean that indicates whether the underlying library
 * will perform as the caller expects.
 *
 * The only argument is a string, which should be the version
 * identifier of the NSS library. That string will be compared
 * against a string that represents the actual build version of
 * the SSL library.
 */
extern PRBool NSSSSL_VersionCheck(const char *importedVersion);

/*
 * Returns a const string of the SSL library version.
 */
extern const char *NSSSSL_GetVersion(void);

/* Restart an SSL connection that was paused to dy is used for all self-encryption but is named for
** session tickets for historical reasons.
*/
SSL_IMPORT SECStatus
SSL_SetSessionTicketKeyPair(SECKEYPublicKey *pubKey, SECKEYPrivateKey *privKey);

/*
** Configure a secure server's session-id cache. Define the maximum number
** of entries in the cache, the longevity of the entires, and the directory
** where the cache files will be placed.  These values can be zero, and
** if so, the implementation will choose defaults.
** This version of the function is for use in applications tFailure or SECWouldBlock
 *  they should not be changed.
 *
 * Ownership of pRetCert and pRetKey passes to NSS. The application must not
 * mutate or free the structures after passing them to NSS.
 *
 *  Returning SECWouldBlock will block the handshake until SSL_ClientCertCallbackComplete
 *  is called. Note that references to *caNames should not be kept after SSLGetClientAuthData
 *  returns. Instead, take a copy of the data.
 *
 * See also the comments for SSL_ClientCertCallbackComplete.
 */
typedef SECStatus(PR_CALLBACK *SSLGetCer.
 *
 * libssl does not do any parsing or validation of the response itself.
 */
SSL_IMPORT const SECItem *SSL_PeerSignedCertTimestamps(PRFileDesc *fd);

/* SSL_SetStapledOCSPResponses stores an array of one or multiple OCSP responses
 * in the fd's data, which may be sent as part of a server side cert_status
 * handshake message. Parameter |responses| is for the server certificate of
 * the key exchange type |kea|.
 * The function will duplicate the responses array.
 *
 * Deprecated: see SSL_ConfigSecureServer for details.
 */
S* The function will block until generation is completed.
** The intention is to enforce that fresh and safe parameters are generated
** each time a process is started.
** At the time this API was initially implemented, the API will enable the
** use of 1024 bit DHE parameters. This value might get increased in future
** versions of NSS.
**
** It is allowed to call this API will a NULL value for parameter fd,
** which will prepare the global parameters that NSS will reuse for the remainder
** of the process lifetime. This can be use* including NULL) forcibly disables ALPN.  In this mode, the server will
 * reject any ClientHello that includes the ALPN extension.
 *
 * Calling this function overrides the callback previously set by
 * SSL_SetNextProtoCallback. */
SSL_IMPORT SECStatus SSL_SetNextProtoNego(PRFileDesc *fd,
                                          const unsigned char *data,
                                          unsigned int length);

typedef enum SSLNextProtoState {
    SSL_NEXT_PROTO_NO_SUPPORT = 0, /* No peer support                   */
   et) record
 * header.  Only do this if there are 2^10 or fewer packets in flight at a time;
 * using this with a larger number of packets in flight could mean that packets
 * are dropped if there is reordering.
 *
 * This applies to TLS 1.3 only.  This is not a parameter that is negotiated
 * during the TLS handshake. Unlike other socket options, this option can be
 * changed after a handshake is complete.
 */
#define SSL_ENABLE_DTLS_SHORT_HEADER 36

/*
 * Enables the processing of the downgrade sentinel that can be added to the
 ****************************************
** FUNCTION:    NSSRWLock_AtomicCreate
** DESCRIPTION:
**  Given the address of a NULL pointer to a NSSRWLock,
**  atomically initializes that pointer to a newly created NSSRWLock.
**  Returns the value placed into that pointer, or NULL.
**
** INPUTS:      address of NSRWLock pointer
**              Lock rank
**      Lock name
** OUTPUTS:     NSSRWLock*
** RETURN:      NSSRWLock*
**   If the lock cannot be created because of resource constraints,
**   the pointer will be left NULL.
**
*******.1 definition:
 *
 * CertStatus	::=	CHOICE {
 *	good			[0] IMPLICIT NULL,
 *	revoked			[1] IMPLICIT RevokedInfo,
 *	unknown			[2] IMPLICIT UnknownInfo }
 *
 * (where for now UnknownInfo is defined to be NULL but in the
 * future may be replaced with an enumeration).
 *
 * Because it is CHOICE, the status value and its associated information
 * (if any) are actually encoded together.  To represent this same
 * information internally, we explicitly define a type and save it,
 * along with the value, into a data structure.
 */

typedee signature
 * has been checked against the appropriate data and thus that "status"
 * contains the result of that verification.  If "status" is not SECSuccess,
 * "failureReason" is a copy of the error code that was set at the time;
 * presumably it tells why the signature verification failed.
 */
struct ocspSignatureStr {
    SECAlgorithmID signatureAlgorithm;
    SECItem signature;     /* a BIT STRING */
    SECItem **derCerts;    /* a SEQUENCE OF Certificate */
    CERTCertificate *cert; /* local; not part of encoding */
    PRndif

#define PKIX_PL_CRL_REASONCODE_NOTSET (-1)

struct PKIX_PL_CRLEntryStruct {
        CERTCrlEntry *nssCrlEntry;
        PKIX_PL_BigInt *serialNumber;
        PKIX_List *critExtOids;
        PKIX_Int32 userReasonCode;
        PKIX_Boolean userReasonCodeAbsent;
};

/* see source file for function documentation */

PKIX_Error *pkix_pl_CRLEntry_RegisterSelf(void *plContext);

/* following functions are called by CRL only hence not public */

PKIX_Error *
pkix_pl_CRLEntry_Create(
        CERTCrlEntry **nssCrlEntry, /* head of entry;
};

struct crmfEncoderOutput {
    CRMFEncoderOutputCallback fn;
    void *outputArg;
};

/*
 * This function is used by the API for encoding functions that are
 * exposed through the API, ie all of the CMMF_Encode* and CRMF_Encode*
 * functions.
 */
extern void
crmf_encoder_out(void *arg, const char *buf, unsigned long len,
                 int depth, SEC_ASN1EncodingPart data_kind);

/*
 * This function is used when we want to encode something locally within
 * the library, ie the CertRequest so that we can produce its signaturLONG ulEncryptedPartLen,
  CK_BYTE_PTR pPart,
  CK_ULONG_PTR pulPartLen
)
{
  return __ADJOIN(MODULE_NAME,C_DecryptVerifyUpdate)(hSession, pEncryptedPart, ulEncryptedPartLen, pPart, pulPartLen);
}
#endif /* DECLARE_STRICT_CRYPTOKI_NAMES */

static CK_RV CK_ENTRY
__ADJOIN(MODULE_NAME,C_GenerateKey)
(
  CK_SESSION_HANDLE hSession,
  CK_MECHANISM_PTR pMechanism,
  CK_ATTRIBUTE_PTR pTemplate,
  CK_ULONG ulCount,
  CK_OBJECT_HANDLE_PTR phKey
)
{
  return NSSCKFWC_GenerateKey(fwInstance, hSession, pMechanism, pTemplate, ulCount, phKey);
E hSession,
  CK_BYTE_PTR pData,
  CK_ULONG ulDataLen,
  CK_BYTE_PTR pSignature,
  CK_ULONG_PTR pulSignatureLen
)
{
  return __ADJOIN(MODULE_NAME,C_Sign)(hSession, pData, ulDataLen, pSignature, pulSignatureLen);
}
#endif /* DECLARE_STRICT_CRYPTOKI_NAMES */

static CK_RV CK_ENTRY
__ADJOIN(MODULE_NAME,C_SignUpdate)
(
  CK_SESSION_HANDLE hSession,
  CK_BYTE_PTR pPart,
  CK_ULONG ulPartLen
)
{
  return NSSCKFWC_SignUpdate(fwInstance, hSession, pPart, ulPartLen);
}

#ifdef DECLARE_STRICT_CRYPTOKI_NAMES
CK_RV CK_ENTRY
C_SignUpdate
(
  CKy);
}

#ifdef DECLARE_STRICT_CRYPTOKI_NAMES
CK_RV CK_ENTRY
C_EncryptInit
(
  CK_SESSION_HANDLE hSession,
  CK_MECHANISM_PTR pMechanism,
  CK_OBJECT_HANDLE hKey
)
{
  return __ADJOIN(MODULE_NAME,C_EncryptInit)(hSession, pMechanism, hKey);
}
#endif /* DECLARE_STRICT_CRYPTOKI_NAMES */

static CK_RV CK_ENTRY
__ADJOIN(MODULE_NAME,C_Encrypt)
(
  CK_SESSION_HANDLE hSession,
  CK_BYTE_PTR pData,
  CK_ULONG ulDataLen,
  CK_BYTE_PTR pEncryptedData,
  CK_ULONG_PTR pulEncryptedDataLen
)
{
  return NSSCKFWC_Encrypt(fwInstance, hSession, pData, KFWC_InitToken(fwInstance, slotID, pPin, ulPinLen, pLabel);
}

#ifdef DECLARE_STRICT_CRYPTOKI_NAMES
CK_RV CK_ENTRY
C_InitToken
(
  CK_SLOT_ID slotID,
  CK_CHAR_PTR pPin,
  CK_ULONG ulPinLen,
  CK_CHAR_PTR pLabel
)
{
  return __ADJOIN(MODULE_NAME,C_InitToken)(slotID, pPin, ulPinLen, pLabel);
}
#endif /* DECLARE_STRICT_CRYPTOKI_NAMES */

static CK_RV CK_ENTRY
__ADJOIN(MODULE_NAME,C_InitPIN)
(
  CK_SESSION_HANDLE hSession,
  CK_CHAR_PTR pPin,
  CK_ULONG ulPinLen
)
{
  return NSSCKFWC_InitPIN(fwInstance, hSession, pPin, ulPinLen);
}

#    PKIX_List *checkers,
        PKIX_RevocationChecker *revChecker,
        PKIX_List *buildCheckedExtOIDs,
        PKIX_ProcessingParams *procParams,
        PKIX_UInt32 *pCertCheckedIndex,
        PKIX_UInt32 *pCheckerIndex,
        PKIX_Boolean *pRevChecking,
        PKIX_UInt32 *pReasonCode,
        void **pNBIOContext,
        PKIX_PL_PublicKey **pFinalSubjPubKey,
        PKIX_PolicyNode **pPolicyTree,
        PKIX_VerifyNode **pVerifyTree,
        void *plContext);

#ifdef __cplusplus
}
#endif

#endif /* _PKIX_VALIDATE_H */
 decoding from an ascii string "inStr" to an Item.
 * The length of the input must be provided as "inLen".  The Item
 * may be provided (as "outItemOpt"); you can also pass in a NULL
 * and the Item will be allocated for you.
 *
 * In any case, the data within the Item will be allocated for you.
 * All allocation will happen out of the passed-in "arenaOpt", if non-NULL.
 * If "arenaOpt" is NULL, standard allocation (heap) will be used and
 * you will want to free the result via SECITEM_FreeItem.
 *
 * Return value is NULL on error,C, 0x29, 0xF8, 0xF4, 0x1D, 0xBD, 0x28, 0x9A, 0x14, 0x7C,
                                     0xE9, 0xDA, 0x31, 0x13, 0xB5, 0xF0, 0xB8, 0xC0, 0x0A, 0x60, 0xB1, 0xCE,
                                     0x1D, 0x7E, 0x81, 0x9D, 0x7A, 0x43, 0x1D, 0x7C, 0x90, 0xEA, 0x0E, 0x5F };

static const ECCurveBytes ecCurve_NIST_P384 = {
    "NIST-P384", ECField_GFp, 384,
    irr384, a384, b384, x384, y384, order384, base384,
    1, 192, 98, 48,
    KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT
};

static const PRUint8 irr521[66] = { 0x01, 0xFF, 0xFF,ate[];
extern const SEC_ASN1Template nsslowkey_RSAPublicKeyTemplate[];

/*
 * PKCS #8 attributes
 */
struct NSSLOWKEYAttributeStr {
    SECItem attrType;
    SECItem *attrValue;
};
typedef struct NSSLOWKEYAttributeStr NSSLOWKEYAttribute;

/*
** A PKCS#8 private key info object
*/
struct NSSLOWKEYPrivateKeyInfoStr {
    PLArenaPool *arena;
    SECItem version;
    SECAlgorithmID algorithm;
    SECItem privateKey;
    NSSLOWKEYAttribute **attributes;
};
typedef struct NSSLOWKEYPrivateKeyInfoStr NSSLOWKEYPrivateKeyInfo;
#define NSSLOWMPL/2.0/. */

#ifndef __SEC_ERR_H_
#define __SEC_ERR_H_

#include "utilrename.h"

#define SEC_ERROR_BASE (-0x2000)
#define SEC_ERROR_LIMIT (SEC_ERROR_BASE + 1000)

#define IS_SEC_ERROR(code) \
    (((code) >= SEC_ERROR_BASE) && ((code) < SEC_ERROR_LIMIT))

#ifndef NO_SECURITY_ERROR_ENUM
typedef enum {
    SEC_ERROR_IO = SEC_ERROR_BASE + 0,
    SEC_ERROR_LIBRARY_FAILURE = SEC_ERROR_BASE + 1,
    SEC_ERROR_BAD_DATA = SEC_ERROR_BASE + 2,
    SEC_ERROR_OUTPUT_LEN = SEC_ERROR_BASE + 3,
    SEC_ERROR_INPUT_LEN = SEC_ERROR_BASE + 4,
    S*/
    CK_GENERATOR_FUNCTION ivGen;          /* PKCS #11 iv generator value */
};

/*
 * structure to hold a pointer to a unique PKCS #11 object
 * (pointer to the slot and the object id).
 */
struct PK11GenericObjectStr {
    PK11GenericObject *prev;
    PK11GenericObject *next;
    PK11SlotInfo *slot;
    CK_OBJECT_HANDLE objectID;
    PRBool owner;
};

#define MAX_TEMPL_ATTRS 16 /* maximum attributes in template */

/* This mask includes all CK_FLAGs with an equivalent CKA_ attribute. */
#define CKF_KEY_OPERATION_FLAGS 0x000e7b0kcs11t.h"

#include "nssdevt.h"

/* internal data structures */

/* Traverse slots callback */
typedef struct pk11TraverseSlotStr {
    SECStatus (*callback)(PK11SlotInfo *, CK_OBJECT_HANDLE, void *);
    void *callbackArg;
    CK_ATTRIBUTE *findTemplate;
    int templateCount;
} pk11TraverseSlot;

/* represent a pkcs#11 slot reference counted. */
struct PK11SlotInfoStr {
    /* the PKCS11 function list for this slot */
    void *functionList;
    SECMODModule *module; /* our parent module */
    /* Boolean to indicate the current se we would
 * support more smartcards that way, and then this argument should go away.)
 *
 * "digest" is the actual digest of the data.  It must be provided in
 * the case of detached data or NULL if the content will be included.
 *
 * This function already does all of the stuff specific to S/MIME protocol
 * and local policy; the return value just needs to be passed to
 * SEC_PKCS7Encode() or to SEC_PKCS7EncoderStart() to create the encoded data,
 * and finally to SEC_PKCS7DestroyContentInfo().
 *
 * An error results in a return*
 *  - The "which" values are defined in ciferfam.h (the SMIME_* values,
 *    for example SMIME_DES_CBC_56).
 *  - If "on" is non-zero then the named cipher is enabled, otherwise
 *    it is disabled.  (It is not necessary to call the function for
 *    ciphers that are disabled, however, as that is the default.)
 *
 * If the cipher preference is successfully recorded, SECSuccess
 * is returned.  Otherwise SECFailure is returned.  The only errors
 * are due to failure allocating memory or bad parameters/calls:
 *	SEC_ERROR_XXX ("ession_DigestKey(
    NSSCKFWSession *fwSession,
    NSSCKFWObject *fwKey);

/*
 * nssCKFWSession_UpdateFinal
 * (do a single-step of a cryptographic operation and get the result)
 */
NSS_IMPLEMENT CK_RV
nssCKFWSession_UpdateFinal(
    NSSCKFWSession *fwSession,
    NSSCKFWCryptoOperationType type,
    NSSCKFWCryptoOperationState state,
    CK_BYTE_PTR inBuf,
    CK_ULONG inBufLen,
    CK_BYTE_PTR outBuf,
    CK_ULONG_PTR outBufLen);

/*
 * nssCKFWSession_UpdateCombo
 * (do a combination encrypt/decrypt and sign/digest/verify operat *
nssCKFWMechanism_DeriveKey(
    NSSCKFWMechanism *fwMechanism,
    CK_MECHANISM_PTR pMechanism,
    NSSCKFWSession *fwSession,
    NSSCKFWObject *fwBaseKeyObject,
    CK_ATTRIBUTE_PTR pTemplate,
    CK_ULONG ulAttributeCount,
    CK_RV *pError);

/*
 * NSSCKFWCryptoOperation
 *
 *  -- create/destroy --
 *  nssCKFWCryptoOperation_Create
 *  nssCKFWCryptoOperation_Destroy
 *
 *  -- implement public accessors --
 *  nssCKFWCryptoOperation_GetMDCryptoOperation
 *  nssCKFWCryptoOperation_GetType
 *
 *  -- private accessors --
 *
 * Session
 *
 */
NSS_EXTERN NSSCKFWSession *
nssCKFWToken_OpenSession(
    NSSCKFWToken *fwToken,
    CK_BBOOL rw,
    CK_VOID_PTR pApplication,
    CK_NOTIFY Notify,
    CK_RV *pError);

/*
 * nssCKFWToken_GetMechanismCount
 *
 */
NSS_EXTERN CK_ULONG
nssCKFWToken_GetMechanismCount(
    NSSCKFWToken *fwToken);

/*
 * nssCKFWToken_GetMechanismTypes
 *
 */
NSS_EXTERN CK_RV
nssCKFWToken_GetMechanismTypes(
    NSSCKFWToken *fwToken,
    CK_MECHANISM_TYPE types[]);

/*
 * nssCKFWToken_GetMechanism
 *
 */
NSS_EXTERN NSSCKFWMechanism *
nssCySessionHandle(
    NSSCKFWInstance *fwInstance,
    CK_SESSION_HANDLE hSession);

/*
 * nssCKFWInstance_FindSessionHandle
 *
 */
NSS_EXTERN CK_SESSION_HANDLE
nssCKFWInstance_FindSessionHandle(
    NSSCKFWInstance *fwInstance,
    NSSCKFWSession *fwSession);

/*
 * nssCKFWInstance_CreateObjectHandle
 *
 */
NSS_EXTERN CK_OBJECT_HANDLE
nssCKFWInstance_CreateObjectHandle(
    NSSCKFWInstance *fwInstance,
    NSSCKFWObject *fwObject,
    CK_RV *pError);

/*
 * nssCKFWInstance_ResolveObjectHandle
 *
 */
NSS_EXTERN NSSCKFWObject *
nssCKF
 *
 * PolicyNode Type Definitions
 *
 */

#ifndef _PKIX_POLICYNODE_H
#define _PKIX_POLICYNODE_H

#include "pkix_tools.h"

#ifdef __cplusplus
extern "C" {
#endif

/* This structure reflects the contents of a policy node...
 */
struct PKIX_PolicyNodeStruct {
    PKIX_PL_OID *validPolicy;
    PKIX_List *qualifierSet;    /* CertPolicyQualifiers */
    PKIX_Boolean criticality;
    PKIX_List *expectedPolicySet;       /* OIDs */
    PKIX_PolicyNode *parent;
    PKIX_List *children;                /* PolicyNodes */
    PKIX_UInt32 depth;sage,
                                        unsigned int *retFlags,
                                        SECTrustType *retTrustType);

/*
 * Find all user certificates that match the given criteria.
 *
 *	"handle" - database to search
 *	"usage" - certificate usage to match
 *	"oneCertPerName" - if set then only return the "best" cert per
 *			name
 *	"validOnly" - only return certs that are curently valid
 *	"proto_win" - window handle passed to pkcs11
 */
CERTCertList *CERT_FindUserCertsByUsage(CERTCertDBHandle *handle,
    eneralName *current);

/*
 * Look up name constraints for some certs that do not include name constraints
 * (Most importantly, root certificates)
 *
 * If a matching subject is found, |extensions| will be populated with a copy of
 * the
 * DER-encoded name constraints extension. The data in |extensions| will point
 * to
 * memory that the caller owns.
 *
 * There is no mechanism to configure imposed name constraints right now.  All
 * imposed name constraints are built into NSS.
 */
SECStatus CERT_GetImposedNameConstraints(const S      const SECItem *encodedValue);

/* Decodes a DER encoded crlDistributionPoints extension value into a
** readable format.
**	arena - where to allocate memory for the decoded value
**	der - value to be decoded
**	Returns a CERTCrlDistributionPoints structure which contains the
**          decoded value
*/
extern CERTCrlDistributionPoints *CERT_DecodeCRLDistributionPoints(
    PLArenaPool *arena, SECItem *der);

/* Extract certain name type from a generalName */
extern void *CERT_GetGeneralNameByType(CERTGeneralName *genNames,
        char *url, int type, void *wincx);

extern void CERT_DestroyCrl(CERTSignedCrl *crl);

/* this is a hint to flush the CRL cache. crlKey is the DER subject of
   the issuer (CA). */
void CERT_CRLCacheRefreshIssuer(CERTCertDBHandle *dbhandle, SECItem *crlKey);

/* add the specified DER CRL object to the CRL cache. Doing so will allow
   certificate verification functions (such as CERT_VerifyCertificate)
   to automatically find and make use of this CRL object.
   Once a CRL is added to the CRL cache, the application must hold oR CertRequest attribute list.
*/
SECStatus CERT_GetCertificateRequestExtensions(CERTCertificateRequest *req,
                                               CERTCertExtension ***exts);

/*
** Extract a public key object from a certificate
*/
extern SECKEYPublicKey *CERT_ExtractPublicKey(CERTCertificate *cert);

/*
** Retrieve the Key Type associated with the cert we're dealing with
*/

extern KeyType CERT_GetCertKeyType(const CERTSubjectPublicKeyInfo *spki);

/*
** Initialize the certificate database.  This is called to create
**  t0/. */
/*
 * pkix_pl_date.h
 *
 * Date Object Definitions
 *
 */

#ifndef _PKIX_PL_DATE_H
#define _PKIX_PL_DATE_H

#include "pkix_pl_common.h"

#ifdef __cplusplus
extern "C" {
#endif

struct PKIX_PL_DateStruct{
        PRTime nssTime;
};

/* see source file for function documentation */

PKIX_Error *pkix_pl_Date_ToString_Helper(
        SECItem *nssTime,
        PKIX_PL_String **pString,
        void *plContext);

PKIX_Error *pkix_pl_Date_RegisterSelf(void *plContext);

PKIX_Error *
pkix_pl_Date_GetPRTime(
        PKIX_PL_Date *datFindCrlIssuer(CERTCertDBHandle *dbHandle, SECItem *subject,
                   CERTAuthKeyID *id, PRTime validTime);

/* call back function used in encoding of an extension. Called from
 * SECU_EncodeAndAddExtensionValue */
typedef SECStatus (*EXTEN_EXT_VALUE_ENCODER)(PLArenaPool *extHandleArena,
                                             void *value, SECItem *encodedValue);

#define DECL_EXTEN_EXT_VALUE_ENCODER(mmm)                                \
    SECStatus EXTEN_EXT_VALUE_ENCODER_##mmm(PLArenaPool *extHandleArena, \
      SGenericWrapperDataCallback encode_after,
                                          PRBool isData);

/************************************************************************/
SEC_END_PROTOS

#endif /* _CMS_H_ */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef _SEC_UTIL_H_
#define _SEC_UTIL_H_

#include "seccomon.h"
#include "secitem.h"
#include "secport.h"
#include "prely) would not be returned). This function is a no-op if both
 * retcert and retkey are NULL. Caller inherits ownership of the cert and key
 * he requested (and is responsible to free them).
 */
SECStatus NSS_CMSRecipientInfo_GetCertAndKey(NSSCMSRecipientInfo *ri,
                                             CERTCertificate **retcert,
                                             SECKEYPrivateKey **retkey);

extern int
NSS_CMSRecipientInfo_GetVersion(NSSCMSRecipientInfo *ri);

extern SECItem *
NSS_CMSRecipientInfo_GetEncryptedKey(NS PRTime *stime);

/*
 * Return the signing cert of a CMS signerInfo.
 *
 * the certs in the enclosing SignedData must have been imported already
 */
extern CERTCertificate *
NSS_CMSSignerInfo_GetSigningCertificate(NSSCMSSignerInfo *signerinfo, CERTCertDBHandle *certdb);

/*
 * NSS_CMSSignerInfo_GetSignerCommonName - return the common name of the signer
 *
 * sinfo - signerInfo data for this signer
 *
 * Returns a pointer to allocated memory, which must be freed with PORT_Free.
 * A return value of NULL is an error.
 */
extern char ********/

extern NSSCMSSignedData *
NSS_CMSSignedData_Create(NSSCMSMessage *cmsg);

extern void
NSS_CMSSignedData_Destroy(NSSCMSSignedData *sigd);

/*
 * NSS_CMSSignedData_Encode_BeforeStart - do all the necessary things to a SignedData
 *     before start of encoding.
 *
 * In detail:
 *  - find out about the right value to put into sigd->version
 *  - come up with a list of digestAlgorithms (which should be the union of the algorithms
 *         in the signerinfos).
 *         If we happen to have a pre-set list of algorithms (a_key_cb_arg" - callback function for getting bulk key for encryptedData
 */
extern NSSCMSDecoderContext *
NSS_CMSDecoder_Start(PLArenaPool *poolp,
                     NSSCMSContentCallback cb, void *cb_arg,
                     PK11PasswordFunc pwfn, void *pwfn_arg,
                     NSSCMSGetDecryptKeyCallback decrypt_key_cb, void *decrypt_key_cb_arg);

/*
 * NSS_