CryptoSys PKI Pro  23.0.0
Functions
diCrPKI.h File Reference

The C/C++ interface to the diCrPKI library. More...

Functions

long ASN1_TextDump (const char *szFileOut, const char *szFileOrPEMString, long nOptions)
 Dumps details of ASN.1 formatted data to a text file. More...
 
long ASN1_TextDumpToString (char *szOutput, long nOutChars, const char *szFileOrPEMString, const char *szDirName, long nOptions)
 Dumps details of ASN.1 formatted data to a string. More...
 
long ASN1_Type (char *szOutput, long nOutChars, const char *szFileOrPEMString, long nOptions)
 Describes the type of ASN.1 data. More...
 
long CIPHER_Bytes (long fEncrypt, unsigned char *lpOutput, const unsigned char *lpData, long nDataLen, const unsigned char *lpKey, const unsigned char *lpIV, const char *szAlgAndMode, long nOptions)
 Encrypt or decrypt data in a byte array. More...
 
long CIPHER_DecryptAEAD (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const unsigned char *lpAAD, long nAadLen, long nOptions)
 Decrypt data using an authenticated encryption algorithm. More...
 
long CIPHER_DecryptBytes (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions)
 Decrypt data in a byte array using the specified block cipher algorithm, mode and padding. More...
 
long CIPHER_DecryptHex (char *szOutput, long nOutChars, const char *szInputHex, const char *szKeyHex, const char *szIvHex, const char *szAlgModePad, long nOptions)
 Decrypt data using the specified block cipher algorithm, mode and padding. More...
 
long CIPHER_EncryptAEAD (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const unsigned char *lpAAD, long nAadLen, long nOptions)
 Encrypt data using an authenticated encryption algorithm. More...
 
long CIPHER_EncryptBytes (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions)
 Encrypt data in a byte array using the specified block cipher algorithm, mode and padding. More...
 
long CIPHER_EncryptHex (char *szOutput, long nOutChars, const char *szInputHex, const char *szKeyHex, const char *szIvHex, const char *szAlgModePad, long nOptions)
 Encrypt data using the specified block cipher algorithm, mode and padding. More...
 
long CIPHER_File (long fEncrypt, const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, const unsigned char *lpIV, const char *szAlgAndMode, long nOptions)
 Encrypt or decrypt data in a file using the specified block cipher algorithm and mode. More...
 
long CIPHER_FileDecrypt (const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions)
 Decrypt a file using specified block cipher algorithm, mode and padding. More...
 
long CIPHER_FileEncrypt (const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long nKeyLen, const unsigned char *lpIV, long nIvLen, const char *szAlgModePad, long nOptions)
 Encrypt a file using specified block cipher algorithm, mode and padding. More...
 
long CIPHER_Hex (long fEncrypt, char *szOutput, long nOutChars, const char *szData, const char *szKey, const char *szIV, const char *szAlgAndMode, long nOptions)
 Encrypt or decrypt data represented as a hexadecimal string. More...
 
long CIPHER_KeyUnwrap (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpData, long nDataLen, const unsigned char *lpKek, long nKekLen, long nOptions)
 Unwrap (decrypt) a content-encryption key with a key-encryption key. More...
 
long CIPHER_KeyWrap (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpData, long nDataLen, const unsigned char *lpKek, long nKekLen, long nOptions)
 Wrap a content-encryption key with a key-encryption key. More...
 
long CMS_GetSigDataDigest (char *szOutput, long nOutChars, const char *szFileIn, const char *szCertFile, long nOptions)
 Extracts the message digest from a signed-data CMS object file and verifies the signature. More...
 
long CMS_MakeComprData (const char *szFileOut, const char *szFileIn, long nOptions)
 Creates a new CMS compressed-data file (.p7z) from an existing input file. More...
 
long CMS_MakeDetachedSig (const char *szFileOut, const char *szHexDigest, const char *szCertList, const char *szPrivateKey, long nOptions)
 Creates a "detached signature" CMS signed-data object from a message digest of the content. More...
 
long CMS_MakeEnvData (const char *szFileOut, const char *szFileIn, const char *szCertList, const char *szKeyString, long nCount, long nOptions)
 Create a CMS enveloped-data object for one or more recipients. More...
 
long CMS_MakeEnvDataFromBytes (const char *szFileOut, const unsigned char *lpInput, long nInputLen, const char *szCertList, const char *szKeyString, long nCount, long nOptions)
 Create a CMS enveloped-data object from data in a byte array. More...
 
long CMS_MakeEnvDataFromString (const char *szFileOut, const char *szDataIn, const char *szCertList, const char *szKeyString, long nCount, long nOptions)
 Create a CMS enveloped-data object from an ASCII string. More...
 
long CMS_MakeSigData (const char *szFileOut, const char *szFileIn, const char *szCertList, const char *szPrivateKey, long nOptions)
 Creates a CMS object of type SignedData from an input data file. More...
 
long CMS_MakeSigDataFromBytes (const char *szFileOut, const unsigned char *lpInput, long nInputLen, const char *szCertList, const char *szPrivateKey, long nOptions)
 Create a CMS object of type SignedData from an array of bytes. More...
 
long CMS_MakeSigDataFromSigValue (const char *szFileOut, const unsigned char *lpSigValue, long nSigLen, const unsigned char *lpData, long nDataLen, const char *szCertList, long nOptions)
 Creates a CMS object of type SignedData using a pre-computed signature value. More...
 
long CMS_MakeSigDataFromString (const char *szFileOut, const char *szDataIn, const char *szCertList, const char *szPrivateKey, long nOptions)
 Create a CMS object of type SignedData from an input string. More...
 
long CMS_QueryEnvData (char *szOutput, long nOutChars, const char *szFileIn, const char *szQuery, long nOptions)
 Queries a CMS enveloped-data object file for selected information. More...
 
long CMS_QuerySigData (char *szOutput, long nOutChars, const char *szFileIn, const char *szQuery, long nOptions)
 Queries a CMS signed-data object file for selected information. More...
 
long CMS_ReadComprData (const char *szFileOut, const char *szFileIn, long nOptions)
 Read and extract the decompressed contents of a CMS compressed-data file. More...
 
long CMS_ReadEnvData (const char *szFileOut, const char *szFileIn, const char *szCertFile, const char *szPrivateKey, long nOptions)
 Read and decrypt a CMS enveloped-data object to a file. More...
 
long CMS_ReadEnvDataToBytes (unsigned char *lpOutput, long nOutBytes, const char *szFileIn, const char *szCertFile, const char *szPrivateKey, long nOptions)
 Reads and decrypts CMS enveloped-data object using the recipient's private key writing the plaintext data directly into a byte array. More...
 
long CMS_ReadEnvDataToString (char *szOutput, long nOutChars, const char *szFileIn, const char *szCertFile, const char *szPrivateKey, long nOptions)
 Reads and decrypts CMS enveloped-data object using the recipient's private key writing the plaintext data directly into a string. More...
 
long CMS_ReadSigData (const char *szFileOut, const char *szFileIn, long nOptions)
 Reads the content from a CMS signed-data object file. More...
 
long CMS_ReadSigDataToBytes (unsigned char *lpOutput, long nOutBytes, const char *szFileIn, long nOptions)
 Reads the content from a CMS signed-data object file directly into a byte array. More...
 
long CMS_ReadSigDataToString (char *szOutput, long nOutChars, const char *szFileIn, long nOptions)
 Reads the content from a CMS signed-data object file directly into a string. More...
 
long CMS_VerifySigData (const char *szFileIn, const char *szCertFile, const char *szHexDigest, long nOptions)
 Verifies the signature and content of a signed-data CMS object file. More...
 
long CNV_B64Filter (char *szOutput, const char *szInput, long nStrLen)
 Removes non-base64 characters from a string. More...
 
long CNV_B64StrFromBytes (char *szOutput, long nOutChars, const unsigned char *lpInput, long nInputLen)
 Encodes an array of bytes into a base64-encoded string. More...
 
long CNV_Base58FromBytes (char *szOutput, long nOutChars, const unsigned char *lpInput, long nInputLen)
 Encodes an array of bytes into a base58-encoded string. More...
 
long CNV_Base58ToBytes (unsigned char *lpOutput, long nOutBytes, const char *szInput)
 Decodes a base58-encoded string into an array of bytes. More...
 
long CNV_ByteEncoding (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nBytes, long nOptions)
 Converts encoding of byte array between UTF-8 and Latin-1. More...
 
long CNV_BytesFromB64Str (unsigned char *lpOutput, long nOutBytes, const char *szInput)
 Decodes a base64-encoded string into an array of Bytes. More...
 
long CNV_BytesFromHexStr (unsigned char *lpOutput, long nOutBytes, const char *szInput)
 Decodes a hexadecimal-encoded string into an array of Bytes. More...
 
long CNV_CheckUTF8 (const char *szInput)
 Checks if a string only contains valid UTF-8 characters. More...
 
long CNV_CheckUTF8Bytes (const unsigned char *lpInput, long nBytes)
 Checks if a byte array contains valid UTF-8 characters. More...
 
long CNV_CheckUTF8File (const char *szFileName)
 Checks if a file contains valid UTF-8 characters. More...
 
long CNV_HexFilter (char *szOutput, const char *szInput, long nStrLen)
 Removes non-hexadecimal characters from a string. More...
 
long CNV_HexStrFromBytes (char *szOutput, long nOutChars, const unsigned char *lpInput, long nInputLen)
 Encodes an array of bytes into a hexadecimal-encoded string. More...
 
long CNV_Latin1FromUTF8 (char *szOutput, long nOutChars, const char *szInput)
 Converts a UTF-8 string into a Latin-1 string, if possible. More...
 
long CNV_Latin1FromUTF8Bytes (char *szOutput, long nOutChars, const unsigned char *lpInput, long nBytes)
 Converts UTF-8 encoded array of bytes into a Latin-1 string, if possible. More...
 
long CNV_NumFromBytes (const unsigned char *lpInput, long nBytes, long nOptions)
 Converts the leftmost four bytes of an array to a 32-bit integer. More...
 
long CNV_NumToBytes (unsigned char *lpOutput, long nOutBytes, long nNumber, long nOptions)
 Converts a 32-bit integer to an array of 4 bytes. More...
 
long CNV_ReverseBytes (unsigned char *lpOutput, const unsigned char *lpInput, long nBytes)
 Reverses the order of a byte array. More...
 
long CNV_ShortPathName (char *szOut, long nOutChars, const wchar_t *szwFilePath)
 Retrieve the Windows short path form of the specified path. More...
 
long CNV_UTF8BytesFromLatin1 (unsigned char *lpOutput, long nOutBytes, const char *szInput)
 Converts a string of 8-bit Latin-1 characters into a UTF-8 encoded array of bytes. More...
 
long CNV_UTF8FromLatin1 (char *szOutput, long nOutChars, const char *szInput)
 Converts a string of 8-bit Latin-1 characters into UTF-8 format. More...
 
long CNV_Utf8FromWide (char *szOut, long nOutChars, const wchar_t *wstr)
 Maps a UTF-16 (wide character) string to a UTF-8-encoded string. More...
 
long COMPR_Compress (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nOptions)
 Compress data using zlib compression. More...
 
long COMPR_Uncompress (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nOptions)
 Uncompress data using zlib compression. More...
 
long ECC_DHSharedSecret (unsigned char *lpZZ, long nOutBytes, const char *szIntPrivateKey, const char *szIntPublicKey, long nOptions)
 Compute EC Diffie-Hellman (ECDH) shared secret. More...
 
long ECC_KeyHashCode (const char *szKeyString)
 Computes the hash code of an "internal" ECC public or private key string. More...
 
long ECC_MakeKeys (const char *szPubKeyFile, const char *szPriKeyFile, const char *szCurveName, const char *szPassword, const char *szParams, long nOptions)
 Generates an EC public/private key pair and saves as two key files. More...
 
long ECC_PublicKeyFromPrivate (char *szOutput, long nOutChars, const char *szIntKeyString, long nOptions)
 Converts an internal EC private key string into an internal EC public key string. More...
 
long ECC_QueryKey (char *szOutput, long nOutChars, const char *szIntKeyString, const char *szQuery, long nOptions)
 Queries an EC key string for selected information. More...
 
long ECC_ReadKeyByCurve (char *szOutput, long nOutChars, const char *szHexKey, const char *szCurveName, long nOptions)
 Reads an EC key from its hexadecimal (base16) representation. More...
 
long ECC_ReadPrivateKey (char *szOutput, long nOutChars, const char *szKeyFileOrString, const char *szPassword, long nOptions)
 Reads an EC private key from a file into an internal key string. More...
 
long ECC_ReadPublicKey (char *szOutput, long nOutChars, const char *szKeyFileOrString, long nOptions)
 Reads an EC public key from a file into an internal key string. More...
 
long ECC_SaveEncKey (const char *szFileOut, const char *szIntKeyString, const char *szPassword, const char *szParams, long nOptions)
 Saves an internal EC private key string to an encrypted private key file. More...
 
long ECC_SaveKey (const char *szFileOut, const char *szIntKeyString, long nOptions)
 Saves an internal EC key string to an unencrypted key file. More...
 
long HASH_Bytes (unsigned char *lpOutput, long nOutBytes, const void *lpMessage, long nMsgLen, long nOptions)
 Creates a message digest hash as a byte array from byte data. More...
 
long HASH_File (unsigned char *lpOutput, long nOutBytes, const char *szFileName, long nOptions)
 Creates a message digest hash in byte format for a file. More...
 
long HASH_HexFromBytes (char *szOutput, long nOutChars, const void *lpMessage, long nMsgLen, long nOptions)
 Creates a message digest hash in hexadecimal format from byte (or string) data. More...
 
long HASH_HexFromFile (char *szOutput, long nOutChars, const char *szFileName, long nOptions)
 Creates a message digest hash in hexadecimal format for a file. More...
 
long HASH_HexFromHex (char *szOutput, long nOutChars, const char *szMsgHex, long nOptions)
 Creates a message digest hash in hexadecimal format from data in a hexadecimal-encoded string. More...
 
long HASH_Length (long nAlgId)
 Return length of message digest output in bytes. More...
 
long HMAC_Bytes (unsigned char *lpOutput, long nOutBytes, const void *lpMessage, long nMsgLen, const void *lpKey, long nKeyLen, long nOptions)
 Creates a keyed-hash based message authentication code (HMAC) as a byte array from byte data. More...
 
long HMAC_HexFromBytes (char *szOutput, long nOutChars, const void *lpMessage, long nMsgLen, const void *lpKey, long nKeyLen, long nOptions)
 Creates a keyed-hash based message authentication code (HMAC) in hexadecimal format from byte data. More...
 
long HMAC_HexFromHex (char *szOutput, long nOutChars, const char *szMsgHex, const char *szKeyHex, long nOptions)
 Creates a keyed-hash based message authentication code (HMAC) in hexadecimal format from data in hexadecimal-encoded strings. More...
 
long HPKE_DerivePrivateKey (char *szOutput, long nOutChars, const unsigned char *lpIkm, long nIkmLen, const char *szCurveName, const char *szParams, long nOptions)
 Derive an EC private key in a deterministic manner from input keying material using the DeriveKeyPair algorithm in RFC9180. More...
 
long HPKE_LabeledExpand (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpPrk, long nPrkLen, const char *szLabel, const unsigned char *lpInfo, long nInfoLen, const char *szCurveName, const char *szParams, long nOptions)
 Compute the output of the LabeledExpand function as defined in RFC9180. More...
 
long HPKE_LabeledExtract (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpSalt, long nSaltLen, const char *szLabel, const unsigned char *lpIkm, long nIkmLen, const char *szCurveName, const char *szParams, long nOptions)
 Compute the output of the LabeledExtract function as defined in RFC9180. More...
 
long KDF_Bytes (unsigned char *lpOutput, long nOutBytes, const void *lpIKM, long nIkmLen, const void *lpInfo, long nInfoLen, const char *szParams, long nOptions)
 Generate a key-encryption key (KEK) from input keying material using a key derivation function (KDF). More...
 
long KDF_ForCms (unsigned char *lpOutput, long nOutBytes, const void *lpZZ, long nZzLen, const void *lpUkm, long nUkmLen, const char *szParams, long nOptions)
 Generate a key-encryption key (KEK) for ECDH key exchange in a CMS EnvelopedData object. More...
 
long OCSP_MakeRequest (char *szOutput, long nOutChars, const char *szIssuerCert, const char *szCertFileOrSerialNum, const char *szExtensions, long nOptions)
 Creates an Online Certification Status Protocol (OCSP) request as a base64 string. More...
 
long OCSP_ReadResponse (char *szOutput, long nOutChars, const char *szResponseFile, const char *szIssuerCert, const char *szExtensions, long nOptions)
 Reads a response to an Online Certification Status Protocol (OCSP) request and outputs the main results in text form. More...
 
long PAD_BytesBlock (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nBlkLen, long nOptions)
 Creates an input block suitably padded for encryption by a block cipher in ECB or CBC mode. More...
 
long PAD_HexBlock (char *szOutput, long nOutChars, const char *szInput, long nBlkLen, long nOptions)
 Creates a hex-encoded input block suitably padded for encryption by a block cipher in ECB or CBC mode. More...
 
long PAD_UnpadBytes (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nBlkLen, long nOptions)
 Removes the padding from an encryption block. More...
 
long PAD_UnpadHex (char *szOutput, long nOutChars, const char *szInput, long nBlkLen, long nOptions)
 Removes the padding from a hex-encoded encryption block. More...
 
long PBE_Kdf2 (unsigned char *lpOutput, long nOutputLen, const unsigned char *lpPwd, long nPwdLen, const unsigned char *lpSalt, long nSaltLen, long nCount, long nOptions)
 Derives a key of any length from a password using the PBKDF2 algorithm from PKCS #5. More...
 
long PBE_Kdf2Hex (char *szOutput, long nMaxChars, long dkBytes, const char *szPwd, const char *szSaltHex, long nCount, long nOptions)
 Derives a key of any length from a password using the PBKDF2 algorithm from PKCS #5 with the salt and output derived key encoded in hexadecimal. More...
 
long PBE_Scrypt (unsigned char *lpDerivedKey, long nKeyLen, const unsigned char *lpPwd, long nPwdLen, const unsigned char *lpSalt, long nSaltLen, long nParamN, long nParamR, long nParamP, long nOptions)
 Derives a key of any length from a password using the SCRYPT algorithm. More...
 
long PBE_ScryptHex (char *szOutput, long nMaxChars, long dkBytes, const char *szPwd, const char *szSaltHex, long nParamN, long nParamR, long nParamP, long nOptions)
 Derives a key of any length from a password using the SCRYPT algorithm with the salt and derived key encoded in hexadecimal. More...
 
long PEM_FileFromBinFile (const char *szFileOut, const char *szFileIn, const char *szHeader, long nLineLen)
 Creates a PEM file from a binary file . More...
 
long PEM_FileFromBinFileEx (const char *szFileOut, const char *szFileIn, const char *szHeader, long nLineLen, long nOptions)
 Creates a PEM file from a binary file with extended options. More...
 
long PEM_FileToBinFile (const char *szFileOut, const char *szFileIn)
 Converts the contents of a PEM file into a binary file. More...
 
long PFX_MakeFile (const char *szFileOut, const char *szCertList, const char *szEpkFile, const char *szPassword, const char *szFriendlyName, long nOptions)
 Creates a simple PFX (PKCS-12) file from an X.509 certificate and (optional) encrypted private key file. More...
 
long PFX_VerifySig (const char *szFileName, const char *szPassword, long nOptions)
 Verifies the signature in a pkcs-12 file. More...
 
long PKI_CompileTime (char *szOutput, long nOutChars)
 Retrieves the date and time the toolkit executable was last compiled. More...
 
long PKI_ErrorCode (void)
 Returns the error code of the first error that occurred when calling the last function. More...
 
long PKI_ErrorLookup (char *szOutput, long nOutChars, long nErrCode)
 Retrieves the error message associated with a given error code. More...
 
long PKI_FormatErrorMessage (char *szOutput, long nOutChars, long nErrCode, const char *szUserMsg)
 Return a formatted error message string for the last error. More...
 
long PKI_LastError (char *szOutput, long nOutChars)
 Retrieves the last error message set by the toolkit. More...
 
long PKI_LicenceType (long nOptions)
 Returns the ASCII value of the licence type. More...
 
long PKI_ModuleInfo (char *szOutput, long nOutChars, long nOptions)
 Get additional information about the core DLL module. More...
 
long PKI_ModuleName (char *szOutput, long nOutChars, long nOptions)
 Retrieves the name of the current process's module. More...
 
long PKI_Platform (char *szOutput, long nOutChars)
 Gets the platform the core DLL was compiled for. More...
 
long PKI_PowerUpTests (long nOptions)
 Carries out on demand the full set of power-up tests automatically performed by the toolkit when first powered up (i.e. More...
 
long PKI_Version (void *nReserved1, void *nReserved2)
 Retrieves the release version number. More...
 
long PRF_Bytes (unsigned char *lpOutput, long nOutBytes, const void *lpMessage, long nMsgLen, const void *lpKey, long nKeyLen, const char *szCustom, long nOptions)
 Generate output bytes using a pseudorandom function (PRF). More...
 
long PWD_Prompt (char *szPassword, long nPwdLen, const char *szCaption)
 Prompts for a password in a dialog box. More...
 
long PWD_PromptEx (char *szPassword, long nPwdLen, const char *szCaption, const char *szPrompt, long nOptions)
 Prompts for a password in a dialog box with option to change prompt wording. More...
 
long RNG_Bytes (unsigned char *lpOutput, long nOutBytes, const void *lpSeed, long nSeedLen)
 Generates a random set of byte data suitable for cryptographic keys. More...
 
long RNG_BytesWithPrompt (unsigned char *lpOutput, long nOutBytes, const char *szPrompt, long nOptions)
 Generates a random set of byte data suitable for cryptographic keys with a prompt for the user to enter random keystrokes and mouse movements. More...
 
long RNG_Guid (char *szOutput, long nOutChars, long nOptions)
 Generate a random 36-character Global Unique IDentifier (GUID) string. More...
 
long RNG_Initialize (const char *szSeedFile, long nOptions)
 Initializes the RNG generator with a seed file. More...
 
long RNG_MakeSeedFile (const char *szSeedFile, const char *szPrompt, long nOptions)
 Creates a new seed file suitable for use with RNG_Initialize(). More...
 
long RNG_Number (long nLower, long nUpper)
 Returns an integer selected at random between specified limits. More...
 
long RNG_Test (const char *szFileOut, long nOptions)
 Carries out a NIST SP800-90 health check and FIPS140-2 statistical tests on the random number generator. More...
 
long RNG_TestDRBGVS (char *szOutput, long nMaxChars, long nReturnedBitsLen, const char *szEntropyInput, const char *szNonce, const char *szPersonalizationString, const char *szAdditionalInput1, const char *szEntropyReseed, const char *szAdditionalInputReseed, const char *szAdditionalInput2, long nOptions)
 Test the RNG for conformance to NIST SP800-90A using the relevant test specified in DRBGVS. More...
 
long RNG_UpdateSeedFile (const char *szSeedFile, long nOptions)
 Updates an RNG seed file. More...
 
long RSA_CheckKey (const char *szKeyString, long nOptions)
 Checks if an RSA key is valid. More...
 
long RSA_DecodeMsg (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nOptions)
 Decodes an EME or EMSA encoded message block according to PKCS#1 (EME = Encoding Method for Encryption, EMSA = Encoding Method for Signature with Appendix). More...
 
long RSA_Decrypt (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const char *szPrivateKeyFile, const char *szPassword, const char *szParameters, long nOptions)
 Decrypt a message encrypted using an RSA encryption scheme. More...
 
long RSA_EncodeMsg (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, long nOptions)
 Creates an EME or EMSA encoded message block according to PKCS#1 (EME = Encoding Method for Encryption, EMSA = Encoding Method for Signature with Appendix). More...
 
long RSA_Encrypt (unsigned char *lpOutput, long nOutBytes, const unsigned char *lpInput, long nInputLen, const char *szPublicKeyFile, const char *szParameters, long nOptions)
 Encrypt a short message using RSA encryption. More...
 
long RSA_FromXMLString (char *szOutput, long nOutChars, const char *szXmlString, long nOptions)
 Creates an RSA key string in internal format from an XML string. More...
 
long RSA_GetPrivateKeyFromPFX (const char *szFileOut, const char *szPfxFile, long nOptions)
 Extracts an encrypted private key from a PKCS-12 PKCS8ShroudedKeyBag, saving the output directly as a new file. More...
 
long RSA_GetPublicKeyFromCert (char *szOutput, long nOutChars, const char *szCertFile, long nOptions)
 Reads a public key from an X.509 certificate into an "internal" public key string. More...
 
long RSA_KeyBits (const char *szKeyString)
 Returns the length of key in bits given the public or private key string. More...
 
long RSA_KeyBytes (const char *szKeyString)
 Returns the length of key in complete bytes (octets) given the public or private key string. More...
 
long RSA_KeyHashCode (const char *szKeyString)
 Computes the hash code of an "internal" RSA public or private key string. More...
 
long RSA_KeyMatch (const char *szPrivateKey, const char *szPublicKey)
 Verifies that a pair of "internal" RSA private and public key strings are matched. More...
 
long RSA_KeyValue (char *szOutput, long nOutChars, const char *szKeyString, const char *szFieldName, long nOptions)
 Extracts a base64-encoded RSA key value from internal key string. More...
 
long RSA_MakeKeys (const char *szPubKeyFile, const char *szEpkFile, long nBits, long nExpFermat, long nTests, long nCount, const char *szPassword, const void *lpSeed, long nSeedLen, long nOptions)
 Generate an RSA key pair and save as two key files. More...
 
long RSA_MakeKeysXtd (const char *szPubKeyFile, const char *szPriKeyFile, const char *szPassword, long nBits, long nExpFermat, const char *szParams, long nOptions)
 Generate an RSA key pair and save as two key files. More...
 
long RSA_PublicKeyFromPrivate (char *szOutput, long nOutChars, const char *szKeyString, long nOptions)
 Converts an internal RSA private key string into an internal public key string. More...
 
long RSA_RawPrivate (unsigned char *lpData, long nDataLen, const char *szPrivateKey, long nOptions)
 Transforms (that is, encrypts or decrypts) raw data using an RSA private key. More...
 
long RSA_RawPublic (unsigned char *lpData, long nDataLen, const char *szPublicKey, long nOptions)
 Transforms (that is, encrypts or decrypts) raw data using an RSA public key. More...
 
long RSA_ReadAnyPrivateKey (char *szOutput, long nOutChars, const char *szKeyFileOrString, const char *szPassword, long nOptions)
 Reads from a file or string containing a private key into an "internal" private key string. More...
 
long RSA_ReadAnyPublicKey (char *szOutput, long nOutChars, const char *szKeyFileOrString, long nOptions)
 Reads from a file or string containing a public key into an "internal" public key string. More...
 
long RSA_ReadEncPrivateKey (char *szOutput, long nOutChars, const char *szEpkFile, const char *szPassword, long nOptions)
 Reads from an encrypted PKCS#8 private key info file into an "internal" private key string. More...
 
long RSA_ReadPrivateKeyFromPFX (char *szOutput, long nOutChars, const char *szPfxFile, const char *szPassword, long nOptions)
 Reads a private key directly from an encrypted PFX/PKCS-12 file into an "internal" private key string. More...
 
long RSA_ReadPrivateKeyInfo (char *szOutput, long nOutChars, const char *szKeyFile, long nOptions)
 Reads from an (unencrypted) PKCS-8 private key info file into an "internal" private key string. More...
 
long RSA_ReadPublicKey (char *szOutput, long nOutChars, const char *szPubKeyFile, long nOptions)
 Reads from an RSA public key file into an "internal" public key string. More...
 
long RSA_SaveEncKey (const char *szFileOut, const char *szIntKeyString, const char *szPassword, const char *szParams, long nOptions)
 Save an internal RSA key string to an encrypted key file. More...
 
long RSA_SaveEncPrivateKey (const char *szFileOut, const char *szKeyString, long nCount, const char *szPassword, long nOptions)
 Saves a private key string to a PKCS-8 encrypted private key info file. More...
 
long RSA_SavePrivateKeyInfo (const char *szFileOut, const char *szKeyString, long nOptions)
 Saves a private key string to an (unencrypted) PKCS-8 private key info file. More...
 
long RSA_SavePublicKey (const char *szFileOut, const char *szKeyString, long nOptions)
 Saves a public key string to PKCS-1 public key file. More...
 
long RSA_ToXMLString (char *szOutput, long nOutChars, const char *szKeyString, long nOptions)
 Creates an XML string representation of an RSA internal key string. More...
 
long RSA_ToXMLStringEx (char *szOutput, long nOutChars, const char *szKeyString, const char *szPrefix, long nOptions)
 Creates an XML string representation of an RSA internal key string with option to add a namespace prefix. More...
 
long SIG_SignData (char *szOutput, long nOutChars, const unsigned char *lpData, long nDataLen, const char *szKeyFile, const char *szPassword, const char *szAlgName, long nOptions)
 Compute a signature value over data in a byte array. More...
 
long SIG_SignFile (char *szOutput, long nOutChars, const char *szDataFile, const char *szKeyFile, const char *szPassword, const char *szAlgName, long nOptions)
 Compute a signature value over data in a file. More...
 
long SIG_VerifyData (const char *szSignature, const unsigned char *lpData, long nDataLen, const char *szCertOrKeyFile, const char *szAlgName, long nOptions)
 Verify a signature value over data in a byte array. More...
 
long SIG_VerifyFile (const char *szSignature, const char *szDataFile, const char *szCertOrKeyFile, const char *szAlgName, long nOptions)
 Verify a signature value over data in a file. More...
 
long SMIME_Extract (const char *szFileOut, const char *szFileIn, long nOptions)
 Extract the body from an S/MIME entity. More...
 
long SMIME_Query (char *szOutput, long nOutChars, const char *szFileIn, const char *szQuery, long nOptions)
 Query an S/MIME entity. More...
 
long SMIME_Wrap (const char *szFileOut, const char *szFileIn, const char *szFeatures, long nOptions)
 Wrap a CMS object in an S/MIME entity. More...
 
long TDEA_B64Mode (char *szOutput, const char *szInput, const char *szKey, long fEncrypt, const char *szMode, const char *szIV)
 Encrypts or decrypts data encoded in base64 using a specified mode. More...
 
long TDEA_BytesMode (unsigned char *lpOutput, const unsigned char *lpData, long nDataLen, const unsigned char *lpKey, long fEncrypt, const char *szMode, const unsigned char *lpIV)
 Encrypts or decrypts an array of Bytes in one step using a specified mode. More...
 
long TDEA_File (const char *szFileOut, const char *szFileIn, const unsigned char *lpKey, long fEncrypt, const char *szMode, const unsigned char *lpIV)
 Encrypts or decrypts a file using a specified mode. More...
 
long TDEA_HexMode (char *szOutput, const char *szInput, const char *szKey, long fEncrypt, const char *szMode, const char *szIV)
 Encrypts or decrypts data represented as a hexadecimal string using a specified mode. More...
 
long WIPE_Data (void *lpData, long nDataLen)
 Zeroise data in memory. More...
 
long WIPE_File (const char *szFileName, long nOptions)
 Wipe and delete a file using secure 7-pass DOD standards. More...
 
long X509_CertExpiresOn (const char *szCertFile, char *szOutput, long nOutChars, long nOptions)
 Returns the date and time an X.509 certificate expires. More...
 
long X509_CertIssuedOn (const char *szCertFile, char *szOutput, long nOutChars, long nOptions)
 Returns the date and time an X.509 certificate was issued. More...
 
long X509_CertIssuerName (const char *szCertFile, char *szOutput, long nOutChars, const char *szDelim, long nOptions)
 Extracts issuer's distinguished name from X.509 certificate. More...
 
long X509_CertIsValidNow (const char *szCertFile, long nOptions)
 Verifies that an X.509 certificate is currently valid. More...
 
long X509_CertRequest (const char *szNewReqFile, const char *szPriKeyFile, const char *szDistName, const char *szExtensions, const char *szPassword, long nOptions)
 Creates a PKCS #10 certificate signing request (CSR) using the subject's private key file. More...
 
long X509_CertSerialNumber (const char *szCertFile, char *szOutput, long nOutChars, long nOptions)
 Returns the serial number of an X.509 certificate. More...
 
long X509_CertSubjectName (const char *szCertFile, char *szOutput, long nOutChars, const char *szDelim, long nOptions)
 Extracts subject's distinguished name from X.509 certificate. More...
 
long X509_CertThumb (const char *szCertFile, char *szOutput, long nOutChars, long nOptions)
 Calculates the thumbprint (message digest hash) of an X.509 certificate. More...
 
long X509_CheckCertInCRL (const char *szCertFile, const char *szCrlFile, const char *szCRLIssuerCert, const char *szDate, long nOptions)
 Checks whether an X.509 certificate has been revoked in a Certificate Revocation List (CRL). More...
 
long X509_GetCertCountInP7Chain (const char *szP7cFile, long nOptions)
 Return number of certificates in a PKCS-7 "certs-only" certificate chain file. More...
 
long X509_GetCertFromP7Chain (const char *szNewCertFile, const char *szP7cFile, long nIndex, long nOptions)
 Extracts an X.509 certificate from a PKCS-7 "certs-only" certificate chain file (typically saved with extension .p7c or .p7b), saving the output directly as a new file. More...
 
long X509_GetCertFromPFX (const char *szNewCertFile, const char *szPfxFile, const char *szPassword, long nOptions)
 Extracts an X.509 certificate from a PKCS-12 PFX/.p12 file, saving the output directly as a new file. More...
 
long X509_HashIssuerAndSN (const char *szCertFile, char *szOutput, long nOutChars, long nOptions)
 Returns the message digest hash of the PKCS #7 issuerAndSerialNumber value of an X.509 certificate in hexadecimal format. More...
 
long X509_KeyUsageFlags (const char *szCertFile)
 Returns a bitfield containing the keyUsage flags for an X.509 certificate. More...
 
long X509_MakeCert (const char *szNewCertFile, const char *szIssuerCertFile, const char *szSubjectPubKeyFile, const char *szIssuerPriKeyFile, long nCertNum, long nYearsValid, const char *szDistName, const char *szExtensions, long nKeyUsageFlags, const char *szPassword, long nOptions)
 Creates an X.509 certificate using subject's public key and issuer's private key files. More...
 
long X509_MakeCertSelf (const char *szNewCertFile, const char *szPriKeyFile, long nCertNum, long nYearsValid, const char *szDistName, const char *szExtensions, long nKeyUsageFlags, const char *szPassword, long nOptions)
 Creates a self-signed X.509 certificate. More...
 
long X509_MakeCRL (const char *szCrlFile, const char *szIssuerCert, const char *szIssuerKeyFile, const char *szPassword, const char *szRevokedCertList, const char *szExtensions, long nOptions)
 Creates an X.509 Certificate Revocation List (CRL). More...
 
long X509_QueryCert (char *szOutput, long nOutChars, const char *szCertFile, const char *szQuery, long nOptions)
 Queries an X.509 certificate file for selected information. More...
 
long X509_ReadCertStringFromP7Chain (char *szOutput, long nOutChars, const char *szP7cFile, long nIndex, long nOptions)
 Reads an X.509 certificate into a base64 string from PKCS-7 "certs-only" data. More...
 
long X509_ReadCertStringFromPFX (char *szOutput, long nOutChars, const char *szPfxFile, const char *szPassword, long nOptions)
 Reads an X.509 certificate into a base64 string from PKCS-12 PFX/.p12 data. More...
 
long X509_ReadStringFromFile (char *szOutput, long nOutChars, const char *szCertFile, long nOptions)
 Creates a base64 string of an X.509 certificate file. More...
 
long X509_SaveFileFromString (const char *szNewCertFile, const char *szCertString, long nOptions)
 Creates an X.509 certificate file from its base64 string representation. More...
 
long X509_TextDump (const char *szFileOut, const char *szCertFile, long nOptions)
 Dumps details of an X.509 certificate (or a X.509 certificate revocation list (CRL) or a PKCS-10 certificate signing request (CSR)) to a text file. More...
 
long X509_TextDumpToString (char *szOutput, long nOutChars, const char *szCertFile, long nOptions)
 Dumps details of an X.509 certificate or a X.509 certificate revocation list (CRL) or a PKCS-10 certificate signing request (CSR) to a string. More...
 
long X509_ValidatePath (const char *szCertListOrP7File, const char *szTrustedCert, long nOptions)
 Validates a certificate path. More...
 
long X509_VerifyCert (const char *szCertToVerify, const char *szIssuerCert, long nOptions)
 Verifies that an X.509 certificate - or X.509 certificate revocation list (CRL) or PKCS-10 certificate signing request (CSR) - has been signed by its issuer. More...
 
long XOF_Bytes (unsigned char *lpOutput, long nOutBytes, const void *lpMessage, long nMsgLen, long nOptions)
 Generate bytes using an extendable output function (XOF). More...
 

Detailed Description

The C/C++ interface to the diCrPKI library.

Type conventions
The convention here is to use the char type for null-terminated strings, denoted szFoo, and the unsigned char for byte arrays, denoted lpBar. Byte arrays must have their length specified in a separate variable, typically named nBarLen.
Allocation for output strings and byte arrays
The user is responsible for allocating memory for any string or byte array variable that receives output. For a string output buffer, the user must allocate one extra byte for the zero terminating byte.
long nchars;
char *szOut;
// Find out how many bytes we need
nchars = CNV_B64StrFromBytes(NULL, 0, lpData, nDataLen);
if (nchars <= 0) error();
// Pre-dimension, i.e allocate memory for string buffer
szOut = malloc(nchars+1); // NB +1
if (!szOut) error();
nchars = CNV_B64StrFromBytes(szOut, nchars, lpData, nDataLen);
// ...
// do something with szOut...
// ...
free(szOut);
long CNV_B64StrFromBytes(char *szOutput, long nOutChars, const unsigned char *lpInput, long nInputLen)
Encodes an array of bytes into a base64-encoded string.
A byte array output buffer is made the exact required size.
long nbytes;
unsigned char *lpOut;
// Find out how many bytes we need
nbytes = CNV_BytesFromB64Str(NULL, 0, szSig64);
if (nbytes <= 0) error();
// Pre-dimension, i.e allocate memory for buffer
lpOut = malloc(nbytes);
if (!lpOut) error();
nbytes = CNV_BytesFromB64Str(lpOut, nbytes, szSig64);
// ...
// do something with lpOut...
// ...
free(lpOut);
long CNV_BytesFromB64Str(unsigned char *lpOutput, long nOutBytes, const char *szInput)
Decodes a base64-encoded string into an array of Bytes.
Base64 alternative for X.509 certificates
Those X.509 functions which require you to pass the filename of an X.509 certificate will also accept a base64 string representation of the certificate instead. This is the base64 string that can be obtained using the X509_ReadStringFromFile() function. The first character in such a string should always be an "M".
szCertFile = "MIHgMIGaAgEBMA0GCSqG...";

You can also pass a string containing the certificate in PEM format. PEM format looks like
-----BEGIN CERTIFICATE-----
MIHgMIGaAgEBMA0GCSqG...
-----END CERTIFICATE-----
PEM string alternative for X.509 certificates, RSA keys, etc
In the same way you can pass a base64 string instead of an X.509 filename, you can pass a string containing the certificate in PEM format. The PEM format looks like
-----BEGIN CERTIFICATE-----
MIHgMIGaAgEBMA0GCSqG...
-----END CERTIFICATE-----
Similarly, those RSA functions which require you to pass the filename of an RSA key file will accept a string that contains the file contents in PEM format. An RSA key file in PEM format looks like
-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICojAcBgoqhkiG9w0BDAEDMA4ECHPQz6NdAmoFAgIH0ASCAoBKn9KXr+dm
Vtc0ZhEog7t3Prs4rJazwUsXExU78ePLMquxLi/cPmqtyjb472r6XUOa...
-----END ENCRYPTED PRIVATE KEY-----
The functions will accept all strings that start with "-----BEGIN" and are of the form
-----BEGIN XXX-----
(base64-encoded data)
-----END XXX-----
The exact word or words used for "XXX" do not matter, but there must be exactly 5 dash characters "-" before and after. Any non-base64 characters found in the encoded data, including newline characters or spaces, will be ignored.
Error codes:
Possible error codes are:
0 = OK, success, no error (SUCCESS_NO_ERROR)
1 = Cannot open input file (OPEN_ERROR)
2 = Cannot create output file (CREATE_ERROR)
3 = File read error (READ_ERROR)
4 = File write error (WRITE_ERROR)
5 = Not enough memory (MEMORY_ERROR)
6 = Parameter is wrong or missing (BAD_PARAM_ERROR)
7 = Data in wrong format (BAD_FORMAT_ERROR)
8 = Invalid data (INVALID_DATA_ERROR)
9 = Unexpected end of file found (EOF_ERROR)
10 = Required data not found (MISSING_ERROR)
11 = Value out of range (OUT_OF_RANGE_ERROR)
12 = Duplicate data (DUP_ERROR)
13 = Misc file IO error (IO_ERROR)
14 = Unexpected NULL value (NULL_ERROR)
15 = Decryption error (DECRYPT_ERROR)
16 = Item has expired or is not yet valid (EXPIRED_ERROR)
17 = Invalid option (BAD_FLAG_ERROR)
18 = Failed to wipe data (WIPE_ERROR)
19 = Item is not supported (NOT_SUPPORTED_ERROR)
20 = No data found to process (NO_DATA_ERROR)
21 = No match found (NO_MATCH_ERROR)
22 = Signature is invalid (SIGNATURE_ERROR)
23 = Failed a test e.g. known answer test (TEST_FAILED_ERROR)
24 = Key generation failed (KEYGEN_FAILED_ERROR)
25 = Certificate issuer error (ISSUER_ERROR)
26 = Data not a valid length (BAD_LENGTH_ERROR)
27 = Invalid XML format (BAD_XML_ERROR)
29 = Not a valid query (BAD_QUERY_ERROR)
30 = Not enough room in output buffer (SHORT_BUF_ERROR)
31 = Zlib compression error (ZLIB_COMPR_ERROR)
33 = Invalid key length (BAD_KEY_LEN_ERROR)
34 = Invalid block length (BAD_BLK_LEN_ERROR)
35 = Invalid mode (BAD_MODE_ERROR)
36 = Invalid key (BAD_KEY_ERROR)
37 = Invalid initialization vector (BAD_IV_ERROR)
38 = Invalid IV length (BAD_IV_LEN_ERROR)
39 = Unable to encode (ENCODING_ERROR)
42 = Item has been revoked (REVOCATION_ERROR)
43 = Certificate path is invalid (CERT_PATH_ERROR)
201 = PRNG: Cannot open input file (PRNG_ERR_FILE_OPEN)
202 = PRNG: Cannot create output file (PRNG_ERR_FILE_CREATE)
203 = PRNG: File read error (PRNG_ERR_FILE_READ)
204 = PRNG: File write error (PRNG_ERR_FILE_WRITE)
205 = PRNG: File locking error (PRNG_ERR_FILE_LOCK)
210 = PRNG: Uninstantiation failed (PRNG_ERR_UNINST)
211 = PRNG: Requested length is too large (PRNG_ERR_TOOBIG)
212 = PRNG: Function failed (PRNG_ERR_FAILURE)
213 = PRNG: Invalid input parameter (PRNG_ERR_BADPARAM)
214 = PRNG: Function is not available (PRNG_ERR_NOTAVAIL)
299 = PRNG: Catastrophic failure (PRNG_ERR_CATASTROPHIC)
9745 = Something not expected to happen has happened (INTERNAL_ERROR)
9999 = Miscellaneous error (MISC_ERROR)
To find the error message corresponding to a numerical error code use the PKI_ErrorLookup() function. Use PKI_ErrorCode() to find the error code that occurred when calling the last function. More details on the error can usually be found by using the PKI_LastError() function which outputs a description of the error or errors that have occurred. Be warned that not all errors set this description.

Function Documentation

◆ ASN1_TextDump()

long ASN1_TextDump ( const char *  szFileOut,
const char *  szFileOrPEMString,
long  nOptions 
)

Dumps details of ASN.1 formatted data to a text file.

Parameters
[in]szFileOutfilename of text file to be created.
[in]szFileOrPEMStringfilename of ASN.1 formatted data file to be analyzed (or its base64 representation or PEM string).
[in]nOptionsoption flags:
PKI_ASN1_NOCOMMENTS to hide the comments
PKI_ASN1_ADDLEVELS to show level numbers
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The input may be a binary file in BER/DER format or a text file in PEM or base64-encoded format, or may be passed as a base64 string or as a PEM string.

Only data with an outer SEQUENCE is accepted, which is the rule for all common PKI-related ASN.1 files.

The output is a text file showing the structure of the ASN.1 formatted data. All the bytes in the input are printed in hexadecimal form laid out to show the nested structure of the ASN.1 formatted data together with comments beginning with "--" that give further details about the elements. The length of each object is shown in bytes, for example

30 81 e0  --SEQUENCE/224 bytes

shows the tag (30) and length bytes (81 e0) which begin a SEQUENCE of length 224 bytes, equal to hexadecimal E0 bytes.

Use the PKI_ASN1_NOCOMMENTS option to hide the comments: the resulting hexadecimal output without comments should decode back directly to the original binary file.

◆ ASN1_TextDumpToString()

long ASN1_TextDumpToString ( char *  szOutput,
long  nOutChars,
const char *  szFileOrPEMString,
const char *  szDirName,
long  nOptions 
)

Dumps details of ASN.1 formatted data to a string.

Parameters
[out]szOutputString buffer to receive output.
[in]nOutCharsMaximum number of characters to be received.
[in]szFileOrPEMStringFilename of ASN.1 formatted data file to be analyzed (or its base64 representation or PEM string).
[in]szDirNameDirectory in which to create a temporary file. Specify "" for default = system TEMP directory.
[in]nOptionsoption flags:
PKI_ASN1_NOCOMMENTS to hide the comments
PKI_ASN1_ADDLEVELS to show level numbers
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a nonzero error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The input may be a binary file in BER/DER format or a text file in PEM or base64-encoded format, or may be passed as a base64 string or as a PEM string.

Only data with an outer SEQUENCE is accepted, which is the rule for all common PKI-related ASN.1 files.

The output is a text file showing the structure of the ASN.1 formatted data. All the bytes in the input are printed in hexadecimal form laid out to show the nested structure of the ASN.1 formatted data together with comments beginning with "--" that give further details about the elements. The length of each object is shown in bytes, for example

30 81 e0  --SEQUENCE/224 bytes

shows the tag (30) and length bytes (81 e0) which begin a SEQUENCE of length 224 bytes, equal to hexadecimal E0 bytes.

Use the PKI_ASN1_NOCOMMENTS option to hide the comments: the resulting hexadecimal output without comments should decode back directly to the original binary file.

This function creates a temporary file, by default in the system TEMP directory. This file is locked and is automatically deleted after use. The user can specify a particular directory known to be secure if required. If the specified directory does not exist, the system TEMP directory will be used.

◆ ASN1_Type()

long ASN1_Type ( char *  szOutput,
long  nOutChars,
const char *  szFileOrPEMString,
long  nOptions 
)

Describes the type of ASN.1 data.

Parameters
[out]szOutputstring of sufficient length to receive the output (guaranteed not to be longer than PKI_ASN1_TYPE_MAXCHARS).
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szFileOrPEMStringfilename of ASN.1 formatted data file to be analyzed (or its base64 representation or PEM string).
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The input may be a binary file in BER/DER format or a text file in PEM or base64 format, or may be passed as a base64 string or as a PEM string. The output is a string describing the most likely type of the ASN.1-formatted data, or an empty string ("") if the type cannot be determined. The following types are detected:

Output string valueASN.1 object typeReference
EC PRIVATE KEY ECPrivateKey [RFC5915]
OCSP REQUEST OCSPRequest [RFC6960]
OCSP RESPONSE OCSPResponse [RFC6960]
PKCS1 RSA PRIVATE KEY RSAPrivateKey [RFC3447]
PKCS1 RSA PUBLIC KEY RSAPublicKey [RFC3447]
PKCS10 CERTIFICATE REQUEST CertificationRequest [RFC2986]
PKCS12 PFX PFX [RFC7292]
PKCS7 CERTIFICATE CHAIN ContentInfo [RFC5652]
PKCS7/CMS COMPRESSED DATA ContentInfo [RFC3274]
PKCS7/CMS DATA ContentInfo [RFC5652]
PKCS7/CMS ENVELOPED DATA ContentInfo [RFC5652]
CMS AUTH ENVELOPED DATA ContentInfo [RFC5083]
PKCS7/CMS SIGNED DATA ContentInfo [RFC5652]
PKCS8 ENCRYPTED PRIVATE KEYEncryptedPrivateKeyInfo[RFC5208], [RFC5958]
PKCS8 PRIVATE KEY INFOPrivateKeyInfo[RFC5208], [RFC5958]
PKCS8 ONE ASYMMETRIC KEYOneAsymmetricKey[RFC5958]
PUBLIC KEY INFOSubjectPublicKeyInfo[RFC3279], [RFC5480]
X509 CERTIFICATECertificate[RFC5280]
X509 CRLCertificateList

[RFC5280]

Note that these descriptions are not necessarily those used as labels for PEM formatted files. See PEM_FileFromBinFile and [RFC7468].

◆ CIPHER_Bytes()

long CIPHER_Bytes ( long  fEncrypt,
unsigned char *  lpOutput,
const unsigned char *  lpData,
long  nDataLen,
const unsigned char *  lpKey,
const unsigned char *  lpIV,
const char *  szAlgAndMode,
long  nOptions 
)

Encrypt or decrypt data in a byte array.

The key and initialization vector are given as byte arrays.

Deprecated:
Use CIPHER_EncryptBytes or CIPHER_DecryptBytes instead.
Parameters
[in]fEncryptdirection flag: set as ENCRYPT (True) to encrypt or DECRYPT (False) to decrypt.
[out]lpOutputarray of sufficient length to receive the output.
[in]lpDataarray containing the input data.
[in]nDataLenspecifying the length of the input data in bytes.
[in]lpKeyarray containing the key.
[in]lpIVcontaining the initialization vector (IV), or zero (0) for ECB mode.
[in]szAlgAndModecontaining the block cipher algorithm and mode (see Specifying the algorithm and mode for generic block cipher functions).
[in]nOptionsoption flags.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The algorithm and mode must be specified using either the szAlgAndMode or nOptions parameter (see Specifying the algorithm and mode for generic block cipher functions).

The length of key lpKey must be exactly the required key size, and the length of the IV, if required, exactly the block size. See Valid key and block sizes.

Important: The output array lpOutput must be at least nDataLen bytes long. lpOutput and lpData may be the same.

For ECB and CBC modes, the length of the input data lpInput must be an exact multiple of the block size otherwise a BAD_LENGTH_ERROR error will result. It is the responsibility of the user to provide suitable padding before encrypting in those modes and to remove any padding after decrypting.

◆ CIPHER_DecryptAEAD()

long CIPHER_DecryptAEAD ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
const unsigned char *  lpKey,
long  nKeyLen,
const unsigned char *  lpIV,
long  nIvLen,
const unsigned char *  lpAAD,
long  nAadLen,
long  nOptions 
)

Decrypt data using an authenticated encryption algorithm.

Parameters
[out]lpOutputarray of sufficient length to receive the output.
[in]nOutByteslength of the output buffer in bytes.
[in]lpInputarray containing the input data.
[in]nInputLenlength of the input data in bytes.
[in]lpKeyarray containing the key.
[in]nKeyLenlength of the key in bytes.
[in]lpIVinitialization vector (IV), a.k.a. nonce, if not provided in input.
[in]nIvLenlength of the IV in bytes.
[in]lpAADadditional authenticated data (AAD)
[in]nAadLenlength of the AAD in bytes.
[in]nOptionsoption flags. Must be one of:
PKI_AEAD_AES_128_GCM to use AEAD_AES_128_GCM authenticated encryption algorithm from RFC 5116
PKI_AEAD_AES_256_GCM to use AEAD_AES_256_GCM authenticated encryption algorithm from RFC 5116
PKI_AEAD_AES_192_GCM to use the AES-192-GCM authenticated encryption algorithm in the same manner
PKI_AEAD_CHACHA20_POLY1305 to use the AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC8439)
and optionally add
PKI_IV_PREFIX to expect the IV to be prepended at the start of the input.
Returns
If successful, the return value is the number of bytes required in the output; otherwise it returns a negative error code.
Remarks
The input is expected to be the ciphertext with a 16-byte tag appended ciphertext||Tag, or, if the PKI_IV_PREFIX option is set, then the same but with the 12-byte IV prepended IV||ciphertext||Tag, where || denotes concatenation. If the IV is not prepended to the input, then it must be provided in the lpIV argument. Note that the term "IV" is used here to mean exactly the same as "nonce".

The length of key lpKey must be exactly the required key size in bytes: 16 for PKI_AEAD_AES_128_GCM, 24 for PKI_AEAD_AES_192_GCM, or 32 for PKI_AEAD_AES_256_GCM. It is an error if a PKI_AEAD_ option is not provided in the nOptions argument. In all cases the IV must be exactly 12 bytes (96 bits) and the tag must be exactly 16 bytes (128 bits). If additional authentication data (AAD) was provided during encryption then the exact same AAD data must be provided here.

If nOutBytes is set to zero or lpOutput set to 0 (or NULL in C or ByVal 0& in VBA), the required number of bytes will be returned. This will be either exactly 16 bytes shorter than the length of the input, or exactly 28 bytes shorter if the PKI_IV_PREFIX option is used.

The output buffer lpOutput must not be the same as or overlap with the input lpInput.

◆ CIPHER_DecryptBytes()

long CIPHER_DecryptBytes ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
const unsigned char *  lpKey,
long  nKeyLen,
const unsigned char *  lpIV,
long  nIvLen,
const char *  szAlgModePad,
long  nOptions 
)

Decrypt data in a byte array using the specified block cipher algorithm, mode and padding.

The key and initialization vector are passed as byte arrays.

Parameters
[out]lpOutputarray of sufficient length to receive the output (must be at least as long as the input, see ** in remarks)).
[in]nOutBytesspecifying the length of the output buffer in bytes.
[in]lpInputarray containing the input data.
[in]nInputLenspecifying the length of the input data in bytes.
[in]lpKeyarray containing the key.
[in]nKeyLenthe length of the key in bytes.
[in]lpIVcontaining the initialization vector (IV), or zero (0) or NULL for ECB mode.
[in]nIvLenthe length of the IV in bytes.
[in]szAlgModePadcontaining the block cipher algorithm, mode and padding (see Specifying the algorithm, mode and padding for generic block cipher functions).
[in]nOptionsoption flags:
Zero (0) for default options. Optionally add:
PKI_IV_PREFIX to expect the IV to be prepended before the ciphertext in the input (ignored for ECB mode).
Returns
If successful, the return value is the number of bytes in or required in the output; otherwise it returns a negative error code.
Remarks
The algorithm/mode/padding must be specified using either the szAlgModePad string or nOptions parameter, but not both (see Specifying the algorithm, mode and padding for generic block cipher functions).

The length of key lpKey must be exactly the required key size, and the length of the IV, if required, exactly the block size. See Valid key and block sizes.

[New in v12.3] You can find the required output length in bytes by setting nOutBytes to zero or lpOutput to 0 (or NULL in C or ByVal 0& in VBA). For ECB and CBC cipher modes, the return value is now (as of [v12.3]) the exact length of plaintext after padding has been removed.

** For ECB and CBC cipher modes, any padding must be removed. To specify the length of lpOutput you can either

  1. [ORIGINAL METHOD] specify the output length of lpOutput equal to the length of the input then truncate the result to the correct length.
  2. [NEW in v12.3] do a first pass setting nOutBytes to zero or lpOutput to 0 or NULL to find the exact decrypted length.

See the examples below. In both cases you may need to cope with the special case where the encrypted output is the empty string, a zero-length byte array.

It is an error (DECRYPT_ERROR) if the padding bytes after decryption are not as expected according to the padding method specified. If the cipher mode is ECB or CBC, it is an error (BAD_LENGTH_ERROR) if the length of the input is not an exact multiple of the block size. The input buffer lpInput may point to the same location as the output buffer. If so, the input ciphertext data will be overwritten by the output (and the user must truncate to remove any padding bytes).

Defaults: If padding is not specified then the default padding method depends on the cipher mode: pkcs5padding will be used for ECB and CBC mode and nopadding for all other modes. The default cipher mode is ECB. Thus "aes128" is the same as "aes128/ecb/pkcs5padding".

◆ CIPHER_DecryptHex()

long CIPHER_DecryptHex ( char *  szOutput,
long  nOutChars,
const char *  szInputHex,
const char *  szKeyHex,
const char *  szIvHex,
const char *  szAlgModePad,
long  nOptions 
)

Decrypt data using the specified block cipher algorithm, mode and padding.

The input data, key and initialization vector are all represented as hexadecimal strings.

Parameters
[out]szOutputstring buffer of sufficient length to receive the output.
[in]nOutCharsmaximum number of characters to be received.
[in]szInputHexthe input data in hex format.
[in]szKeyHexthe key in hex format.
[in]szIvHexthe initialization vector (IV) in hex format, ignored for ECB mode or if PKI_IV_PREFIX is used (use "").
[in]szAlgModePadstring specifying the block cipher algorithm, mode and padding (see Specifying the algorithm, mode and padding for generic block cipher functions).
[in]nOptionsoption flags:
Zero (0) for default options. Optionally add:
PKI_IV_PREFIX to expect the IV to be prepended before the ciphertext in the input (not applicable for ECB mode).
Returns
If successful, the return value is the number of characters in or required in the output; otherwise it returns a nonzero error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This is the equivalent of CIPHER_DecryptBytes with all parameters passed as hex-encoded strings instead of byte arrays. It is similar to the CIPHER_Hex function except this accepts variable-length input and copes with padding if required, as well as the option to prepend the IV to the ciphertext.

Any padding will be removed after decryption.

If the PKI_IV_PREFIX option is used, the IV will be expected prepended to the ciphertext in the input.

The algorithm/mode/padding must be specified using either the szAlgModePad string or nOptions parameter, but not both (see Specifying the algorithm, mode and padding for generic block cipher functions).

It is an error (BAD_PARAM_ERROR) to pass the empty string "" as input in szInputHex. The output buffer strOutput should not be the same as the input strInputHex.

CAUTION: be aware of the special case where the output is the empty string "" of length zero.

◆ CIPHER_EncryptAEAD()

long CIPHER_EncryptAEAD ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
const unsigned char *  lpKey,
long  nKeyLen,
const unsigned char *  lpIV,
long  nIvLen,
const unsigned char *  lpAAD,
long  nAadLen,
long  nOptions 
)

Encrypt data using an authenticated encryption algorithm.

Parameters
[out]lpOutputarray of sufficient length to receive the output.
[in]nOutByteslength of the output buffer in bytes.
[in]lpInputarray containing the input data.
[in]nInputLenlength of the input data in bytes.
[in]lpKeyarray containing the key.
[in]nKeyLenlength of the key in bytes.
[in]lpIV(required) initialization vector (IV), a.k.a. nonce.
[in]nIvLenlength of the IV in bytes (must be exactly 12).
[in]lpAAD(optional) additional authenticated data (AAD)
[in]nAadLenlength of the AAD in bytes.
[in]nOptionsoption flags. Must be one of:
PKI_AEAD_AES_128_GCM to use AEAD_AES_128_GCM authenticated encryption algorithm from RFC 5116
PKI_AEAD_AES_256_GCM to use AEAD_AES_256_GCM authenticated encryption algorithm from RFC 5116
PKI_AEAD_AES_192_GCM to use the AES-192-GCM authenticated encryption algorithm in the same manner
PKI_AEAD_CHACHA20_POLY1305 to use the AEAD_CHACHA20_POLY1305 authenticated encryption algorithm (RFC 8439)
and optionally add
PKI_IV_PREFIX to prepend the IV before the ciphertext in the output.
Returns
If successful, the return value is the number of bytes required in the output; otherwise it returns a negative error code.
Remarks
This function carries out authenticated encryption using AES-GCM. In this implementation, the function
must have a fixed-length nonce (IV) of exactly 12 bytes (96 bits) and only creates a fixed-length tag of exactly 16 bytes (128 bits). There is no option to use different lengths for the IV or tag. The tag is automatically appended to the output of the encryption operation. The IV may optionally be prepended to the output using the PKI_IV_PREFIX option flag. Note that the term "IV" is used here to mean exactly the same as "nonce".

The length of key lpKey must be exactly the required key size in bytes: 16 for PKI_AEAD_AES_128_GCM, 24 for PKI_AEAD_AES_192_GCM, or 32 for PKI_AEAD_AES_256_GCM. It is an error if a PKI_AEAD_ option is not provided in the nOptions argument. The length of the IV must be exactly 12 bytes. The user is responsible for providing a unique IV each time the same key is used. Be aware it is a serious security risk if the same IV and key are used to encrypt different plaintexts.

If nOutBytes is set to zero or lpOutput set to 0 (or NULL in C or ByVal 0& in VBA), the required number of bytes will be returned. This will be either exactly 16 bytes longer than the length of the input, or exactly 28 bytes longer if the PKI_IV_PREFIX option is used.

The output buffer lpOutput must not be the same as or overlap with the input lpInput.

◆ CIPHER_EncryptBytes()

long CIPHER_EncryptBytes ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
const unsigned char *  lpKey,
long  nKeyLen,
const unsigned char *  lpIV,
long  nIvLen,
const char *  szAlgModePad,
long  nOptions 
)

Encrypt data in a byte array using the specified block cipher algorithm, mode and padding.

The key and initialization vector are passed as byte arrays.

Parameters
[out]lpOutputarray of sufficient length to receive the output.
[in]nOutBytesspecifying the length of the output buffer in bytes.
[in]lpInputarray containing the input data.
[in]nInputLenspecifying the length of the input data in bytes.
[in]lpKeyarray containing the key.
[in]nKeyLenthe length of the key in bytes.
[in]lpIVcontaining the initialization vector (IV), or zero (0) or NULL for ECB mode.
[in]nIvLenthe length of the IV in bytes.
[in]szAlgModePadcontaining the block cipher algorithm, mode and padding (see Specifying the algorithm, mode and padding for generic block cipher functions).
[in]nOptionsoption flags:
Zero (0) for default options. Optionally add:
PKI_IV_PREFIX to prepend the IV before the ciphertext in the output (ignored for ECB mode).
Returns
If successful, the return value is the number of bytes required in the output; otherwise it returns a negative error code.
Remarks
Padding is added as specified to the input before encryption. The user must allocate an output buffer of the required length, which will always be at least as long as the input, or longer if padding is to be added.

The algorithm/mode/padding must be specified using either the szAlgModePad string or nOptions parameter, but not both (see Specifying the algorithm, mode and padding for generic block cipher functions).

The length of key lpKey must be exactly the required key size, and the length of the IV, if required, exactly the block size. See Valid key and block sizes.

If nOutBytes is set to zero or lpOutput set to 0 (or NULL in C or ByVal 0& in VBA), the required number of bytes will be returned. If the NoPadding option is specified, the required output length will be the same as the input.

Defaults: If padding is not specified then the default padding method depends on the cipher mode: pkcs5padding will be used for ECB and CBC mode and nopadding for all other modes. The default cipher mode is ECB. Thus "aes128" is the same as "aes128/ecb/pkcs5padding".

Note that padding is only needed for ECB or CBC mode where the input length is not a multiple of the block size. It is an error (BAD_LENGTH_ERROR) to specify NoPadding with ECB or CBC mode if the length of the input is not an exact multiple of the block size.

The padding option is ignored for CTR, OFB and CFB modes, which do not need padding. The default nopadding is always used for these modes regardless of what is specified (so just use the default, e.g. "aes128/ctr").

[New in v12.3] Use the PKI_IV_PREFIX to prepend the IV before the ciphertext in the output. This will add the IV before the ciphertext in the form IV||CT. This is the scheme used with block ciphers in XML encryption (see section 5.2 of [XMLENC]) where they use the phrase "The resulting cipher text is prefixed by the IV." It is the responsibility of the receiver to parse this data to recover the IV.

◆ CIPHER_EncryptHex()

long CIPHER_EncryptHex ( char *  szOutput,
long  nOutChars,
const char *  szInputHex,
const char *  szKeyHex,
const char *  szIvHex,
const char *  szAlgModePad,
long  nOptions 
)

Encrypt data using the specified block cipher algorithm, mode and padding.

The input data, key and initialization vector are all represented as hexadecimal strings.

Parameters
[out]szOutputstring buffer of sufficient length to receive the output.
[in]nOutCharsmaximum number of characters to be received.
[in]szInputHexthe input data in hex format.
[in]szKeyHexthe key in hex format.
[in]szIvHexthe initialization vector (IV) in hex format, ignored for ECB mode (use "").
[in]szAlgModePadstring specifying the block cipher algorithm, mode and padding (see Specifying the algorithm, mode and padding for generic block cipher functions).
[in]nOptionsoption flags:
Zero (0) for default options. Optionally add:
PKI_IV_PREFIX to prepend the IV before the ciphertext in the output (ignored for ECB mode).
Returns
If successful, the return value is the number of characters in or required in the output; otherwise it returns a nonzero error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This is the equivalent of CIPHER_EncryptBytes with all parameters passed as hex-encoded strings instead of byte arrays. It is similar to the CIPHER_Hex function except this accepts variable-length input and adds padding if required, as well as the option to prepend the IV to the ciphertext.

Padding is added as specified to the input before encryption. The output will always be at least as long as the input, or longer if padding or a prefixed IV is to be added.

The algorithm/mode/padding must be specified using either the szAlgModePad string or nOptions parameter, but not both (see Specifying the algorithm, mode and padding for generic block cipher functions).

It is an error (BAD_PARAM_ERROR) to pass the empty string "" as input in szInputHex. The output buffer strOutput should not be the same as the input strInputHex.

Use the PKI_IV_PREFIX option to prepend the IV before the ciphertext in the output. This will add the IV before the ciphertext in the form IV||CT. This is the scheme used with block ciphers in XML encryption (see section 5.2 of [XMLENC]) where they use the phrase "The resulting cipher text is prefixed by the IV."

◆ CIPHER_File()

long CIPHER_File ( long  fEncrypt,
const char *  szFileOut,
const char *  szFileIn,
const unsigned char *  lpKey,
const unsigned char *  lpIV,
const char *  szAlgAndMode,
long  nOptions 
)

Encrypt or decrypt data in a file using the specified block cipher algorithm and mode.

Deprecated:
Use CIPHER_FileEncrypt() or CIPHER_FileDecrypt() instead.
Parameters
[in]fEncryptdirection flag: set as ENCRYPT (True) to encrypt or DECRYPT (False) to decrypt.
[in]szFileOutwith the full path name of the output file to be created.
[in]szFileInwith the full path name of the input file to be processed.
[in]lpKeyarray containing the key.
[in]lpIVcontaining the initialization vector (IV), or zero (0) for ECB mode.
[in]szAlgAndModecontaining the block cipher algorithm and mode (see Specifying the algorithm and mode for generic block cipher functions).
[in]nOptionsoption flags.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The key and initialization vector are passed as bytes arrays. PKCS5 padding is used, if required. The algorithm and mode must be specified using either the szAlgAndMode or nOptions parameter (see Specifying the algorithm and mode for generic block cipher functions).

The length of key lpKey must be exactly the required key size, and the length of the IV, if required, exactly the block size. See Valid key and block sizes.

The output file szFileOut will be overwritten without warning. If there is an error, the output file will not exist. The input and output files must not be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of [CMS], which is the same as the padding method in [PKCS7] section 10.3 and [PKCS5] section 6.1.1 and [RFC1423] para 1.1.

◆ CIPHER_FileDecrypt()

long CIPHER_FileDecrypt ( const char *  szFileOut,
const char *  szFileIn,
const unsigned char *  lpKey,
long  nKeyLen,
const unsigned char *  lpIV,
long  nIvLen,
const char *  szAlgModePad,
long  nOptions 
)

Decrypt a file using specified block cipher algorithm, mode and padding.

Parameters
[in]szFileOutwith the full path name of the output file to be created.
[in]szFileInwith the full path name of the input file to be processed.
[in]lpKeyarray containing the key.
[in]nKeyLenspecifying the length of the key in bytes.
[in]lpIVcontaining the initialization vector (IV), if required.
[in]nIvLenspecifying the length of the IV in bytes.
[in]szAlgModePadcontaining the block cipher algorithm, mode and padding (see Specifying the algorithm, mode and padding for generic block cipher functions).
[in]nOptionsoption flags:
Zero (0) for default options. Optionally add:
PKI_IV_PREFIX to expect the IV to be prepended at the start of the file (ignored for ECB mode).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The algorithm/mode/padding must be specified using either the szAlgModePad string or nOptions parameter, but not both (see Specifying the algorithm, mode and padding for generic block cipher functions).

The length of key must be exactly the required key size, and the length of the IV, if required, exactly the block size. See Valid key and block sizes.

The output file szFileOut will be overwritten without warning. If there is an error, the output file will not exist. The input and output files must not be the same.

Prepended IV: If the ciphertext file was created with the IV prepended at the start of the file, then you must specify the PKI_IV_PREFIX option. In this case, the lpIV parameter is ignored and should be set to NULL. The input file is expected to be of the form IV||ciphertext, or IV||ciphertext||tag for AES-GCM.

Defaults: If padding is not specified then the default padding method depends on the cipher mode: pkcs5padding will be used for ECB and CBC mode and nopadding for all other modes. The default cipher mode is ECB. Thus "aes128" is the same as "aes128/ecb/pkcs5padding".

Padding: When decrypting you can specify NoPadding to leave any padding intact in the deciphered file. This is useful if you wish to examine an unknown padding scheme. Otherwise, when decrypting in ECB or CBC mode, you must specify the same padding scheme used when encrypting. It is an error (DECRYPT_ERROR) if the expected padding string is not found after decrypting. The padding parameter is ignored when decrypting in CTR, OFB or CFB mode.

GCM mode: [New in v20.7] Use aes*-gcm to decrypt the file using AES-GCM mode. A 16-byte tag (mac) must be appended at the end of the file. Only a 16-byte tag is supported. The IV must be exactly 12 bytes long for AES-GCM mode. Use the PKI_IV_PREFIX flag to indicate that the IV is at the start of the file.

◆ CIPHER_FileEncrypt()

long CIPHER_FileEncrypt ( const char *  szFileOut,
const char *  szFileIn,
const unsigned char *  lpKey,
long  nKeyLen,
const unsigned char *  lpIV,
long  nIvLen,
const char *  szAlgModePad,
long  nOptions 
)

Encrypt a file using specified block cipher algorithm, mode and padding.

The IV may be prepended to the file, if required.

Parameters
[in]szFileOutwith the full path name of the output file to be created.
[in]szFileInwith the full path name of the input file to be processed.
[in]lpKeyarray containing the key.
[in]nKeyLenspecifying the length of the key in bytes.
[in]lpIVcontaining the initialization vector (IV), if required.
[in]nIvLenspecifying the length of the IV in bytes.
[in]szAlgModePadcontaining the block cipher algorithm, mode and padding (see Specifying the algorithm, mode and padding for generic block cipher functions).
[in]nOptionsoption flags:
Zero (0) for default options. Optionally add:
PKI_IV_PREFIX to prepend the IV before the ciphertext in the output file (ignored for ECB mode).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The algorithm/mode/padding must be specified using either the szAlgModePad string or nOptions parameter, but not both (see Specifying the algorithm, mode and padding for generic block cipher functions).

The length of key must be exactly the required key size, and the length of the IV, if required, exactly the block size. See Valid key and block sizes.

The output file szFileOut will be overwritten without warning. If there is an error, the output file will not exist. The input and output files must not be the same.

Prepended IV: If the PKI_IV_PREFIX option flag is set in nOptions then the IV will be prepended (i.e. added) at the start of the output file. That is, the output file will be of the form IV||ciphertext. The PKI_IV_PREFIX flag is ignored in ECB mode where an IV is not needed.

Defaults: If padding is not specified then the default padding method depends on the cipher mode: pkcs5padding will be used for ECB and CBC mode and nopadding for all other modes. The default cipher mode is ECB. Thus "aes128" is the same as "aes128/ecb/pkcs5padding".

Padding: In normal circumstances you should leave the padding unspecified and use the default padding when encrypting. The only time it should be required is if you want to use an exotic padding like OneAndZeroesPadding instead of pkcs5padding with EBC or CBC mode. Note that, unlike the behaviour with CIPHER_EncryptBytes, it is an error (BAD_PARAM_ERROR) to specify NoPadding when encrypting a file with ECB or CBC mode under any circumstances. The padding option is ignored for CTR, OFB and CFB modes; that is, the default nopadding is always used for these modes regardless of what is specified (so just use the default, e.g. "aes128/ctr").

GCM mode: [New in v21.0] Use aes128-gcm, aes192-gcm or aes256-gcm to encrypt the file using AES-GCM mode. A 16-byte tag (mac) is always appended to the file. The IV must be exactly 12 bytes long for AES-GCM mode. Add the PKI_IV_PREFIX flag to prepend the IV at the start of the output file (this is in accordance with section 5.2.4 of [XMLENC]).

◆ CIPHER_Hex()

long CIPHER_Hex ( long  fEncrypt,
char *  szOutput,
long  nOutChars,
const char *  szData,
const char *  szKey,
const char *  szIV,
const char *  szAlgAndMode,
long  nOptions 
)

Encrypt or decrypt data represented as a hexadecimal string.

The key and initialization vector are represented as a hexadecimal string.

Parameters
[in]fEncryptdirection flag: set as ENCRYPT (True) to encrypt or DECRYPT (False) to decrypt.
[out]szOutputof sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szDatacontaining the input data in hex format.
[in]szKeycontaining the key in hex format.
[in]szIVcontaining the initialization vector (IV) in hex format, or the empty string "" for ECB mode.
[in]szAlgAndModecontaining the block cipher algorithm and mode (see Specifying the algorithm and mode for generic block cipher functions).
[in]nOptionsoption flags.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The algorithm and mode must be specified using either the szAlgAndMode or nOptions parameter (see Specifying the algorithm and mode for generic block cipher functions). All data parameters are expected to be in hexadecimal-encoded format and to be of valid lengths. Valid hexadecimal characters are [0-9A-Fa-f]. The hex-encoded key string szKey must represent a value with a length of exactly the required key size. The hex-encoded initialization vector string szIV, if required, must represent a value with a length of exactly the block size. See Valid key and block sizes.

Important: The output string szOutput must be dimensioned with at least the same number of characters as the input string before calling. The variables szOutput and szInput should be different.

For ECB and CBC modes, the length of the input string szInput must be an exact multiple of the block size encoded in hex characters otherwise a BAD_LENGTH_ERROR error will occur. It is the responsibility of the user to provide suitable padding before encrypting in those modes and to remove any padding after decrypting.

[New in v20.0] Consider using the newer functions CIPHER_EncryptHex and CIPHER_DecryptHex. These functions take a variable length input and add (or remove) the required padding, and provide the option to prepend the IV to the ciphertext.

◆ CIPHER_KeyUnwrap()

long CIPHER_KeyUnwrap ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpData,
long  nDataLen,
const unsigned char *  lpKek,
long  nKekLen,
long  nOptions 
)

Unwrap (decrypt) a content-encryption key with a key-encryption key.

Parameters
[out]lpOutputarray of sufficient length to receive the output.
[in]nOutBytesspecifying the maximum length of the output array.
[in]lpDataarray containing the input data (wrapped key).
[in]nDataLenspecifying the length of the input data in bytes.
[in]lpKekarray containing the key encryption key.
[in]nKekLenspecifying the length of the key encryption key.
[in]nOptionsoption flags:
Select the key wrap algorithm from one of the following:
PKI_KWRAP_AES128 (or PKI_BC_AES128) to use AES128-Wrap
PKI_KWRAP_AES192 (or PKI_BC_AES192) to use AES128-Wrap
PKI_KWRAP_AES256 (or PKI_BC_AES256) to use AES128-Wrap
PKI_KWRAP_3DES (or PKI_BC_3DES) to use cms3DESWrap
Returns
If successful, the return value is the number of bytes in the output; otherwise it returns a negative error code.
Remarks
This unwraps (decrypts) key material using a key encryption key (KEK) and uses either the AES Key Wrap Algorithm from [RFC3394] or the Triple-DES Key Wrap algorithm from [RFC3217]. There is no default algorithm. The algorithm must be specified in the nOptions parameter. To find the required length for the output key material, pass zero as the nOutBytes parameter. This will be 8 bytes less than the input length for AES and 16 bytes less for triple DES. No parity bit checks or changes are made for a Triple-DES key.

◆ CIPHER_KeyWrap()

long CIPHER_KeyWrap ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpData,
long  nDataLen,
const unsigned char *  lpKek,
long  nKekLen,
long  nOptions 
)

Wrap a content-encryption key with a key-encryption key.

Parameters
[out]lpOutputarray of sufficient length to receive the output.
[in]nOutBytesspecifying the maximum length of the output array.
[in]lpDataarray containing the input data (key material).
[in]nDataLenspecifying the length of the input data in bytes.
[in]lpKekarray containing the key encryption key.
[in]nKekLenspecifying the length of the key encryption key.
[in]nOptionsoption flags:
Select the key wrap algorithm from one of the following:
PKI_KWRAP_AES128 (or PKI_BC_AES128) to use AES128-Wrap
PKI_KWRAP_AES192 (or PKI_BC_AES192) to use AES128-Wrap
PKI_KWRAP_AES256 (or PKI_BC_AES256) to use AES128-Wrap
PKI_KWRAP_3DES (or PKI_BC_3DES) to use cms3DESWrap
Returns
If successful, the return value is the number of bytes in the output; otherwise it returns a negative error code.
Remarks
This wraps (encrypts) key material using a key encryption key (KEK) and uses either the AES Key Wrap Algorithm from [RFC3394] or the Triple-DES Key Wrap algorithm from [RFC3217]. There is no default algorithm. The algorithm must be specified in the nOptions parameter. The input data to be wrapped must be a valid length for the underlying data encapsulation mechanism; specifically, at least 16 bytes and a multiple of 8 bytes for AES, or exactly 24 bytes for Triple DES. To find the required length for the output wrapped key, pass zero as the nOutBytes parameter (Hint: an AES-wrapped key is exactly 8 bytes longer than the input; a triple-DES-wrapped key is 16 bytes longer). No parity bit checks or changes are made for a Triple-DES key.

Changed in [v20.5]: Added the explicit key wrap options PKI_KWRAP_* which are different from the old PKI_BC_* options. The old PKI_BC_* options are still accepted for backwards compatibility.

◆ CMS_GetSigDataDigest()

long CMS_GetSigDataDigest ( char *  szOutput,
long  nOutChars,
const char *  szFileIn,
const char *  szCertFile,
long  nOptions 
)

Extracts the message digest from a signed-data CMS object file and verifies the signature.

Parameters
[out]szOutputto receive the message digest output.
[in]nOutCharsspecifying the length of the output string.
[in]szFileInwith name of signed-data CMS object file or the data as a base64 or PEM string.
[in]szCertFilespecifying an (optional) X.509 certificate file to be used to identify the signer.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
Returns
If successful, the return value is a non-negative value indicating the message digest algorithm (CAUTION: this is not the number of characters in the output); otherwise it returns a negative error code.
Remarks
This function extracts the message digest of the signed encapsulated content. In doing so, it also verifies that the signature is valid. The object may be a "detached signature" object. If signed attributes are present, the function will extract the messageDigest attribute for RSA and DSA signature algorithms. If signed attributes are not present, the message digest is extracted directly from the signature value, but only for RSASSA-PKCS1-v1_5 signatures, as the message digest cannot be directly extracted from a DSA or RSA-PSS signature. If given, the function will use the public key from the specified X.509 certificate to validate the signature; otherwise it will use the first valid SignerInfo and certificate pair it finds in the SignedData.

The message digest, if found, is copied into szHexDigest. The maximum expected length of szHexDigest is PKI_MAX_HASH_CHARS characters. ANSI C users must add one to this value when allocating memory. The message digest is encoded in hexadecimal format using lower-case letters [a-f].

The message digest algorithm is indicated by the return code:

CodeAlgorithm
PKI_HASH_SHA1 SHA-1
PKI_HASH_MD5 (1)MD5
PKI_HASH_MD2 (2)MD2
PKI_HASH_SHA256 (3)SHA-256
PKI_HASH_SHA384 (4)SHA-384
PKI_HASH_SHA512 (5)SHA-512
PKI_HASH_SHA224 (6)SHA-224

CAUTION: unlike other hash-related functions, this function does not return the length of the digest string; it returns the code for the digest algorithm.

Note that this does not verify that the message digest is that of the content. It does, however, verify that the message digest was indeed signed by the purported signer, but it does not check the content itself. To verify that the SignedData object is validly signed, the user must extract the content separately and verify that its message digest matches the digest extracted by this function. To do this, use the functions CMS_ReadSigDataToString() and HASH_HexFromBytes(). See the examples below.

Alternatively, use the CMS_VerifySigData() to verify the signature and message digest directly and use CMS_QuerySigData() to extract the messageDigest attribute, if present, without validation.

◆ CMS_MakeComprData()

long CMS_MakeComprData ( const char *  szFileOut,
const char *  szFileIn,
long  nOptions 
)

Creates a new CMS compressed-data file (.p7z) from an existing input file.

Parameters
[in]szFileOutname of output file to be created.
[in]szFileInname of file containing input data.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is zero; otherwise it returns a negative error code.
Remarks
This creates a CMS compressed-data file (conventionally saved with a .p7z extension) using the zlibCompress algorithm. It only works in file-to-file mode. Any existing file with the same name as the parameter szFileOut will be overwritten without warning. Note that it may not produce an exact identical output to that of another program on the same input due to differences in ZLIB buffers and window sizes.

◆ CMS_MakeDetachedSig()

long CMS_MakeDetachedSig ( const char *  szFileOut,
const char *  szHexDigest,
const char *  szCertList,
const char *  szPrivateKey,
long  nOptions 
)

Creates a "detached signature" CMS signed-data object from a message digest of the content.

Parameters
[in]szFileOutwith name of output file to be created.
[in]szHexDigestcontaining the digest of the content in hexadecimal format.
[in]szCertListcontaining the filename of the signer's certificate and (optionally) a list of other certificates to be included in the output, separated by semi-colons (;)
[in]szPrivateKeycontaining the private key data for the signer.
[in]nOptionsoption flags: Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
and optionally add
PKI_CMS_EXCLUDE_CERTS to exclude signer's certificate
PKI_CMS_INCLUDE_ATTRS to add signed attributes (default = no signed attributes) including content-type and message-digest plus any more added below.
PKI_CMS_ADD_SIGNTIME to add SigningTime to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SMIMECAP to add sMIMECapabilities to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SIGNINGCERT to add ESS Signing Certificate attribute to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_FORMAT_BASE64 to format the output with base64 encoding (default output is binary)
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code. Further error information may be available by calling PKI_LastError().
Remarks
RSASSA-PKCS1V1_5 only. See CMS_MakeSigData() for more details. The PKI_CMS_EXCLUDE_DATA option is obviously ignored.

◆ CMS_MakeEnvData()

long CMS_MakeEnvData ( const char *  szFileOut,
const char *  szFileIn,
const char *  szCertList,
const char *  szKeyString,
long  nCount,
long  nOptions 
)

Create a CMS enveloped-data object for one or more recipients.

Parameters
[in]szFileOutname of output file to be created.
[in]szFileInname of file containing input data.
[in]szCertListlist of one or more recipient X.509 certificate filenames, separated by semicolons (;). A certificate's representation in base64 or as a PEM string may be used instead of a filename. Alternatively, specify a single PKCS#7 certificate chain file (.p7c/.p7b).

Special cases: Set as "type=@pwri" to create a single recipientInfo of the PasswordRecipientInfo (pwri) type; or set as "type=@kekri,keyid=<string>" to create a single recipientInfo of the KEKRecipientInfo (kekri) type. See Remarks.

Parameters
[in]szKeyString(formerly szSeed) Use to pass optional additional user key material (ukm) for KDF where KeyAgreement (kari) type or RSA-KEM is used. Or use to pass the password for a pwri type or the key encryption key (KEK) for a kekri type. Either pass a plain ASCII string or use the format "#x<hex-digits>" to pass a string of arbitrary octet values. Required for pwri and kekri types.

Examples: "abc" will pass the 3 bytes (0x61, 0x62, 0x63); "#xdeadbeef01" will pass the 5 bytes (0xde, 0xad, 0xbe, 0xef, 0x01).

Parameters
[in]nCount(formerly nSeedLen) Optional iteration count for KDF in pwri type (default=4096) or tag length for AuthEnvelopedData (in range 12-16, default=16). Otherwise ignored.
[in]nOptionsoption flags: Set as zero (0) to use the defaults rsaEncryption for key transport or ECDH with ANSI-X9.63-KDF using SHA-1 with cms3DESwrap for key agreement; and aes128-CBC for content encryption, and output in binary format. NOTE: some default algorithms [changed in v23.0]

To set the content encryption algorithm (default is aes128-CBC), add one of the following:
PKI_BC_AES128 to use aes128-CBC for content encryption (default as of [v23.0])
PKI_BC_AES192 to use aes192-CBC for content encryption
PKI_BC_AES256 to use aes256-CBC for content encryption
PKI_BC_3DES to use Triple-DES des-EDE3-CBC for content encryption [legacy]
PKI_AEAD_AES_128_GCM to use aes128-GCM for content encryption and authentication
PKI_AEAD_AES_192_GCM to use aes192-GCM for content encryption and authentication
PKI_AEAD_AES_256_GCM to use aes256-GCM for content encryption and authentication
PKI_AEAD_CHACHA20_POLY1305 to use AEAD_CHACHA20_POLY1305 for content encryption and authentication

To set the key transport scheme or key encapsulation mechanism (KEM) for RSA, use one of
PKI_KT_RSAES_PKCS (0) to encrypt the key using the RSAES-PKCS1-v1_5 encryption scheme rsaEncryption (default)
PKI_KT_RSAES_OAEP to encrypt the key using the RSAES-OAEP encryption scheme (see RSA signature and encryption schemes).
PKI_KEM_RSA [New in v23.0] to encrypt the key using the RSA Key Encapsulation Mechanism (RSA-KEM) algorithm (see RSA-KEM).

To select a hash function where applicable, add one of:
PKI_HASH_SHA1 to use SHA-1 (default - CAUTION)
PKI_HASH_SHA224 to use SHA-224
PKI_HASH_SHA256 to use SHA-256 [minimum recommended]
PKI_HASH_SHA384 to use SHA-384
PKI_HASH_SHA512 to use SHA-512

If you have selected PKI_KT_RSAES_OAEP then, optionally, add
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (default = same as encoding hash function set above)

To set the key derivation function (KDF) (where applicable), add one of:
PKI_KDF_X963 to use the ANSI-X9.63-KDF key derivation function (default for ECDH).
PKI_KDF_HKDF to use the HMAC-based Key Derivation Function (HKDF) from [RFC5869]
PKI_KDF_KDF2 to use KDF2 from ANSI-X9.44 [X9-44]
PKI_KDF_KDF3 to use KDF3 from ANSI-X9.44 (default for RSA-KEM)

and add the key wrap algorithm for the ECDH key agreement scheme or the kekri key encryption algorithm or RSA-KEM. Default (0) is to match the key agreement algorithm to the content encryption algorithm:
PKI_KWRAP_3DES to use cms3DESwrap [legacy - only valid if Triple DES used for the content encryption algorithm].
PKI_KWRAP_AES128 to use aes128-wrap
PKI_KWRAP_AES192 to use aes192-wrap
PKI_KWRAP_AES256 to use aes256-wrap

Optionally, add any of the bitflags:
PKI_CMS_FORMAT_BASE64 to encode the output with base64 encoding (default output is binary)
PKI_CMS_ALT_ALGID to use specialist alternative encryption algorithm identifier (see Remarks)
PKI_CMS_BIGFILE to speed up the processing of large files (binary file to binary file only)
PKI_CMS_USE_SKI to use subjectKeyIdentifier (SKI) instead of issuerAndSerialNumber for RecipientInfo [New in v23.0].

Returns
If successful, the return value is the number of successful recipients; otherwise it returns a negative error code.
Remarks
The output is a file containing a CMS EnvelopedData or AuthEnvelopedData object which can be sent as part of an S/MIME message or used directly as a binary .p7m file. The supported objects are those described in CMS Content Types. RecipientInfo types can be KeyTransRecipientInfo (ktri), KeyAgreeRecipientInfo (kari), KEKRecipientInfo (kekri) and PasswordRecipientinfo (pwri). If the content encryption algorithm is an authenticated encryption algorithm (AES*-GCM), then the output will be an Authenticated-Enveloped-Data object (AuthEnvelopedData) as specified in [RFC5083] and [RFC5084].

TL;DR. The RecipientInfo type will be set according to the type of public key in the X.509 certificates. If the certificate has an RSA key, then a key-transport RecipientInfo (ktri) will be created (default PKCS#1v1.5 or RSA-OAEP if flag set). If the certificate contains a supported ECC public key, then a key-agreement type (kari) will be used (default ANSI-X9.63-KDF and keywrap to match the content encryption algorithm, HKDF if flag set). You can pass a list of mixed certificates and the appropriate RecipientInfo type will be chosen for each. There are special cases for KEK and password recipientInfo types - see below.

ktri and kari types

By default, the RecipientInfo type is set automatically depending on the public key found in each certificate in szCertList, one for each certificate. If the public key is RSA (rsaEncryption) then the key transport technique (ktri) will be used to create that particular recipientInfo. If the public key is a supported ECC key, then the standard ECDH ephemeral-static key agreement technique (kari) will be used as per [RFC5753] and [RFC8418].

No checks are made on the validity period of the recipients' X.509 certificates or their key usage attributes. A PKCS#7 certificate chain file may be specified as an argument for szCertList. In which case, all certificates in the chain file will be used as recipients.

It is an error if any specified certificate file in szCertList is missing or corrupted. Call PKI_LastError() to find more details of the errors that occurred.

kekri and pwri types

[New in v20.6] RecipientInfo types KEKRecipientInfo (kekri) and PasswordRecipientinfo (pwri) are supported for a single recipient only. For these types no certificates are required and the szCertList argument must include "type=@kekri" or "type=@pwri", respectively, all characters lower case. In addition, for a kekri type, this argument should be of the form "type=@kekri,keyid=<string>" (Note separated by a comma ',') where the value for the keyid attribute is used to set the keyIdentifier field in the KEKIdentifier. This can be a simple ASCII string or can use the format "#x<hex-digits>" to pass a string of arbitrary octet values. If omitted, the default keyIdentifier is "keyid". Optionally add a date field in the KEKIdentifier by adding a date=<iso-date-string>, e.g. "type=@kekri,keyid=ourkeyid,date=2022-07-31T12:01".

The szKeyString argument must include either the key encryption key (KEK) for kekri or the password for pwri. This parameter is expected to be an ASCII string. A binary KEK may be passed by using the format "#x<hex-digits>" to pass a string of arbitrary octet values.

Examples

nRet = CMS_MakeEnvData("xscipher_kekri.p7m", "plain.txt", "type=@kekri,keyid=oursharedkey", 
    "#x0123456789ABCDEFF0E1D2C3B4A59687", 0, PKI_BC_AES192 Or PKI_KWRAP_AES128);

Creates an EnvelopedData file with a single recipientInfo of type KEKRecipientInfo (kekri) with a keyid of "oursharedkey" using the 128-bit KEK (0x)0123456789ABCDEFF0E1D2C3B4A59687 wrapped with aes128-wrap. The content is encrypted with AES-192 using a random content encryption key.

nRet = CMS_MakeEnvData("xscipher_pwri.p7m", "plain.txt", "type=@pwri", 
    "This is my password", 6666, PKI_BC_AES256);

Creates an EnvelopedData file with a single recipientInfo of type PasswordRecipientinfo (pwri) using the password "This is my password". The iteration count for the KDF is 6666 (default=4096). The content is encrypted with AES-256 using a random content encryption key.

Other options

Use the PKI_CMS_BIGFILE option flag to handle large files more efficiently. This results in improvements of speed typically of 30% and enables, in theory, unlimited sizes of enveloped files (subject, of course, to your level of boredom in waiting for the output). Binary output only. Not available for authenticated encryption or kekri or pwri recipientInfo types.

Specialist Option: If the PKI_CMS_ALT_ALGID option flag is present, an alternative Content Encryption Algorithm Identifier will be used as follows:

Default Content Encryption Algorithm Identifier with PKI_CMS_ALT_ALGID
des-ede3-cbc (1.2.840.113549.3.7)des_3CBC_pad (1.3.36.3.1.3.2.1)

This alternative TeleTrusT algorithm identifier was added for compatibility with certain (superseded?) German Health profiles.

◆ CMS_MakeEnvDataFromBytes()

long CMS_MakeEnvDataFromBytes ( const char *  szFileOut,
const unsigned char *  lpInput,
long  nInputLen,
const char *  szCertList,
const char *  szKeyString,
long  nCount,
long  nOptions 
)

Create a CMS enveloped-data object from data in a byte array.

Parameters
[in]szFileOutname of output file to be created.
[in]lpInputbyte array containing the input data.
[in]nInputLenlength in bytes of input data.
[in]szCertListlist of one or more recipient X.509 certificate filenames, separated by semicolons (;). A certificate's representation in base64 or as a PEM string may be used instead of a filename. Alternatively, specify a single PKCS#7 certificate chain file (.p7c/.p7b).

Special cases: Set as "type=@pwri" to create a single recipientInfo of the PasswordRecipientInfo (pwri) type; or set as "type=@kekri,keyid=<string>" to create a single recipientInfo of the KEKRecipientInfo (kekri) type. See Remarks.

Parameters
[in]szKeyString(formerly szSeed) Use to pass optional additional user key material (ukm) for KDF where KeyAgreement (kari) type is used. Or use to pass the password for a pwri type or the key encryption key (KEK) for a kekri type. Either pass a plain ASCII string or use the format "#x<hex-digits>" to pass a string of arbitrary octet values. Required for pwri and kekri types.

Examples: "abc" will pass the 3 bytes (0x61, 0x62, 0x63); "#xdeadbeef01" will pass the 5 bytes (0xde, 0xad, 0xbe, 0xef, 0x01).

Parameters
[in]nCount(formerly nSeedLen) Optional iteration count for KDF in pwri type (default=4096) or tag length for AuthEnvelopedData (in range 12-16, default=16). Otherwise ignored.
[in]nSeedLenformerly used for length of the seed string. No longer used. [IGNORED!]
[in]nOptionsoption flags: see the options in CMS_MakeEnvData.
Returns
If successful, the return value is the number of successful recipients; otherwise it returns a negative error code.
Remarks
This function is the same as CMS_MakeEnvData except the input data is in a byte array instead of a file.

See the remarks for CMS_MakeEnvData() above.

Use this function if the plaintext contains non-ASCII characters such as UTF-8 encoded.

◆ CMS_MakeEnvDataFromString()

long CMS_MakeEnvDataFromString ( const char *  szFileOut,
const char *  szDataIn,
const char *  szCertList,
const char *  szKeyString,
long  nCount,
long  nOptions 
)

Create a CMS enveloped-data object from an ASCII string.

Parameters
[in]szFileOutname of output file to be created.
[in]szDataInstring containing input data.
[in]szCertListlist of one or more recipient X.509 certificate filenames, separated by semicolons (;). A certificate's representation in base64 or as a PEM string may be used instead of a filename. Alternatively, specify a single PKCS#7 certificate chain file (.p7c/.p7b).

Special cases: Set as "type=@pwri" to create a single recipientInfo of the PasswordRecipientInfo (pwri) type; or set as "type=@kekri,keyid=<string>" to create a single recipientInfo of the KEKRecipientInfo (kekri) type. See Remarks.

Parameters
[in]szKeyString(formerly szSeed) Use to pass optional additional user key material (ukm) for KDF where KeyAgreement (kari) type is used. Or use to pass the password for a pwri type or the key encryption key (KEK) for a kekri type. Either pass a plain ASCII string or use the format "#x<hex-digits>" to pass a string of arbitrary octet values. Required for pwri and kekri types.

Examples: "abc" will pass the 3 bytes (0x61, 0x62, 0x63); "#xdeadbeef01" will pass the 5 bytes (0xde, 0xad, 0xbe, 0xef, 0x01).

Parameters
[in]nCount(formerly nSeedLen) Optional iteration count for KDF in pwri type (default=4096) or tag length for AuthEnvelopedData (in range 12-16, default=16). Otherwise ignored.
[in]nOptionsoption flags: see the options in CMS_MakeEnvData.
Returns
If successful, the return value is the number of successful recipients; otherwise it returns a negative error code.
Remarks
This function is the same as CMS_MakeEnvData except the input data is in an ASCII string instead of a file.

See the remarks for CMS_MakeEnvData() above. Use this function only when the plaintext is only plain ASCII text, otherwise use CMS_MakeEnvDataFromBytes.

◆ CMS_MakeSigData()

long CMS_MakeSigData ( const char *  szFileOut,
const char *  szFileIn,
const char *  szCertList,
const char *  szPrivateKey,
long  nOptions 
)

Creates a CMS object of type SignedData from an input data file.

Parameters
[in]szFileOutname of output file to be created.
[in]szFileInname of file containing message data to be signed.
[in]szCertListfilename of the signer's certificate and (optionally) a list of other certificates to be included in the output, separated by semi-colons (;). Alternatively specify a single PKCS#7 certificate chain file (.p7c/.p7b) containing the signer's certificate.
[in]szPrivateKeyprivate key data for the sender in "internal" string format.
[in]nOptionsOption flags. Select one of:
PKI_SIG_RSA_SHA1 (0) to use RSASSA-PKCS-v1_5 with SHA-1 (sha1WithRSAEncryption) (default - CAUTION)
PKI_SIG_RSA_SHA224 to use RSASSA-PKCS-v1_5 with SHA-224 (sha224WithRSAEncryption)
PKI_SIG_RSA_SHA256 to use RSASSA-PKCS-v1_5 with SHA-256 (sha256WithRSAEncryption) [minimum recommended]
PKI_SIG_RSA_SHA384 to use RSASSA-PKCS-v1_5 with SHA-384 (sha384WithRSAEncryption)
PKI_SIG_RSA_SHA512 to use RSASSA-PKCS-v1_5 with SHA-512 (sha512WithRSAEncryption)
PKI_SIG_RSA_MD5 to use RSASSA-PKCS-v1_5 with MD5 (md5WithRSAEncryption) [legacy, not recommended for new implementations]
PKI_SIG_RSA_PSS_SHA1 to use RSASSA-PSS with SHA-1
PKI_SIG_RSA_PSS_SHA224 to use RSASSA-PSS with SHA-224
PKI_SIG_RSA_PSS_SHA256 to use RSASSA-PSS with SHA-256
PKI_SIG_RSA_PSS_SHA384 to use RSASSA-PSS with SHA-384
PKI_SIG_RSA_PSS_SHA512 to use RSASSA-PSS with SHA-512
PKI_SIG_ECDSA_SHA1 to use ecdsaWithSHA1
PKI_SIG_ECDSA_SHA224 to use ecdsaWithSHA224
PKI_SIG_ECDSA_SHA256 to use ecdsaWithSHA256
PKI_SIG_ECDSA_SHA384 to use ecdsaWithSHA384
PKI_SIG_ECDSA_SHA512 to use ecdsaWithSHA512
PKI_SIG_ED25519 to use Ed25519 [New in v20.0]
PKI_SIG_ED448 to use Ed448 [New in v22.0]

And optionally add any combination of the following flags:
PKI_CMS_EXCLUDE_CERTS to exclude signer's certificate
PKI_CMS_EXCLUDE_DATA to exclude the eContent data
PKI_CMS_CERTS_ONLY to create a "certs-only" PKCS#7 certficate chain
PKI_CMS_USE_SKI to use subjectKeyIdentifier (SKI) instead of issuerAndSerialNumber for SignerIdentifier [New in v23.0].
PKI_CMS_INCLUDE_ATTRS to add signed attributes (default = no signed attributes) including content-type and message-digest plus any more added below.
PKI_CMS_FORMAT_BASE64 to format the output with base64 encoding (default output is binary)
PKI_CMS_NO_OUTER to create a "naked" SignedData object with no outerContentInfo as permitted by PKCS#7 v1.6 (specialist option)
PKI_CMS_ALT_ALGID to use an alternative signature algorithm identifier (see Remarks)
PKI_CMS_BIGFILE to speed up the processing of large files (see Remarks)
PKI_PSS_SALTLEN_ZERO to set the salt length to be zero (RSASSA-PSS only, default = same length as the output of the hash function)
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (RSASSA-PSS only, default = same as signature hash function)
PKI_CMS_PSEUDOSIG to create a create a "pseudo" SignedData object with a dummy placeholder signature (see Remarks)
PKI_CMS_ADD_SIGNER to add a new signer to an existing SignedData object [New in v23.0] (see Remarks)

If the PKI_CMS_INCLUDE_ATTRS option flag is included, optionally add any of the following:
PKI_CMS_ADD_SIGNTIME to add SigningTime to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SMIMECAP to add sMIMECapabilities to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SIGNINGCERT to add an ESS Signing Certificate Attribute to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS) [New in v12.4]
PKI_CMS_ADD_ALGPROTECT to add an Algorithm Identifier Protection Attribute to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS) [New in v12.4]
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code. Further error information may be available by calling PKI_LastError().
Remarks
A SignedData CMS object with a single SignerInfo is created with the message data included by default in the eContent.

The signer's certificate must be included in the certificate list. All certificates in the list will be included in the output by default. Signed attributes are not included by default but can be added by using the PKI_CMS_INCLUDE_ATTRS option flag (see below). Unsigned attributes and attribute certificates are not supported. The default signature algorithm is RSASSA-PKCS-v1_5 with SHA-1 (SHA-1 caution!). The message digest algorithm always matches the digest algorithm used in the signature.

The encapContentInfo eContentType is always id-data: other eContentTypes are not possible. Only one SignerInfo can be included at one time, but [New in v23.0] additional SignerInfos can be added by calling this function second time passing an existing SignedData object as input and setting the PKI_CMS_ADD_SIGNER (see below). [New in v23.0] The signer's public key can be referenced using either issuerAndSerialNumber (default) or subjectKeyIdentifier (use the PKI_CMS_USE_SKI option). If subjectKeyIdentifier is used then the CMSversion will be 3 and the relevant SignerInfo version will also be 3. Otherwise the CMSVersion will be 1 and the SignerInfo structure also version 1.

It is an error (NO_MATCH_ERROR) if the private key does not match any certificate in the certificate list.

[New in v12.2] A PKCS#7 certificate chain file (.p7c/.p7b) may be specified as an argument for szCertList. The signer's certificate can now exist anywhere in the certificate list (previously it had to be the first).

PKI_CMS_CERTS_ONLY: To create a PKCS#7 certificate chain (a degenerate "certs-only" signed data object), include the option flag PKI_CMS_CERTS_ONLY. The szCertList can contain references to any existing certificate files in any order, separated by semi-colons. The szFileIn and szPrivateKey parameters are ignored and can be left empty. See the second example below.

PKI_CMS_INCLUDE_ATTRS: Signed attributes are not included by default. To add signed attributes use the PKI_CMS_INCLUDE_ATTRS option flag. This will add the content-type and message-digest attributes plus any other attributes specified using a PKI_CMS_ADD_* option.

PKI_CMS_ADD_SIGNINGCERT: [New in v12.4] Include the PKI_CMS_ADD_SIGNINGCERT option to add an ESS Signing Certificate Attribute to the signed attributes. This is required for B-level compliance with CAdES-BES [CADES] and with ESS [RFC2634] and [RFC5035].

PKI_CMS_ADD_ALGPROTECT: [New in v12.4] Include the PKI_CMS_ADD_ALGPROTECT option to add an Algorithm Protection Attribute to the signed attributes. This is in accordance with [RFC6211]. If a CMS validator supports this attribute, then additional checks can be made against algorithm substitution attacks.

PKI_CMS_BIGFILE: Include the PKI_CMS_BIGFILE option to cope more efficiently with large files. This only works in binary-file-to-binary-file mode, and only for RSA signatures, but makes a significant difference in processing times. The option flags PKI_CMS_EXCLUDE_DATA, PKI_CMS_CERTS_ONLY, PKI_CMS_FORMAT_BASE64, and PKI_CMS_NO_OUTER are not permitted with this option.

PKI_CMS_ADD_SIGNER: [New in v23.0] To sign an existing SignedData object with another signature, use the PKI_CMS_ADD_SIGNER option and pass the existing SignedData object as the input data file. Pass the signer's certificate in szCertList (plus any additional certificates if required) and the signer's private key string in szPrivateKey.

PKI_PSS_SALTLEN_ZERO: [New in v12.0] Include the PKI_PSS_SALTLEN_ZERO with an RSA-PSS scheme to set the salt length parameter to be zero. This results in a deterministic signature value. The default salt length is otherwise always hLen, the length of the output of the hash function. There are no other salt length options available for this function. See RSA signature and encryption schemes.

PKI_CMS_ALT_ALGID: If the PKI_CMS_ALT_ALGID option flag is present, an alternative Signature Algorithm Identifier will be used as follows (RSAES-PKCS-v1_5 only):

Message Digest Algorithm Default Signature Algorithm Identifier Alternative ID with PKI_CMS_ALT_ALGID
SHA-1 (default, PKI_SIG_RSA_SHA1)rsaEncryption (1.2.840.113549.1.1)sha1withRSAEncryption (1.2.840.113549.1.1.5)
MD5 (with PKI_SIG_RSA_MD5)rsaEncryption (1.2.840.113549.1.1)md5withRSAEncryption (1.2.840.113549.1.1.4)
SHA-224 (with PKI_SIG_RSA_SHA224)rsaEncryption (1.2.840.113549.1.1)sha224withRSAEncryption (1.2.840.113549.1.1.14)
SHA-256 (with PKI_SIG_RSA_SHA256)rsaEncryption (1.2.840.113549.1.1)sha256withRSAEncryption (1.2.840.113549.1.1.11)
SHA-384 (with PKI_SIG_RSA_SHA384)rsaEncryption (1.2.840.113549.1.1)sha384withRSAEncryption (1.2.840.113549.1.1.12)
SHA-512 (with PKI_SIG_RSA_SHA512)rsaEncryption (1.2.840.113549.1.1)sha512withRSAEncryption (1.2.840.113549.1.1.13)

The default is to use the rsaEncryption identifier specified in Section 3.2 of [CMSALG].

PKI_CMS_PSEUDOSIG: [New in v20.2] Include the PKI_CMS_PSEUDOSIG option to create a create a "pseudo" SignedData object. The idea here is that we create an intermediate file which has the same structure as a CMS SignedData object except the signature is a dummy placeholder. We use the term "pseudo" file here to describe this intermediate file.

This pseudo file has the same digest value as the final signed object (as the digest is not calculated over the final signature). We send this digest value to a signing authority (say, Aruba), they sign it, and send back the actual signature value. This can be substituted in the intermediate pseudo file to produce the final SignedData object (.p7m file) using CMS_MakeSigDataFromSigValue with the PKI_CMS_PSEUDOSIG option. RSASSA-PKCS1V1_5 only.

Specialist Option: If the PKI_CMS_NO_OUTER option flag is present, the output will be a "naked" SignedData object without an outerContentInfo. This is not permitted by the CMS standard [CMS] but is allowed by PKCS#7 version 1.6 [PKCS7-EXT]. Some profiles (e.g. Royal Thai Customs) require this.

◆ CMS_MakeSigDataFromBytes()

long CMS_MakeSigDataFromBytes ( const char *  szFileOut,
const unsigned char *  lpInput,
long  nInputLen,
const char *  szCertList,
const char *  szPrivateKey,
long  nOptions 
)

Create a CMS object of type SignedData from an array of bytes.

Parameters
[in]szFileOutname of output file to be created.
[in]lpInputbyte array containing input data to be signed.
[in]nInputLenlength in bytes of input data.
[in]szCertListfilename of the signer's certificate and (optionally) a list of other certificates to be included in the output, separated by semi-colons (;). Alternatively specify a single PKCS#7 certificate chain file (.p7c/.p7b) containing the signer's certificate.
[in]szPrivateKeyprivate key data for the sender in "internal" string format.
[in]nOptionsOption flags. Select one of:
PKI_SIG_RSA_SHA1 (0) to use RSASSA-PKCS-v1_5 with SHA-1 (sha1WithRSAEncryption) (default - CAUTION)
PKI_SIG_RSA_SHA224 to use RSASSA-PKCS-v1_5 with SHA-224 (sha224WithRSAEncryption)
PKI_SIG_RSA_SHA256 to use RSASSA-PKCS-v1_5 with SHA-256 (sha256WithRSAEncryption) [minimum recommended]
PKI_SIG_RSA_SHA384 to use RSASSA-PKCS-v1_5 with SHA-384 (sha384WithRSAEncryption)
PKI_SIG_RSA_SHA512 to use RSASSA-PKCS-v1_5 with SHA-512 (sha512WithRSAEncryption)
PKI_SIG_RSA_MD5 to use RSASSA-PKCS-v1_5 with MD5 (md5WithRSAEncryption) [legacy, not recommended for new implementations]
PKI_SIG_RSA_PSS_SHA1 to use RSASSA-PSS with SHA-1
PKI_SIG_RSA_PSS_SHA224 to use RSASSA-PSS with SHA-224
PKI_SIG_RSA_PSS_SHA256 to use RSASSA-PSS with SHA-256
PKI_SIG_RSA_PSS_SHA384 to use RSASSA-PSS with SHA-384
PKI_SIG_RSA_PSS_SHA512 to use RSASSA-PSS with SHA-512
PKI_SIG_ECDSA_SHA1 to use ecdsaWithSHA1
PKI_SIG_ECDSA_SHA224 to use ecdsaWithSHA224
PKI_SIG_ECDSA_SHA256 to use ecdsaWithSHA256
PKI_SIG_ECDSA_SHA384 to use ecdsaWithSHA384
PKI_SIG_ECDSA_SHA512 to use ecdsaWithSHA512
PKI_SIG_ED25519 to use Ed25519 [New in v20.0]
PKI_SIG_ED2448 to use Ed448 [New in v22.0]

and optionally add any of the following flags:
PKI_CMS_EXCLUDE_CERTS to exclude signer's certificate
PKI_CMS_EXCLUDE_DATA to exclude the eContent data
PKI_CMS_CERTS_ONLY to create a "certs-only" PKCS#7 certficate chain
PKI_CMS_INCLUDE_ATTRS to add signed attributes (default = no signed attributes) including content-type and message-digest plus any more added below.
PKI_CMS_FORMAT_BASE64 to format the output with base64 encoding (default output is binary)
PKI_CMS_NO_OUTER to create a "naked" SignedData object with no outerContentInfo as permitted by PKCS#7 v1.6 (specialist option)
PKI_CMS_ALT_ALGID to use an alternative signature algorithm identifier (see Remarks)
PKI_CMS_BIGFILE to speed up the processing of large files (see Remarks)
PKI_PSS_SALTLEN_ZERO to set the salt length to be zero (RSASSA-PSS only, default = same length as the output of the hash function)
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (RSASSA-PSS only, default = same as signature hash function)

If the PKI_CMS_INCLUDE_ATTRS option flag is included, optionally add any of the following:
PKI_CMS_ADD_SIGNTIME to add SigningTime to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SMIMECAP to add sMIMECapabilities to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SIGNINGCERT to add an ESS Signing Certificate Attribute to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS) [New in v12.4]
PKI_CMS_ADD_ALGPROTECT to add an Algorithm Identifier Protection Attribute to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS) [New in v12.4]
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code. Further error information may be available by calling PKI_LastError().
Remarks
This function is identical to CMS_MakeSigData() except the input is passed as a byte array instead of in a file.

See the remarks for CMS_MakeSigData above.

Use this function if the content contains non-ASCII characters such as UTF-8 encoded.

◆ CMS_MakeSigDataFromSigValue()

long CMS_MakeSigDataFromSigValue ( const char *  szFileOut,
const unsigned char *  lpSigValue,
long  nSigLen,
const unsigned char *  lpData,
long  nDataLen,
const char *  szCertList,
long  nOptions 
)

Creates a CMS object of type SignedData using a pre-computed signature value.

Parameters
[in]szFileOutname of output file to be created.
[in]lpSigValuebyte array containing the pre-computed signature.
[in]nSigLenlength of the signature value in bytes.
[in]lpDatabyte array containing the data that has been signed (required).
[in]nDataLenlength of the data in bytes.
[in]szCertListfilename of the signer's certificate and (optionally) a list of other certificates to be included in the output, separated by semi-colons (;). Alternatively specify a single PKCS#7 certificate chain file (.p7c/.p7b) containing the signer's certificate.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
and optionally add
PKI_CMS_EXCLUDE_CERTS to exclude signer's certificate
PKI_CMS_FORMAT_BASE64 to format the output with base64 encoding (default output is binary)
PKI_CMS_NO_OUTER to create a "naked" SignedData object with no outerContentInfo as permitted by PKCS#7 v1.6
PKI_CMS_ALT_ALGID to use alternative signature algorithm identifiers (see Remarks for CMS_MakeSigData())
PKI_CMS_PSEUDOSIG to create a SignedData object from a "pseudo" object (see Remarks).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code. Further error information may be available by calling PKI_LastError().
Remarks
This is a specialized option for a specific case where the RSA v1.5 signature value over the content has been computed separately (say, using a smart card) and the user requires this to be used inside a CMS signed-data object.

A SignedData CMS object with a single SignerInfo is created with the message data included in the eContent. Signed attributes cannot be added. Unsigned attributes and attribute certificates are not supported. The content must be included in the input using the lpData and nDataLen parameters. Only RSASSA-PKCS-v1_5 signature schemes are supported by this function. Only one message digest algorithm is used in each object. SHA-1 is used by default. Alternative hash algorithms can be used instead by adding the appropriate PKI_HASH_ option flag (this must match the digest algorithm used to compute the signature). The content and the signature are checked before the output file is created. If the signature data is not valid, or the data is not the data signed, or the certificate specified is not that of the signer, then it will return SIGNATURE_ERROR (-22).

[New in v12.2] A PKCS#7 certificate chain file (.p7c/.p7b) may be specified as an argument for szCertList. The signer's certificate can now exist anywhere in the certificate list (previously it had to be the first).

[New in v20.2] Use the PKI_CMS_PSEUDOSIG option to create a SignedData object from a "pseudo" object, created using CMS_MakeSigData with the PKI_CMS_PSEUDOSIG option.

◆ CMS_MakeSigDataFromString()

long CMS_MakeSigDataFromString ( const char *  szFileOut,
const char *  szDataIn,
const char *  szCertList,
const char *  szPrivateKey,
long  nOptions 
)

Create a CMS object of type SignedData from an input string.

Parameters
[in]szFileOutname of output file to be created.
[in]szDataInstring containing message data to be signed.
[in]szCertListfilename of the signer's certificate and (optionally) a list of other certificates to be included in the output, separated by semi-colons (;). Alternatively specify a single PKCS#7 certificate chain file (.p7c/.p7b) containing the signer's certificate.
[in]szPrivateKeyprivate key data for the sender in "internal" string format.
[in]nOptionsOption flags. Select one of:
PKI_SIG_RSA_SHA1 (0) to use RSASSA-PKCS-v1_5 with SHA-1 (sha1WithRSAEncryption) (default - CAUTION)
PKI_SIG_RSA_SHA224 to use RSASSA-PKCS-v1_5 with SHA-224 (sha224WithRSAEncryption)
PKI_SIG_RSA_SHA256 to use RSASSA-PKCS-v1_5 with SHA-256 (sha256WithRSAEncryption) [minimum recommended]
PKI_SIG_RSA_SHA384 to use RSASSA-PKCS-v1_5 with SHA-384 (sha384WithRSAEncryption)
PKI_SIG_RSA_SHA512 to use RSASSA-PKCS-v1_5 with SHA-512 (sha512WithRSAEncryption)
PKI_SIG_RSA_MD5 to use RSASSA-PKCS-v1_5 with MD5 (md5WithRSAEncryption) [legacy, not recommended for new implementations]
PKI_SIG_RSA_PSS_SHA1 to use RSASSA-PSS with SHA-1
PKI_SIG_RSA_PSS_SHA224 to use RSASSA-PSS with SHA-224
PKI_SIG_RSA_PSS_SHA256 to use RSASSA-PSS with SHA-256
PKI_SIG_RSA_PSS_SHA384 to use RSASSA-PSS with SHA-384
PKI_SIG_RSA_PSS_SHA512 to use RSASSA-PSS with SHA-512
PKI_SIG_ECDSA_SHA1 to use ecdsaWithSHA1
PKI_SIG_ECDSA_SHA224 to use ecdsaWithSHA224
PKI_SIG_ECDSA_SHA256 to use ecdsaWithSHA256
PKI_SIG_ECDSA_SHA384 to use ecdsaWithSHA384
PKI_SIG_ECDSA_SHA512 to use ecdsaWithSHA512
PKI_SIG_ED25519 to use Ed25519 [New in v20.0]
PKI_SIG_ED448 to use Ed448 [New in v22.0]

and optionally add any of the following flags:
PKI_CMS_EXCLUDE_CERTS to exclude signer's certificate
PKI_CMS_EXCLUDE_DATA to exclude the eContent data
PKI_CMS_CERTS_ONLY to create a "certs-only" PKCS#7 certficate chain
PKI_CMS_INCLUDE_ATTRS to add signed attributes (default = no signed attributes) including content-type and message-digest plus any more added below.
PKI_CMS_FORMAT_BASE64 to format the output with base64 encoding (default output is binary)
PKI_CMS_NO_OUTER to create a "naked" SignedData object with no outerContentInfo as permitted by PKCS#7 v1.6 (specialist option)
PKI_CMS_ALT_ALGID to use an alternative signature algorithm identifier (see Remarks)
PKI_PSS_SALTLEN_ZERO to set the salt length to be zero (RSASSA-PSS only, default = same length as the output of the hash function)
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (RSASSA-PSS only, default = same as signature hash function)

If the PKI_CMS_INCLUDE_ATTRS option flag is included, optionally add any of the following:
PKI_CMS_ADD_SIGNTIME to add SigningTime to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SMIMECAP to add sMIMECapabilities to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS)
PKI_CMS_ADD_SIGNINGCERT to add an ESS Signing Certificate Attribute to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS) [New in v12.4]
PKI_CMS_ADD_ALGPROTECT to add an Algorithm Identifier Protection Attribute to the signed attributes (requires PKI_CMS_INCLUDE_ATTRS) [New in v12.4]
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code. Further error information may be available by calling PKI_LastError().
Remarks
This function is identical to CMS_MakeSigData() except the input is passed as a string instead of in a file.

Zero-terminated ANSI data is expected in szDataIn.

To sign a messsage that contains binary or Unicode UTF-8 or UTF-16 data, use CMS_MakeSigDataFromBytes.

◆ CMS_QueryEnvData()

long CMS_QueryEnvData ( char *  szOutput,
long  nOutChars,
const char *  szFileIn,
const char *  szQuery,
long  nOptions 
)

Queries a CMS enveloped-data object file for selected information.

Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the length of the output string.
[in]szFileInwith name of signed-data CMS object file or the data as a base64 or PEM string.
[in]szQueryspecifying the query (see Remarks below).
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_QUERY_GETTYPE to return the type of data returned for a given query.
Returns
If successful, the return value is a positive integer indicating either the result itself (if the result is a number) or the number of characters in the output string (if the query is looking for a string). If the item queried cannot be found, the return value is zero. If there is an error (e.g. an invalid signed-data file), it returns a negative error code.
Remarks
This function queries a given EnvelopedData file for selected information. The query string is case-insensitive, so "version", "VERSION" and "VeRsIoN" are all valid.

Valid queries are (case-insensitive):

Query StringReturnsData Type
versionenvelopedData CMSVersion (edVer) valueNumber
recipientInfoVersionrecipientInfo version (riVer) valueNumber
recipientInfoTypeType of recipientInfo: ktri, kari, kekri, pwri, oriString
CountOfRecipientInfosNumber of RecipientInfos included in the dataNumber
recipientIssuerNameDistinguished Name of recipient's certificate issuerString
recipientSerialNumberserialNumber of recipient's certificate in hex formatString
keyEncryptionAlgorithmkeyEncryptionAlgorithm, e.g. "rsaEncryption"String
keyEncryptionFlagsBit flags used for the key encryption algorithm (ktri only)Number
SizeOfEncryptedKeySize (in bytes) of the EncryptedKeyNumber
encryptedKeyEncryptedKey value encoded in hexString
oaepParamsParameters used for RSA-OAEP (if applicable). String
kemParamsParameters used for RSA-KEM (if applicable) [New in v23.0] String
keyWrapAlgorithmKey wrap algorithm, e.g. "aes128-wrap" (kari and kekri only)String
originatorKeyAlgorithmOriginatorPublicKey algorithm, e.g. "ecPublicKey" (kari only)String
originatorPublicKeyOriginatorPublicKey publicKey value encoded in hex (kari only)String
keyidkeyIdentifier for KEKRecipientInfo (kekri) typeString
ukmUser Keying Material (if applicable) [New in v23.0]String
contentEncryptionAlgorithmcontentEncryptionAlgorithm, e.g. "des-EDE3-CBC"String
SizeOfEncryptedContentSize (in bytes) of the EncryptedContentNumber
encryptedContentEncryptedContent encoded in hexString
ivInitialization vector for encrypted content encoded in hexString
HASsubjectKeyIdentifier1 if recipientIdentifier is the CHOICE subjectKeyIdentifier; 0 if issuerAndSerialNumber [New in v23.0]Number
recipientIdentifierrecipientIdentifier value encoded in hex [New in v23.0]

String

By default, the function queries the first recipientInfo in the file. To query the Nth recipientInfo append "/N" to the query string, e.g. "recipientInfoVersion/2" to find the version number of the second recipientInfo in the file. The query encryptedContent may be slow to respond if the file is large.

The "raw" VBA/C function behaves differently depending on whether the output is a string or a number. If the result data type is a number then it returns the value directly. If the result is a string, then it sets szOutput and returns the number of characters in the string. The required number of characters can be found by passing zero for nOutChars or a null string for szOutput. ANSI C users must add one to this value when allocating memory.

Note that the VBA wrapper function and the C#/VB.NET and C++ (STL) methods always return a string, which is different from the behaviour of the raw VB6/C function.

To find out the type of data returned for a given query, use the PKI_QUERY_GETTYPE option. The function will return either PKI_QUERY_NUMBER (1) or PKI_QUERY_STRING (2), or a negative "invalid query" error. For example

nRet = CMS_QueryEnvData("", 0, "", "version", PKI_QUERY_GETTYPE);

will return PKI_QUERY_NUMBER.

◆ CMS_QuerySigData()

long CMS_QuerySigData ( char *  szOutput,
long  nOutChars,
const char *  szFileIn,
const char *  szQuery,
long  nOptions 
)

Queries a CMS signed-data object file for selected information.

Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the length of the output string.
[in]szFileInwith name of signed-data CMS object file or the data as a base64 or PEM string.
[in]szQueryspecifying the query (see Remarks below).
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_QUERY_GETTYPE to return the type of data returned for a given query.
Returns
If successful, the return value is a positive integer indicating either the result itself (if the result is a number) or the number of characters in the output string (if the query is looking for a string). If the item queried cannot be found, the return value is zero. If there is an error (e.g. an invalid signed-data file), it returns a negative error code.
Remarks
This function queries a given SignedData file for selected information. Only version 1 signed-data objects are fully supported. The function will attempt to query other versions but may not succeed. Note that this function does not verify any data, including the messageDigest attribute, it just returns what it finds. The query string is case-insensitive, so "version", "Version" and "VeRsIoN" are all valid.

Valid queries are (case-insensitive):

Query StringReturnsData Type
versionsignedData version (sdVer) valueNumber
eContentTypeContentType of the EncapsulatedContentInfo, e.g. "data"String
HASeContent1 if eContent is present; 0 if notNumber
CountOfCertificatesNumber of certificates in the SignedDataNumber
CountOfSignerInfosNumber of SignerInfos in the SignedDataNumber
CountOfDigestAlgsNumber of DigestAlgorithmIdentifiers in the SignedData [New in v23.0]Number
certificate/NNth certificate encoded in base64 [New in v23.0]String
signerInfoVersionsignerInfo version (siVer) valueNumber
digestAlgorithmdigestAlgorithm, e.g. "sha1"String
signatureAlgorithmsignatureAlgorithm, e.g. "rsaEncryption"String
signatureValueSignature value encoded in hexString
HASsignedAttributes1 if signedAttributes (authenticatedAttributes) are present; 0 if notNumber
DigestOfSignedAttrsComputed digest over signed attributes, if present, using digestAlgorithmString
DigestOfeContentComputed digest over eContent, if present, using digestAlgorithmString
signingTimesigningTime attribute in format "2005-12-31 23:30:59"String
messageDigestmessageDigest attribute in hexadecimal format, if presentString
pssParamsParameters used for RSA-PSS (if applicable).String
HASsigningCertificate1 if an ESS signingCertificate is present; 0 if not.Number
signingCertHashcertHash value of ESS signing certificate, if present, encoded in hexString
HASalgorithmProtection1 if a cmsAlgorithmProtection attribute is present; 0 if not.Number
HASsubjectKeyIdentifier1 if signerIdentifier is the CHOICE subjectKeyIdentifier; 0 if issuerAndSerialNumber [New in v23.0]Number
signerIdentifiersignerIdentifier value encoded in hex [New in v23.0]

String

By default, the function queries the first signerInfo in the file. To query the Nth signerInfo append "/N" to the query string, e.g. "signerInfoVersion/2" to find the version number of the second signerInfo in the file.

[New in v23.0] The query "certificate/N" will output the Nth certificate in the CertificateSet (default N = 1) encoded in base64. Note that the length of an X.509 certificate is typically several hundred bytes.

The "raw" VBA/C function behaves differently depending on whether the output is a string or a number. If the result data type is a number then it returns the value directly. If the result is a string, then it sets szOutput and returns the number of characters in the string. The required number of characters can be found by passing zero for nOutChars or a null string for szOutput. ANSI C users must add one to this value when allocating memory.

Note that the VBA wrapper function and the C#/VB.NET methods always return a string, which is different from the behaviour of the raw VB6/C function.

To find out the type of data returned for a given query, use the PKI_QUERY_GETTYPE option. The function will return either PKI_QUERY_NUMBER (1) or PKI_QUERY_STRING (2), or a negative "invalid query" error. For example

nRet = CMS_QuerySigData("", 0, "", "version", PKI_QUERY_GETTYPE);

will return PKI_QUERY_NUMBER.

◆ CMS_ReadComprData()

long CMS_ReadComprData ( const char *  szFileOut,
const char *  szFileIn,
long  nOptions 
)

Read and extract the decompressed contents of a CMS compressed-data file.

Parameters
[in]szFileOutname of output file to be created.
[in]szFileInname of file containing input data.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_CMS_NO_INFLATE to extract the compressed data as is without inflation
Returns
If successful, the return value is the number of bytes in the output file; otherwise it returns a negative error code.
Remarks
This will read and extract the contents of a CMS compressed-data file (conventionally saved with a .p7z extension) which uses the zlibCompress algorithm. It only works in file-to-file mode. Any existing file with the same name as the parameter szFileOut will be overwritten without warning. Use the PKI_CMS_NO_INFLATE option to extract the compressed data as is without inflation.

◆ CMS_ReadEnvData()

long CMS_ReadEnvData ( const char *  szFileOut,
const char *  szFileIn,
const char *  szCertFile,
const char *  szPrivateKey,
long  nOptions 
)

Read and decrypt a CMS enveloped-data object to a file.

Parameters
[in]szFileOutwith name of output file to be created.
[in]szFileInwith name of file containing input data (binary or base64-encoded) or the data as a base64 or PEM string.
[in]szCertFile(optional) specifies the filename of the recipient's X.509 certificate.
[in]szPrivateKeyrecipient's private key in internal string format.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options.
PKI_CMS_BIGFILE to speed up the processing of large files (binary only).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
If received as an attachment to an S/MIME email message, the user must first extract the CMS object from the email (Hint: use a text editor and cut out the base64 data from the message
  • see Sending an enveloped-data object and work backwards).

The optional certificate szCertFile is used to identify the intended recipient in a message addressed to multiple recipients. If the intended recipient's certificate is not provided, the first valid message that can be decrypted using the given private key, if any, will be extracted.

The supported EnvelopedData and AuthEnvelopedData objects are those described in CMS Content Types.

Use the PKI_CMS_BIGFILE option to process large files more efficiently. See the example in CMS_MakeEnvData().

[Changes in v12.1] To avoid certain attacks that rely on timing differences, the encrypted content will always be decrypted. If all else is good but no valid content encryption key (CEK) can be found in the recipient data, then a random key will be used. The end result in this latter case will always be a negative DECRYPT_ERROR with no further information as to the cause. If there is something obviously wrong with the input, such as a badly-formed input file (INVALID_DATA_ERROR), or the given certificate does not have a match with any recipient (NO_MATCH_ERROR), then an appropriate error code will be returned.

◆ CMS_ReadEnvDataToBytes()

long CMS_ReadEnvDataToBytes ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szFileIn,
const char *  szCertFile,
const char *  szPrivateKey,
long  nOptions 
)

Reads and decrypts CMS enveloped-data object using the recipient's private key writing the plaintext data directly into a byte array.

Parameters
[out]lpOutputbuffer to receive output plaintext.
[in]nOutByteslength in bytes of the output buffer.
[in]szFileInname of file containing input data (binary or base64-encoded) or the data as a base64 or PEM string.
[in]szCertFile(optional) filename of the recipient's X.509 certificate.
[in]szPrivateKeyrecipient's private key in internal string format.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
Returns
If successful, the return value is the number of bytes in the decrypted plaintext; otherwise it returns a negative error code.
Remarks
See the remarks for CMS_ReadEnvData() above. Call the function with a NULL lpOutput or zero nOutBytes parameter to find out the required length of the output buffer. Alternatively, use the CMS_QueryEnvData() function with the query "sizeofEncryptedContent". This will return an upper bound on the length of the decrypted plaintext, at most 16 bytes too long. Calling CMS_ReadEnvDataToString() with a properly-sized output buffer will return the exact size of the recovered plaintext. The buffer must be large enough to receive the entire output or a SHORT_BUF_ERROR error will result.

Use this function if the output plaintext is known to contain non-ASCII characters such as UTF-8 encoded.

◆ CMS_ReadEnvDataToString()

long CMS_ReadEnvDataToString ( char *  szOutput,
long  nOutChars,
const char *  szFileIn,
const char *  szCertFile,
const char *  szPrivateKey,
long  nOptions 
)

Reads and decrypts CMS enveloped-data object using the recipient's private key writing the plaintext data directly into a string.

Parameters
[out]szOutputbuffer to receive output plaintext.
[in]nOutCharslength in bytes of the output buffer.
[in]szFileInname of file containing input data (binary or base64-encoded) or the data as a base64 or PEM string.
[in]szCertFile(optional) filename of the recipient's X.509 certificate.
[in]szPrivateKeyrecipient's private key in internal string format.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
Returns
If successful, the return value is the number of bytes in the decrypted plaintext; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

See the remarks for CMS_ReadEnvData() above.

Alternatively, use the CMS_QueryEnvData() function with the query "sizeofEncryptedContent". This will return an upper bound on the length of the decrypted plaintext, at most 16 bytes too long. Calling CMS_ReadEnvDataToString() with a properly-sized output buffer will return the exact size of the recovered plaintext. The buffer must be large enough to receive the entire output or a SHORT_BUF_ERROR error will result.

Use this function only if the output plaintext is known to be plain ASCII text with no embedded NUL (zero) characters, otherwise use CMS_ReadEnvDataToBytes.

◆ CMS_ReadSigData()

long CMS_ReadSigData ( const char *  szFileOut,
const char *  szFileIn,
long  nOptions 
)

Reads the content from a CMS signed-data object file.

Parameters
[in]szFileOutwith name of output file to be created.
[in]szFileInwith name of signed-data CMS object file (binary or base64-encoded) or the data as a base64 or PEM string.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_CMS_BIGFILE to speed up the processing of large files (binary input only).
Returns
If successful, the return value is a positive number indicating the number of bytes in the content; otherwise it returns a negative error code.
Remarks
This function extracts the signed data from the signed-data CMS object without making any attempt to verify it. Any existing file with the same name as the specified output will be overwritten without further warning.

This function automatically checks for and reads "naked" SignedData files as per PKCS#7 version 1.6 [PKCS7-EXT] as well as the default SignedData objects properly encapsulated in an outerContentInfo as per the S/MIME standard.

◆ CMS_ReadSigDataToBytes()

long CMS_ReadSigDataToBytes ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szFileIn,
long  nOptions 
)

Reads the content from a CMS signed-data object file directly into a byte array.

Parameters
[out]lpOutputbuffer to receive the output.
[in]nOutByteslength of the output buffer.
[in]szFileInwith name of signed-data CMS object file (binary or base64-encoded) or the data as a base64 or PEM string.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
Returns
If successful, the return value is a positive number indicating the number of bytes in the content; otherwise it returns a negative error code.
Remarks
This function extracts the signed content from the signed-data CMS object without making any attempt to verify it. Call the function with a NULL abOutput array or zero nOutBytes parameter to find out the required length of the output buffer. The buffer must be large enough to receive the entire output or a SHORT_BUF_ERROR error will result.

Use this function if the content contains non-ASCII characters such as UTF-8 encoded.

◆ CMS_ReadSigDataToString()

long CMS_ReadSigDataToString ( char *  szOutput,
long  nOutChars,
const char *  szFileIn,
long  nOptions 
)

Reads the content from a CMS signed-data object file directly into a string.

Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the length of the output string.
[in]szFileInwith name of signed-data CMS object file (binary or base64-encoded) or the data as a base64 or PEM string.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
Returns
If successful, the return value is a positive number indicating the number of bytes in the content; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This function extracts the signed data from the signed-data CMS object without making any attempt to verify it.

The buffer must be large enough to receive the entire output or a SHORT_BUF_ERROR error will result.

Use this only when the signed content is known to be plain ASCII text, otherwise use CMS_ReadSigDataToBytes.

◆ CMS_VerifySigData()

long CMS_VerifySigData ( const char *  szFileIn,
const char *  szCertFile,
const char *  szHexDigest,
long  nOptions 
)

Verifies the signature and content of a signed-data CMS object file.

Parameters
[in]szFileInspecifying the name of the signed-data CMS object file (binary or base64-encoded) or the data as a base64 or PEM string.
[in]szCertFile(optional) specifying an X.509 certificate file to be used to identify the signer. Specify an empty string "" to use the certificate(s) in the input file.
[in]szHexDigest(optional) specifying a message digest encoded in hexadecimal format. Use this to verify a "detached-signature" input file. Specify an empty string "" to verify the eContent data in the SignedData file.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options.
PKI_CMS_BIGFILE to speed up the processing of large files (binary input only).
Returns
If successful, the return value is zero; otherwise it returns a negative error code.
Remarks
This function verifies that the content was indeed signed by the purported signer. Note that it returns zero to indicate success, not true. If a certificate is specified in szCertFile then the public key from that certificate will be used and a matching signerInfo will be searched for in the SignedData file. Otherwise the first matching pair of certificate and signerInfo found in the SignedData file will be used.

If the signed content (eContent) is included in the SignedData object (this is the usual case), then specify an empty string ("") for szHexDigest. For a "detached-signature" file where the signed content has been passed to the user by other means, compute a separate message digest of the data and pass it to the function in the szHexDigest parameter.

This function handles SignedData objects both with and without signedAttributes.

[New in v12.4] If an ESS Signing Certificate attribute is found, then the purported signing certificate will be checked against the value of this attribute as per ESS [RFC5035] and CAdES [CADES]. It is a SIGNATURE_ERROR (22) if these do not match.

[New in v12.4] If an Algorithm Protection Attribute is found, then further verification checks will be made to prevent algorithm substitution attacks as per [RFC6211]. It is a SIGNATURE_ERROR (22) if these checks fail.

◆ CNV_B64Filter()

long CNV_B64Filter ( char *  szOutput,
const char *  szInput,
long  nStrLen 
)

Removes non-base64 characters from a string.

Parameters
[out]szOutputto receive filtered characters.
[in]szInputto be filtered.
[in]nStrLenspecifying the length of the input string.
Returns
If successful, the return value is the number of characters in the filtered string; otherwise it returns a negative error code.
Remarks
Specify a zero nOutChars or an empty string for szOutput to find the required length of the output string. ANSI C users must add one to this value when allocating memory.

Assumes that the output string is at least as long as the input string.

◆ CNV_B64StrFromBytes()

long CNV_B64StrFromBytes ( char *  szOutput,
long  nOutChars,
const unsigned char *  lpInput,
long  nInputLen 
)

Encodes an array of bytes into a base64-encoded string.

Parameters
[out]szOutputto receive encoded data.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]lpInputarray of binary data to be encoded.
[in]nInputLennumber of bytes to be encoded.
Returns
If successful, the return value is the number of characters in the encoded string; otherwise it returns a negative error code.
Remarks
Specify a zero nOutChars or an empty string for szOutput to find the required length of the output string. ANSI C users must add one to this value when allocating memory.

This uses the base64 encoding scheme from [RFC4648]. Pass a zero value of nOutChars to find the required maximum possible number of characters in the output string. The final result may be smaller. C/C++ programmers should add one to the returned length value when allocating memory for szOutput.

◆ CNV_Base58FromBytes()

long CNV_Base58FromBytes ( char *  szOutput,
long  nOutChars,
const unsigned char *  lpInput,
long  nInputLen 
)

Encodes an array of bytes into a base58-encoded string.

Parameters
[out]szOutputto receive encoded data.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]lpInputarray of binary data to be encoded.
[in]nInputLennumber of bytes to be encoded.
Returns
If successful, the return value is the number of characters in the encoded string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This uses the "Bitcoin" scheme of base58 encoding where the leading character '1' is reserved for representing an entire leading zero byte [BTC-B58].

◆ CNV_Base58ToBytes()

long CNV_Base58ToBytes ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szInput 
)

Decodes a base58-encoded string into an array of bytes.

Parameters
[out]lpOutputarray suitably dimensioned to receive decoded output.
[in]nOutBytesspecifying the maximum number of bytes to be received.
[in]szInputbase58 data to be decoded.
Returns
If successful, the return value is the number of bytes in the decoded array; otherwise it returns a negative error code.
Remarks
This uses the "Bitcoin" scheme of base58 encoding where the leading character '1' is reserved for representing an entire leading zero byte [BTC-B58]. Pass a zero value for nOutBytes to find the required number of bytes in the output array.

◆ CNV_ByteEncoding()

long CNV_ByteEncoding ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nBytes,
long  nOptions 
)

Converts encoding of byte array between UTF-8 and Latin-1.

Parameters
[out]lpOutputarray suitably dimensioned to receive output..
[in]nOutBytesspecifying the maximum number of bytes to be received.
[in]lpInputarray containing input data.
[in]nBytesnumber of bytes in input array.
[in]nOptionsOption flags. Select one of:
PKI_CNV_UTF8_FROM_LATIN1 (1) to convert from UTF-8 encoding to Latin-1
PKI_CNV_LATIN1_FROM_UTF8 (2) to convert from Latin-1 encoding to UTF-8
Returns
If successful, the return value is a positive number indicating the number of bytes in the output array, or number of bytes required if nOutBytes is set to zero; otherwise it returns a negative error code.
Remarks
Converting UTF-8 from Latin-1 assumes the input is from the 8-bit Latin-1 character set and so will always produce output that is valid UTF-8. However, for Latin-1 from UTF-8, the input must contain a valid sequence of UTF-8-encoded bytes and this must be convertible to a single-byte character set, or an error will be returned.

◆ CNV_BytesFromB64Str()

long CNV_BytesFromB64Str ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szInput 
)

Decodes a base64-encoded string into an array of Bytes.

Parameters
[out]lpOutputarray suitably dimensioned to receive output.
[in]nOutBytesspecifying the maximum number of bytes to be received.
[in]szInputbase64 data to be decoded.
Returns
If successful, the return value is the number of bytes in the decoded array; otherwise it returns a negative error code.
Remarks
This uses the base64 encoding scheme from [RFC4648]. Pass a zero value for nOutBytes to find the required maximum possible number of bytes in the output array. The final array may be shorter.
Warning
[Changed in v11.1] This function now returns an error if it finds an illegal character in the input string (previously any non-base64 character was just ignored). Whitespace characters (space, TAB, LF, CR, VT, FF) are still allowed and ignored but any other non-base64 characters will cause an error.

◆ CNV_BytesFromHexStr()

long CNV_BytesFromHexStr ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szInput 
)

Decodes a hexadecimal-encoded string into an array of Bytes.

Parameters
[out]lpOutputarray suitably dimensioned to receive output.
[in]nOutBytesspecifying the length of the byte array.
[in]szInputof hexadecimal data to be decoded.
Returns
If successful, the return value is the number of bytes in the decoded array; otherwise it returns a negative error code.
Remarks
Call the function with a null lpOutput array or zero nOutBytes to find the required length.
Warning
[Changed in v11.1] This function now returns an error if it finds an illegal character in the input string (previously any non-hex character was just ignored). Whitespace characters and ASCII punctuation characters are still allowed and ignored (so "DE:AD:BE:EF" is OK) but characters like those in the range [G-Zg-z] that are obviously non-hex will cause an error.

◆ CNV_CheckUTF8()

long CNV_CheckUTF8 ( const char *  szInput)

Checks if a string only contains valid UTF-8 characters.

Deprecated:
Use CNV_CheckUTF8Bytes() instead.
Parameters
[in]szInputto be checked.
Returns
Returns zero if the string is invalid UTF-8, or a positive number if the string is valid UTF-8.

◆ CNV_CheckUTF8Bytes()

long CNV_CheckUTF8Bytes ( const unsigned char *  lpInput,
long  nBytes 
)

Checks if a byte array contains valid UTF-8 characters.

Parameters
[in]lpInputarray to be checked.
[in]nBytesnumber of bytes in input array.
Returns
Returns zero if the byte array contains invalid UTF-8, or a positive number if the byte array contains valid UTF-8, where the value of the number indicates the nature of the encoded characters (see Remarks below):
Remarks
Return values:
ReturnsValueResult
PKI_CHRS_NOT_UTF80Not valid UTF-8
PKI_CHRS_ALL_ASCII1Valid UTF-8, all chars are 7-bit ASCII
PKI_CHRS_ANSI82Valid UTF-8, contains at least one multi-byte character equivalent to 8-bit ANSI
PKI_CHRS_MULTIBYTE3Valid UTF-8, contains at least one multi-byte character that cannot be represented in a single-byte character set.

Overlong UTF-8 sequences and illegal surrogates are rejected as invalid. Strings that return PKI_CHRS_ANSI8 (2) can be converted to Latin-1 format using the CNV_Latin1FromUTF8Bytes() function. Strings that return PKI_CHRS_MULTIBYTE (3) cannot be converted to Latin-1, and strings that return PKI_CHRS_ALL_ASCII (1) are already OK because they only consist of 7-bit ASCII characters.

◆ CNV_CheckUTF8File()

long CNV_CheckUTF8File ( const char *  szFileName)

Checks if a file contains valid UTF-8 characters.

Parameters
[in]szFileNamecontaining the name of the file.
Returns
Returns zero if the file contains invalid UTF-8, or a positive number if the file contains valid UTF-8, where the value of the number indicates the nature of the encoded characters: see CNV_CheckUTF8Bytes() for more details. If there is an error, like the file is missing or cannot be read, then it returns a negative error code.
Remarks
This is the same as CNV_CheckUTF8Bytes() but for a file instead of a byte array. For more details, see CNV_CheckUTF8Bytes().

◆ CNV_HexFilter()

long CNV_HexFilter ( char *  szOutput,
const char *  szInput,
long  nStrLen 
)

Removes non-hexadecimal characters from a string.

Parameters
[out]szOutputto receive filtered characters.
[in]szInputto be filtered.
[in]nStrLenspecifying the length of the input string.
Returns
If successful, the return value is the number of characters in the filtered string; otherwise it returns a negative error code.
Remarks
Specify a zero nOutChars or an empty string for szOutput to find the required length of the output string. ANSI C users must add one to this value when allocating memory.

Assumes that the output string is at least as long as the input string.

◆ CNV_HexStrFromBytes()

long CNV_HexStrFromBytes ( char *  szOutput,
long  nOutChars,
const unsigned char *  lpInput,
long  nInputLen 
)

Encodes an array of bytes into a hexadecimal-encoded string.

Parameters
[out]szOutputto receive encoded data.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]lpInputarray of binary data to be encoded.
[in]nInputLennumber of bytes to be encoded.
Returns
If successful, the return value is the number of characters in the encoded string; otherwise it returns a negative error code.
Remarks
Specify a zero nOutChars or an empty string for szOutput to find the required length of the output string. ANSI C users must add one to this value when allocating memory.

The input array may contain bytes of any value. If vbNullString or an empty string ("") is specified for szHex or zero for nHexStrLen, the function will return the maximum possible size of the encoded string. The final result may be smaller. C/C++ programmers should add one to the returned length value when allocating memory.

◆ CNV_Latin1FromUTF8()

long CNV_Latin1FromUTF8 ( char *  szOutput,
long  nOutChars,
const char *  szInput 
)

Converts a UTF-8 string into a Latin-1 string, if possible.

Deprecated:
Use CNV_Latin1FromUTF8Bytes() instead.
Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szInputof UTF-8 characters to be converted.
Returns
If successful, the return value is a positive number indicating the number of characters in the output string, or number of characters required if nOutChars is set to zero; otherwise it returns a negative error code.

◆ CNV_Latin1FromUTF8Bytes()

long CNV_Latin1FromUTF8Bytes ( char *  szOutput,
long  nOutChars,
const unsigned char *  lpInput,
long  nBytes 
)

Converts UTF-8 encoded array of bytes into a Latin-1 string, if possible.

Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]lpInputarray containing UTF-8 encoded data.
[in]nBytesnumber of bytes in input array.
Returns
If successful, the return value is a positive number indicating the number of characters (bytes) in the output string, or number of characters required if nOutChars is set to zero; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The input must be valid UTF-8 data. Possible errors are INVALID_DATA_ERROR indicating invalid UTF-8 input and OUT_OF_RANGE_ERROR which indicates that the output would contain a character greater than 8 bits in size.

◆ CNV_NumFromBytes()

long CNV_NumFromBytes ( const unsigned char *  lpInput,
long  nBytes,
long  nOptions 
)

Converts the leftmost four bytes of an array to a 32-bit integer.

Parameters
[in]lpInputByte array to be converted.
[in]nBytesnumber of bytes.
[in]nOptionsOption flags. Select one of:
PKI_CNV_BIG_ENDIAN (0) for big-endian order (default)
PKI_CNV_LITTLE_ENDIAN for little-endian order
Returns
Decoded integer value, or zero on error.
Remarks
An array shorter than 4 bytes will be padded on the right with zeros.

◆ CNV_NumToBytes()

long CNV_NumToBytes ( unsigned char *  lpOutput,
long  nOutBytes,
long  nNumber,
long  nOptions 
)

Converts a 32-bit integer to an array of 4 bytes.

Parameters
[out]lpOutputbyte array to receive output.
[in]nOutBytessize of output array in bytes.
[in]nNumberinteger to be converted.
[in]nOptionsOption flags. Select one of:
PKI_CNV_BIG_ENDIAN (0) for big-endian order (default)
PKI_CNV_LITTLE_ENDIAN for little-endian order
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The output byte array lpOutput will contain the representation of the integer in given order. A negative nNumber will be interpreted in equivalent twos-complement unsigned form.

◆ CNV_ReverseBytes()

long CNV_ReverseBytes ( unsigned char *  lpOutput,
const unsigned char *  lpInput,
long  nBytes 
)

Reverses the order of a byte array.

Parameters
[out]lpOutputbyte array to receive output.
[in]lpInputarray of bytes to be reversed.
[in]nBytesnumber of bytes.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The output array lpOutput must be at least nBytes long. It may be the same variable as lpInput.

◆ CNV_ShortPathName()

long CNV_ShortPathName ( char *  szOut,
long  nOutChars,
const wchar_t *  szwFilePath 
)

Retrieve the Windows short path form of the specified path.

Parameters
[out]szOutBuffer to receive output.
[in]nOutCharsMaximum length of output string in bytes (excluding the terminating null).
[in]szwFilePathPath name in wide characters.
Returns
Number of characters (bytes) in or required for the output string; otherwise it returns a negative error code.
Remarks
Use this function to find the ASCII equivalent file path for a path represented in "Unicode" UTF-16 wchar_t characters. Then use this ASCII short name as an argument for an input file in any of the functions in this library that require a file name.

The file must exist. The output path is guaranteed to be in ASCII characters, and the base name and each folder name will be 8 characters or fewer. It may not give the same value on a different system. Windows only.

For the "raw" function, pass a NULL szOut or zero nOutChars to find the required output length in bytes. ANSI C users must add one to this value when allocating memory.

◆ CNV_UTF8BytesFromLatin1()

long CNV_UTF8BytesFromLatin1 ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szInput 
)

Converts a string of 8-bit Latin-1 characters into a UTF-8 encoded array of bytes.

Parameters
[out]lpOutputarray suitably dimensioned to receive output.
[in]nOutBytesspecifying the maximum number of bytes to be received.
[in]szInputof Latin-1 characters to be converted.
Returns
If successful, the return value is a positive number indicating the number of bytes in the output array, or number of bytes required if nOutBytes is set to zero; otherwise it returns a negative error code.
Remarks
Will set up to nOutBytes bytes in the output array. If nOutBytes is zero, it returns the required number of bytes.

◆ CNV_UTF8FromLatin1()

long CNV_UTF8FromLatin1 ( char *  szOutput,
long  nOutChars,
const char *  szInput 
)

Converts a string of 8-bit Latin-1 characters into UTF-8 format.

Deprecated:
Use CNV_UTF8BytesFromLatin1() instead.
Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szInputof Latin-1 characters to be converted.
Returns
If successful, the return value is a positive number indicating the number of (single-byte) characters in the output string, or number of characters required if nOutChars is set to zero; otherwise it returns a negative error code.

◆ CNV_Utf8FromWide()

long CNV_Utf8FromWide ( char *  szOut,
long  nOutChars,
const wchar_t *  wstr 
)

Maps a UTF-16 (wide character) string to a UTF-8-encoded string.

Parameters
[out]szOutBuffer to receive null-terminated UTF-8-encoded string.
[in]nOutCharsMaximum length of output string in bytes (excluding the terminating null).
[in]wstrString of wide characters to be processed.
Returns
Number of characters (bytes) in or required for the output string; otherwise it returns a negative error code.
Remarks
Use this function to convert a C/C++ string of "Unicode" UTF-16 wchar_t characters to a UTF-8-encoded string of type char.

For the "raw" ANSI function, pass a NULL szOut or zero nOutChars to find the required output length in bytes. Allocate one extra byte for the terminating null.

This function is for C/C++ programmers only. There is no VBA or .NET equivalent.

◆ COMPR_Compress()

long COMPR_Compress ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
long  nOptions 
)

Compress data using zlib compression.

Parameters
[out]lpOutputbyte buffer to receive output data.
[in]nOutBytessize of the output buffer in bytes.
[in]lpInputinput data to be compressed.
[in]nInputLenlength of input array in bytes.
[in]nOptionsoption flags. Not used in this release. Set to zero.
Returns
The number of bytes successfully copied into the output buffer or the required size in bytes. If an error occurs, it returns a negative error code.
Remarks
To determine the required size of the output buffer, call the function with nOutBytes set to zero (or lpOutput set to NULL).

◆ COMPR_Uncompress()

long COMPR_Uncompress ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
long  nOptions 
)

Uncompress data using zlib compression.

Parameters
[out]lpOutputbyte buffer to receive output data.
[in]nOutBytessize of the output buffer in bytes.
[in]lpInputinput data to be uncompressed.
[in]nInputLenlength of input array in bytes.
[in]nOptionsoption flags. Not used in this release. Set to zero.
Returns
The number of bytes successfully copied into the output buffer or the required size in bytes. If an error occurs, it returns a negative error code.
Remarks
To determine the required size of the output buffer, call the function with nOutBytes set to zero (or lpOutput set to NULL).

◆ ECC_DHSharedSecret()

long ECC_DHSharedSecret ( unsigned char *  lpZZ,
long  nOutBytes,
const char *  szIntPrivateKey,
const char *  szIntPublicKey,
long  nOptions 
)

Compute EC Diffie-Hellman (ECDH) shared secret.

Parameters
[out]lpZZBuffer to receive shared secret as an array of bytes.
[in]nOutBytesLength of output buffer in bytes.
[in]szIntPrivateKeyString containing our own private key in ephemeral "internal" form.
[in]szIntPublicKeyString containing other party's public key in "internal" form.
[in]nOptionsNot used in this release. Specify zero.
Returns
If successful, the return value is the number of bytes in or required in the output; otherwise it returns a negative error code.
Remarks
The output is the Diffie-Hellman shared secret. This may require further processing to be used in an application; for example, as input to a key derivation function. The keys are expected in ephemeral "internal" format read into a string using ECC_ReadPrivateKey, ECC_ReadPublicKey or ECC_ReadKeyByCurve. All supported NIST/SEC curves can be used as well as the safe curve X25519 (but not Ed25519 or Ed448, which are for signatures only).

◆ ECC_KeyHashCode()

long ECC_KeyHashCode ( const char *  szKeyString)

Computes the hash code of an "internal" ECC public or private key string.

Parameters
[in]szKeyStringcontaining the ECC private or public key string in internal format.
Returns
A 32-bit hash code for the key, or zero on error.
Remarks
Use this function to compare internal key strings. The hash code value will be the same for a given key. The hash code is computed to an internal algorithm and may return any integer value between -2,147,483,648 and 2,147,483,647.

If the key string is invalid, the return value is zero and a nonzero error code will be set (use PKI_ErrorCode to check). There is a very small chance (one in 4 billion) that a valid key string returns a hash code of zero.

◆ ECC_MakeKeys()

long ECC_MakeKeys ( const char *  szPubKeyFile,
const char *  szPriKeyFile,
const char *  szCurveName,
const char *  szPassword,
const char *  szParams,
long  nOptions 
)

Generates an EC public/private key pair and saves as two key files.

Parameters
[in]szPubKeyFilename of public key file to be created.
[in]szPriKeyFilename of encrypted private key file to be created.
[in]szCurveNamename of elliptic curve (see remarks).
[in]szPasswordthe password to be used for the encrypted key file.
[in]szParams(optional) parameters. Set as the empty string "" for defaults. Otherwise include a set of attribute-value pairs separated by a semi-colon ";" to set options from the following
  • count=<nnn> to set the iteration count in the encrypted private key used in the PBKDF method, e.g. "count=5000;" [default=2048]
  • prf=<hmac-name> to change the HMAC algorithm used in the PBKDF2 method, e.g. "prf=hmacWithSHA256;" [default=hmacwithSHA1]
  • rngseed=<string> to add some extra user-specified additional seed for the random number generator, e.g. "rngseed=pqrrr1234xyz;"
Valid values for hmac-name are {hmacWithSHA1|hmacWithSHA224|hmacWithSHA256|hmacWithSHA384|hmacWithSHA512}.
[in]nOptionscontaining a flag to indicate the password-based encryption scheme to be used to encrypt the private key file. Select from:
PKI_PBE_SHA_3DES (0) for "pbeWithSHAAnd3-KeyTripleDES-CBC" (default)
PKI_PBE_PBKDF2_DESEDE3 for PBKDF2 using des-EDE3-CBC
PKI_PBE_PBKDF2_AES128 for PBKDF2 using aes128-CBC
PKI_PBE_PBKDF2_AES192 for PBKDF2 using aes192-CBC
PKI_PBE_PBKDF2_AES256 for PBKDF2 using aes256-CBC
(there are more options - see security options for encrypted private keys)
and optionally add
PKI_KEY_FORMAT_PEM to save the key files in PEM form (default is binary DER-encoded format).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The public and private keys are encoded into ASN.1 values of type SubjectPublicKeyInfo and EncryptedPrivateKeyInfo respectively. Any existing files of the same names will be overwritten without warning. The password should be a string of non-zero ASCII characters.

The key is stored by default as a pair of DER-encoded binary files. Use the PKI_KEY_FORMAT_PEM flag to save in PEM-encoded format.

Supported curve names for szCurveName are:

Curve nameAlternative namesRemarks
secp192r1P-192, P_192, prime192v1NIST
secp256r1P-256, P_256, prime256v1NIST
secp224r1P-224, P_224NIST
secp384r1P-384, P_384NIST
secp521r1P-521, P_521NIST
secp256k1 Bitcoin/SEC
Ed25519 For EdDSA signatures
X25519 For ECDH key exchange
Ed448 For EdDSA signatures
X448 For ECDH key exchange
brainpoolP256r1 [RFC5639]
brainpoolP384r1 [RFC5639]
brainpoolP512r1 [RFC5639]

Valid values for the "prf" parameter in szParams are:

  • hmacWithSHA1 (default)
  • hmacWithSHA224
  • hmacWithSHA256
  • hmacWithSHA384
  • hmacWithSHA512

These are case-insensitive and work only with the PKI_PBE_PBKDF2_ options. This will override any PKI_HMAC_ flag in nOptions

Set szParams as the empty string "" for defaults.

◆ ECC_PublicKeyFromPrivate()

long ECC_PublicKeyFromPrivate ( char *  szOutput,
long  nOutChars,
const char *  szIntKeyString,
long  nOptions 
)

Converts an internal EC private key string into an internal EC public key string.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szIntKeyStringcontaining the private key as an internal key string.
[in]nOptionsnot used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a nonzero error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

Use this to derive the public key from the EC private key, where both values are represented as "internal" key strings.

◆ ECC_QueryKey()

long ECC_QueryKey ( char *  szOutput,
long  nOutChars,
const char *  szIntKeyString,
const char *  szQuery,
long  nOptions 
)

Queries an EC key string for selected information.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szIntKeyStringcontaining the key as an internal key string.
[in]szQueryspecifying the query (see Remarks below).
[in]nOptionsnot used in this release. Specify zero.
Returns
If successful, the return value is a positive integer indicating either the result itself (if the result is a number) or the number of characters in the output string (if the query is looking for a string). If the item queried cannot be found, the return value is zero. If there is an error (e.g. invalid input), it returns a negative error code.
Remarks
Valid queries are (case-insensitive):
Query StringReturnsData Type
curveNameName of the curveString
keyBitsNumber of bits in the keyNumber
isPrivate1 if the key is a private key; 0 if notNumber
isValid1 if the key is valid; 0 if notNumber
privateKeyValue of the private key in hex formatString
publicKeyValue of the public key in hex format

String

The "raw" VBA/C function behaves differently depending on whether the output is a string or a number. If the result data type is a number then it returns the value directly. If the result is a string, then it sets szOutput and returns the number of characters in the string. The required number of characters can be found by passing zero for nOutChars or a null string for szOutput. ANSI C users must add one to this value when allocating memory.

Note that the VBA wrapper function and the C#/VB.NET methods always return a string, which is different from the behaviour of the raw VB6/C function.

◆ ECC_ReadKeyByCurve()

long ECC_ReadKeyByCurve ( char *  szOutput,
long  nOutChars,
const char *  szHexKey,
const char *  szCurveName,
long  nOptions 
)

Reads an EC key from its hexadecimal (base16) representation.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szHexKeycontaining a hexadecimal (base16) representation of the key
[in]szCurveNamecontaining the name of the elliptic curve (see remarks)
[in]nOptionsFor Safe Curves specify PKI_ECC_PRIVATE_KEY or PKI_ECC_PUBLIC_KEY to indicate that the key value represents a private or public key, respectively. Otherwise, nOptions is ignored.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a nonzero error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The output string is an ephemeral internal key string valid only for the current session. This internal key string can be used directly by functions such as ECC_DHSharedSecret or SIG_SignData. You can analyze the key string using ECC_QueryKey or save it in one of the supported key file formats using ECC_SaveKey or ECC_SaveEncKey. The input string is expected to be the hexadecimal (base16) representation of a private or public key.

NIST/SEC/Brainpool curves: A private key is represented by the hexadecimal encoding of its integer value encoded in octets as per section 3 of [RFC5915]. A public key is represented by the hexadecimal encoding of the octet string as defined in section 4.3.6 of [X9-63]; that is, 04||Px||Py.

Only the uncompressed form of a public key (beginning "04") is supported due to patent issues. It is an error if the key value is out of range or not a valid point on the curve.

Safe curves: Both private and public keys are represented by the hexadecimal encoding of its integer value encoded as a byte array in little-endian form as per [RFC7748] and [RFC8032]. For Ed25519 and X25519, the input string szHexKey is always expected to be a hexadecimal representation of exactly 32 bytes. Set nOptions as PKI_ECC_PRIVATE_KEY (default 0) or PKI_ECC_PUBLIC_KEY to indicate whether the key value represents a private or public key, respectively. Any 32-byte key string will be accepted as input and any required bit masking (e.g. for an X25519 private key) will be applied before use.

Supported curve names for szCurveName are:

Curve nameAlternative namesRemarks
secp192r1P-192, P_192, prime192v1NIST
secp224r1P-224, P_224NIST
secp256r1P-256, P_256, prime256v1NIST
secp384r1P-384, P_384NIST
secp521r1P-521, P_521NIST
secp256k1 SEC/Bitcoin
Ed25519 Safe EdDSA curve [RFC8032]
Ed448 Safe EdDSA curve [RFC8032]
X25519 Safe ECDH curve [RFC7748]
X448 Safe ECDH curve [RFC7748]
brainpoolP256r1 [RFC5639]
brainpoolP384r1 [RFC5639]
brainpoolP512r1 [RFC5639]

◆ ECC_ReadPrivateKey()

long ECC_ReadPrivateKey ( char *  szOutput,
long  nOutChars,
const char *  szKeyFileOrString,
const char *  szPassword,
long  nOptions 
)

Reads an EC private key from a file into an internal key string.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyFileOrStringspecifying either the name of file containing the key or a string containing the key in PEM format.
[in]szPasswordpassword for the key file, if encrypted; otherwise set as "".
[in]nOptionsnot used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a nonzero error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This reads both encrypted private keys and the unencrypted PKCS#8 PrivateKeyInfo and ECPrivateKey formats. Set szPassword as the empty string "" if not required.

◆ ECC_ReadPublicKey()

long ECC_ReadPublicKey ( char *  szOutput,
long  nOutChars,
const char *  szKeyFileOrString,
long  nOptions 
)

Reads an EC public key from a file into an internal key string.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyFileOrStringspecifying either the name of file containing the key or a string containing the key in PEM format.
[in]nOptionsnot used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

[New in v12.0] An EC public key can also be read directly from an X.509 certificate (or its base64 representation).

◆ ECC_SaveEncKey()

long ECC_SaveEncKey ( const char *  szFileOut,
const char *  szIntKeyString,
const char *  szPassword,
const char *  szParams,
long  nOptions 
)

Saves an internal EC private key string to an encrypted private key file.

Parameters
[in]szFileOutname of key file to be created.
[in]szIntKeyStringthe private key in an internal key string.
[in]szPasswordthe password to be used for the encrypted key file
[in]szParams(optional) parameters. Set as the empty string "" for defaults. Otherwise include a set of attribute-value pairs separated by a semi-colon ";" to set options from the following
  • count=<nnn> to set the iteration count used in the PBKDF method, e.g. "count=5000;" [default=2048]
  • prf=<hmac-name> to change the HMAC algorithm used in the PBKDF2 method, e.g. "prf=hmacWithSHA256;" [default=hmacwithSHA1]
[in]nOptionscontaining a flag to indicate the algorithm to be used to encrypt the private key file. Select from:
PKI_PBE_SHA_3DES (0) for "pbeWithSHAAnd3-KeyTripleDES-CBC" (default)
PKI_PBE_PBKDF2_DESEDE3 for PBKDF2 using des-EDE3-CBC
PKI_PBE_PBKDF2_AES128 for PBKDF2 using aes128-CBC
PKI_PBE_PBKDF2_AES192 for PBKDF2 using aes192-CBC
PKI_PBE_PBKDF2_AES256 for PBKDF2 using aes256-CBC
(there are more options - see security options for encrypted private keys)
and optionally add
PKI_KEY_FORMAT_PEM to save the key files in PEM form (default is binary DER-encoded format).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
Use this function to save a private key in a new encrypted file format, perhaps with stronger encryption. Use the PKI_KEY_FORMAT_PEM flag to save in PEM-encoded format. You must first read in the old private key file into an "internal" private key string which is only valid for the current session.

Valid values for the "prf" parameter in szParams are:

  • hmacWithSHA1 (default)
  • hmacWithSHA224
  • hmacWithSHA256
  • hmacWithSHA384
  • hmacWithSHA512

These are case-insensitive and work only with the PKI_PBE_PBKDF2_ options. This will override any PKI_HMAC_ flag in nOptions

Set szParams as the empty string "" for defaults.

◆ ECC_SaveKey()

long ECC_SaveKey ( const char *  szFileOut,
const char *  szIntKeyString,
long  nOptions 
)

Saves an internal EC key string to an unencrypted key file.

Parameters
[in]szFileOutname of key file to be created.
[in]szIntKeyStringthe private or public EC key in an internal key string.
[in]nOptionschoose one of
  • PKI_DEFAULT (0) to save the key in the default format (see remarks).
  • PKI_KEY_TYPE_PKCS8 to save a NIST/SEC curve private key in PKCS#8 format.
and optionally add any of
PKI_KEY_FORMAT_PEM to save the key file in PEM form (default is binary DER-encoded format).
PKI_KEY_LEGACY to save a safe key in "legacy" PKCS#8 v1 format (default is v2 OneAsymmetricKey).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
EC public keys are always saved in SubjectPublicKeyInfo format [RFC5480]. By default, NIST/SEC curve private keys are saved in ECPrivateKey format [RFC5915]. Use the PKI_KEY_TYPE_PKCS8 option to save in PKCS#8 PrivateKeyInfo format [RFC5208].

[New in v22.0] Safe curve private keys (X25519, Ed25519, X448 and Ed448) are always saved in PKCS#8 v2 OneAsymmetricKey format including the public key [RFC5958]. Add the option PKI_KEY_LEGACY to save in older PKCS#8 v1 PrivateKeyInfo format [RFC5208] excluding the public key.

To save a private key in encrypted form, use ECC_SaveEncKey.

◆ HASH_Bytes()

long HASH_Bytes ( unsigned char *  lpOutput,
long  nOutBytes,
const void *  lpMessage,
long  nMsgLen,
long  nOptions 
)

Creates a message digest hash as a byte array from byte data.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]lpOutputarray to receive the hash digest.
[in]nOutBytesspecifying the length in bytes of the output array.
[in]lpMessagearray containing the message data
[in]nMsgLenspecifying length of the message data in bytes.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
PKI_HASH_MD2 to use the MD2 algorithm (legacy applications)
PKI_HASH_RMD160 to use the RIPEMD-160 algorithm
PKI_HASH_BTC160 to use the Bitcoin160 algorithm, RIPEMD160(SHA256(m))
and optionally add
PKI_HASH_DOUBLE to compute a double hash, HASH(HASH(m))
Returns
If successful, the return value is the number of bytes in the hash digest array; otherwise it returns a negative error code.
Remarks
Specify a zero nDigLen parameter to find out the required length of the output array. The maximum possible length is PKI_MAX_HASH_BYTES. Hint: SHA-1 requires 20 bytes; MD5 and MD2 require 16 bytes; SHA-512 requires 64. The final digest will be truncated to the specified length if less than the expected size.

◆ HASH_File()

long HASH_File ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szFileName,
long  nOptions 
)

Creates a message digest hash in byte format for a file.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]lpOutputarray to receive the hash digest.
[in]nOutBytesspecifying the length in bytes of the output array.
[in]szFileNamecontaining the name of the file.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
PKI_HASH_MD2 to use the MD2 algorithm (legacy applications)
PKI_HASH_RMD160 to use the RIPEMD-160 algorithm
PKI_HASH_BTC160 to use the Bitcoin160 algorithm, RIPEMD160(SHA256(m))
and optionally add
PKI_HASH_DOUBLE to compute a double hash, HASH(HASH(m))
and add
PKI_HASH_MODE_TEXT to hash in "text" mode instead of default "binary" mode
Returns
If successful, the return value is the number of bytes in the hash digest array; otherwise it returns a negative error code.
Remarks
Specify a zero nOutBytes parameter to find out the required length of the output array. The maximum size will be PKI_MAX_HASH_BYTES. The final digest will be truncated to the specified length if less than the expected size. Add the option PKI_HASH_MODE_TEXT to work in "text" mode where CR-LF pairs are treated as a single newline (LF) character. (This option is provided if you need to pass hash digests of text files between Windows and Unix systems.) The default mode is "binary" where each byte is treated individually. Only ANSI characters are supported in file names and paths.

◆ HASH_HexFromBytes()

long HASH_HexFromBytes ( char *  szOutput,
long  nOutChars,
const void *  lpMessage,
long  nMsgLen,
long  nOptions 
)

Creates a message digest hash in hexadecimal format from byte (or string) data.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]szOutputto receive hash digest in hexadecimal format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]lpMessagearray containing the message data; or
[in]nMsgLenspecifying length of the message data in bytes.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
PKI_HASH_MD2 to use the MD2 algorithm (legacy applications)
PKI_HASH_RMD160 to use the RIPEMD-160 algorithm
PKI_HASH_BTC160 to use the Bitcoin160 algorithm, RIPEMD160(SHA256(m))
and optionally add
PKI_HASH_DOUBLE to compute a double hash, HASH(HASH(m))
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The maximum number of output characters is PKI_MAX_HASH_CHARS (C/C++ users add one).

The final digest will be truncated to the specified length if less than the expected size.

◆ HASH_HexFromFile()

long HASH_HexFromFile ( char *  szOutput,
long  nOutChars,
const char *  szFileName,
long  nOptions 
)

Creates a message digest hash in hexadecimal format for a file.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]szOutputto receive hash digest in hexadecimal format.
[in]nOutCharsspecifying the maximum number of characters to be received in characters.
[in]szFileNamecontaining the name of the file.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
PKI_HASH_MD2 to use the MD2 algorithm (legacy applications)
PKI_HASH_RMD160 to use the RIPEMD-160 algorithm
PKI_HASH_BTC160 to use the Bitcoin160 algorithm, RIPEMD160(SHA256(m))
and optionally add
PKI_HASH_DOUBLE to compute a double hash, HASH(HASH(m))
and add
PKI_HASH_MODE_TEXT to hash in "text" mode instead of default "binary" mode
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The maximum number of output characters will be PKI_MAX_HASH_CHARS (C/C++ users add one). The final digest will be truncated to the specified length if less than the expected size. Add the option PKI_HASH_MODE_TEXT to work in "text" mode where CR-LF pairs are treated as a single newline (LF) character. (This option is provided if you need to pass hash digests of text files between Windows and Unix systems.) The default mode is "binary" where each byte is treated individually. Only ANSI characters are supported in file names and paths.

◆ HASH_HexFromHex()

long HASH_HexFromHex ( char *  szOutput,
long  nOutChars,
const char *  szMsgHex,
long  nOptions 
)

Creates a message digest hash in hexadecimal format from data in a hexadecimal-encoded string.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]szOutputto receive hash digest in hexadecimal format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szMsgHexcontaining the message data in hexadecimal-encoded format.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
PKI_HASH_MD2 to use the MD2 algorithm (legacy applications)
PKI_HASH_RMD160 to use the RIPEMD-160 algorithm
PKI_HASH_BTC160 to use the Bitcoin160 algorithm, RIPEMD160(SHA256(m))
and optionally add
PKI_HASH_DOUBLE to compute a double hash, HASH(HASH(m))
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The maximum number of output characters is PKI_MAX_HASH_CHARS (C/C++ users add one). The final digest will be truncated to the specified length if less than the expected size. Valid input hex digits are [0-9A-Fa-f]. The output is always in lower-case letters.

◆ HASH_Length()

long HASH_Length ( long  nAlgId)

Return length of message digest output in bytes.

Parameters
[in]nAlgIdAlgorithm Id flag. Select one of PKI_HASH_* or PKI_HMAC_*, for example:
PKI_HASH_SHA1 SHA-1 algorithm
PKI_HASH_SHA224 SHA-224 algorithm
PKI_HASH_SHA256 SHA-256 algorithm
PKI_HASH_SHA384 SHA-384 algorithm
PKI_HASH_SHA512 SHA-512 algorithm
PKI_HASH_SHA3_224 SHA-3-224 algorithm
PKI_HASH_SHA3_256 SHA-3-256 algorithm
PKI_HASH_SHA3_384 SHA-3-384 algorithm
PKI_HASH_SHA3_512 SHA-3-512 algorithm
PKI_HASH_MD5 MD5 algorithm
PKI_HASH_MD2 MD2 algorithm
PKI_HASH_RMD160 RIPEMD-160 algorithm
PKI_HASH_BTC160 Bitcoin160 algorithm, RIPEMD160(SHA256(m))
Returns
Length of the hash function output in bytes; else a negative error code.
Remarks
[New in v20.5]

◆ HMAC_Bytes()

long HMAC_Bytes ( unsigned char *  lpOutput,
long  nOutBytes,
const void *  lpMessage,
long  nMsgLen,
const void *  lpKey,
long  nKeyLen,
long  nOptions 
)

Creates a keyed-hash based message authentication code (HMAC) as a byte array from byte data.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]lpOutputarray to receive the hash digest.
[in]nOutBytesspecifying the length in bytes of the output array.
[in]lpMessagearray containing the message data
[in]nMsgLenspecifying length of the message data in bytes.
[in]lpKeyarray containing the key
[in]nKeyLenspecifying length of the key in bytes.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
If successful, the return value is the number of bytes in the output array; otherwise it returns a negative error code.
Remarks
Specify a zero nDigLen parameter to find out the required length of the output array, or use the appropriate PKI_XXX_BYTES constant. The maximum possible length is PKI_MAX_HASH_BYTES. The final digest will be truncated to the specified length if less than the expected size. MD2 is not available with the HMAC functions.

◆ HMAC_HexFromBytes()

long HMAC_HexFromBytes ( char *  szOutput,
long  nOutChars,
const void *  lpMessage,
long  nMsgLen,
const void *  lpKey,
long  nKeyLen,
long  nOptions 
)

Creates a keyed-hash based message authentication code (HMAC) in hexadecimal format from byte data.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]szOutputto receive output in hexadecimal format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]lpMessagearray containing the message data in a byte array
[in]nMsgLenspecifying length of the message data in bytes.
[in]lpKeyarray containing the key in a byte array
[in]nKeyLenspecifying length of the key in bytes.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The maximum number of output characters is PKI_MAX_HASH_CHARS (C/C++ users add one). C/C++ users should add one to this value when allocating memory. The final digest will be truncated to the specified length if less than the expected size. MD2 is not available with the HMAC functions.

◆ HMAC_HexFromHex()

long HMAC_HexFromHex ( char *  szOutput,
long  nOutChars,
const char *  szMsgHex,
const char *  szKeyHex,
long  nOptions 
)

Creates a keyed-hash based message authentication code (HMAC) in hexadecimal format from data in hexadecimal-encoded strings.

The hash algorithm to use is passed in the options parameter.

Parameters
[out]szOutputto receive output in hexadecimal format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szMsgHexcontaining the message data in hexadecimal-encoded format.
[in]szKeyHexcontaining the key in hexadecimal-encoded format.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_SHA3_224 to use the SHA-3-224 algorithm
PKI_HASH_SHA3_256 to use the SHA-3-256 algorithm
PKI_HASH_SHA3_384 to use the SHA-3-384 algorithm
PKI_HASH_SHA3_512 to use the SHA-3-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The maximum number of output characters is PKI_MAX_HASH_CHARS (C/C++ users add one). C/C++ users should add one to this value when allocating memory. The final digest will be truncated to the specified length if less than the expected size. MD2 is not available with the HMAC functions.

Note the order of parameters here (data, key) is different from the usual order HMAC(key, text).

◆ HPKE_DerivePrivateKey()

long HPKE_DerivePrivateKey ( char *  szOutput,
long  nOutChars,
const unsigned char *  lpIkm,
long  nIkmLen,
const char *  szCurveName,
const char *  szParams,
long  nOptions 
)

Derive an EC private key in a deterministic manner from input keying material using the DeriveKeyPair algorithm in RFC9180.

Parameters
[out]szOutputstring of sufficient length to receive the derived private key.
[in]nOutCharsmaximum number of characters to be received.
[in]lpIkmbyte array containing the input key material (ikm). This must have length in bytes at least as long as the key to be produced.
[in]nIkmLenlength of the input key material in bytes.
[in]szCurveNamename of ECDH curve: Specify one of:
"P-256" | "P-384" | "P-521" | "X25519" | "X448"
[in]szParams(optional) parameters. Not used in this version. Set as the empty string "".
[in]nOptionsOption flags. Select one of:
Zero (0) to output the private key in ephemeral "internal" key format (default); or
PKI_ENCODE_HEX to output the private key in serialized hex form.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
By default the key is output as an ephemeral "internal" key string, which can be used directly with ECC_SaveKey, ECC_SaveEncKey, ECC_PublicKeyFromPrivate, ECC_DHSharedSecret and ECC_QueryKey. If nOptions is set to PKI_ENCODE_HEX then the key is output in serialized hexadecimal form in the same manner as the test vectors in [RFC9180] (without the clamping).

For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This function derives an ECDH private key in the deterministic manner described in [RFC9180] using user-provided input key material (ikm). There is very, very small chance that a valid key cannot be generated from the ikm; in which case the function will return a negative KEYGEN_FAILED_ERROR error code.

The input key material must have length in bytes at least as long as the key to be produced (Nsk) or a BAD_LENGTH_ERROR error code will be returned. The values of Nsk (the length in bytes of a Diffie-Hellman private key) for the supported EC curves are as follows:

EC curve groupNsk
P-25632
P-38448
P-52166
X2551932
X44856

The KDF to be used is fixed by the EC curve group. See Hybrid Public Key Encryption (HPKE).

◆ HPKE_LabeledExpand()

long HPKE_LabeledExpand ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpPrk,
long  nPrkLen,
const char *  szLabel,
const unsigned char *  lpInfo,
long  nInfoLen,
const char *  szCurveName,
const char *  szParams,
long  nOptions 
)

Compute the output of the LabeledExpand function as defined in RFC9180.

Parameters
[out]lpOutputbyte array to be filled with output keying material.
[in]nOutputLenrequired size of the output key in bytes (L).
[in]lpPrkbyte array containing the pseudorandom key (prk).
[in]nPrkLenlength of prk in bytes.
[in]szLabellabel string.
[in]lpInfobyte array containing optional string info
[in]nInfoLenlength of info in bytes (can be zero)
[in]szCurveNamename of ECDH curve used in scheme (required): Specify one of:
"P-256" | "P-384" | "P-521" | "X25519" | "X448"
[in]szParams(optional) parameters. Not used in this version. Set as the empty string "".
[in]nOptionsOption flags. Use to specify the AEAD encryption algorithm used in the scheme (if applicable). Specify either:
Zero (0) to indicate that the KDF is being used inside a KEM algorithm
or, if used in the remainder of HPKE, one of:
PKI_AEAD_AES_128_GCM
PKI_AEAD_AES_256_GCM
PKI_AEAD_CHACHA20_POLY1305
Returns
If successful, the return value is zero; otherwise it returns a negative error code.
Remarks
The output buffer for the output keying material lpOutput must exist and must have been dimensioned to at least the required length given in nOutBytes, which must be a positive number. Note that the return value on success is zero.

The LabeledExpand function is defined in section 4 of [RFC9180]. It uses the "expand" stage of the HKDF function [RFC5869].

Because this is a standalone function with no context, the ECDH curve group used in the scheme must be specified. This automatically fixes the KDF and associated HMAC algorithm to be used as per Table 2 of [RFC9180]. In the case where the KDF is being used inside a KEM algorithm, the AEAD algorithm is not used and nOptions must be set to zero . In the other case where the KDF is being used in the remainder of the HPKE scheme, an explicit AEAD algorithm must be specified in nOptions. For more details see Hybrid Public Key Encryption (HPKE).

◆ HPKE_LabeledExtract()

long HPKE_LabeledExtract ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpSalt,
long  nSaltLen,
const char *  szLabel,
const unsigned char *  lpIkm,
long  nIkmLen,
const char *  szCurveName,
const char *  szParams,
long  nOptions 
)

Compute the output of the LabeledExtract function as defined in RFC9180.

Parameters
[out]lpOutputbyte array to be filled with a pseudorandom key of fixed length.
[in]nOutputLenlength of the output array in bytes.
[in]lpSaltbyte array containing the optional salt.
[in]nSaltLenlength of salt in bytes (can be zero).
[in]szLabellabel string.
[in]lpIkmbyte array containing input keying material (ikm).
[in]nIkmLenlength of ikm in bytes.
[in]szCurveNamename of ECDH curve used in scheme (required): Specify one of:
"P-256" | "P-384" | "P-521" | "X25519" | "X448"
[in]szParams(optional) parameters. Not used in this version. Set as the empty string "".
[in]nOptionsOption flags. Use to specify the AEAD encryption algorithm used in the scheme (if applicable). Specify either:
Zero (0) to indicate that the KDF is being used inside a KEM algorithm
or, if used in the remainder of HPKE, one of:
PKI_AEAD_AES_128_GCM
PKI_AEAD_AES_256_GCM
PKI_AEAD_CHACHA20_POLY1305
Returns
If successful, the return value is the number of bytes in or required for the output; otherwise it returns a negative error code. otherwise it returns a negative error code.
Remarks
The LabeledExtract function is defined in section 4 of [RFC9180]. It uses the "extract" stage of the HKDF function [RFC5869]. It outputs a fixed value of bytes equal to the length (Nh) of the underlying HMAC function used by the KDF algorithm.

Because this is a standalone function with no context, the ECDH curve group used in the scheme must be specified. This automatically fixes the KDF and associated HMAC algorithm to be used as per Table 2 of [RFC9180]. In the case where the KDF is being used inside a KEM algorithm, the AEAD algorithm is not used and nOptions must be set to zero . In the other case where the KDF is being used in the remainder of the HPKE scheme, an explicit AEAD algorithm must be specified in nOptions. For more details see Hybrid Public Key Encryption (HPKE).

◆ KDF_Bytes()

long KDF_Bytes ( unsigned char *  lpOutput,
long  nOutBytes,
const void *  lpIKM,
long  nIkmLen,
const void *  lpInfo,
long  nInfoLen,
const char *  szParams,
long  nOptions 
)

Generate a key-encryption key (KEK) from input keying material using a key derivation function (KDF).

Parameters
[out]lpOutputbyte array to be filled with output key material (OKM/KEK) (cannot be NULL).
[in]nOutputLenrequired size of the output key in bytes (must be greater than zero).
[in]lpIKMbyte array containing the input key material/shared secret value (denoted variously as IKM/K/Z/ZZ).
[in]nIkmLenlength of the input key material in bytes.
[in]lpInfobyte array containing the optional SharedInfo (otherInfo/key derivation parameter/kdp).
[in]nInfoLenlength of the SharedInfo in bytes.
[in]szParams(optional) parameters. Set as the empty string "" for defaults. Otherwise include a set of attribute-value pairs separated by a semi-colon ";" to set options from the following
  • salt=<hex-digits> to set the optional salt parameter for the HKDF algorithm encoded in hex format, e.g. "salt=606162636465666768696a6b6c6d6e6f;" [default=no salt]
[in]nOptionsOption flags. Select one of:
PKI_KDF_X963 to use the the ANSI-X9.63-KDF key derivation function (default)
PKI_KDF_HKDF to use the HMAC-based Key Derivation Function (HKDF) from RFC 5869
PKI_KDF_KDF2 to use KDF2 from ANSI-X9.44. New in [v23.0]
PKI_KDF_KDF3 to use KDF3 from ANSI-X9.44. New in [v23.0]
and select one hash algorithm to use with the key derivation function:
PKI_HASH_SHA1 (0) to use the SHA-1 hash algorithm (default - CAUTION)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm [minimum recommended]
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The output buffer for the output key material lpOutput must exist and must have been dimensioned to at least the required length given in nOutBytes, which must be a positive number. Note that the return value on success is zero.

The ANSI-X9.63-KDF key derivation function is described in section 3.6.1 of [SEC1]. The HMAC-based Key Derivation Function (HKDF) is described in [RFC5869]. KDF2 and KDF3 are described in ANSI X9.44 [X9-44].

◆ KDF_ForCms()

long KDF_ForCms ( unsigned char *  lpOutput,
long  nOutBytes,
const void *  lpZZ,
long  nZzLen,
const void *  lpUkm,
long  nUkmLen,
const char *  szParams,
long  nOptions 
)

Generate a key-encryption key (KEK) for ECDH key exchange in a CMS EnvelopedData object.

Parameters
[out]lpOutputbyte array to be filled with output key material (OKM/KEK).
[in]nOutputLenrequired size of the output key in bytes.
[in]lpZZbyte array containing the input key material/shared secret value (denoted variously as ZZ/Z/K/IKM).
[in]nZzLenlength of the shared secret material in bytes.
[in]lpUkm(optional) byte array containing user key material (ukm)
[in]nUkmLenlength of user key material (ukm) in bytes.
[in]szParams(optional) parameters. Not used in this version. Set as the empty string "".
[in]nOptionsOption flags. Select one of:
PKI_KDF_X963 to use the the ANSI-X9.63-KDF key derivation function (default) or
PKI_KDF_HKDF to use the HMAC-based Key Derivation Function (HKDF) from RFC 5869;
and select one hash algorithm to use with the key derivation function:
PKI_HASH_SHA1 (0) to use the SHA-1 hash algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm [minimum recommended]
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
and select one option to specify the key wrap algorithm (no default):
PKI_KWRAP_3DES to use cms3DESwrap
PKI_KWRAP_AES128 to use aes128-wrap
PKI_KWRAP_AES192 to use aes192-wrap
PKI_KWRAP_AES256 to use aes256-wrap
Returns
If successful, the return value is the number of bytes in or required for the output key material; otherwise it returns a negative error code.
Remarks
This is a specialist function using the key definition algorithms described in [RFC5753] and [RFC8418] when used for key agreement with ECDH in a CMS EnvelopedData object using the ECC-CMS-SharedInfo structure.

Note the behaviour of this function is different from KDF_KeyBytes as the length of the output is fixed by the key wrap algorithm and is not an arbitrary number. The function returns the number of bytes in the output key material, not zero on success. Specify a zero nOutChars or NULL for szOutput to find the required number of bytes for the given key wrap algorithm. The output buffer for the output key material lpOutput must have been dimensioned to at least the required length in nOutBytes.

When using ECDH with EnvelopedData, the key-encryption keys are derived using the ECC-CMS-SharedInfo type, described in section 7.2 of [RFC5753] (the SharedInfo input to the KDF is the DER-encoded ECC-CMS-SharedInfo structure).

The processing of the ukm with the HKDF key derivation function is described in section 2.2 of RFC8418.

◆ OCSP_MakeRequest()

long OCSP_MakeRequest ( char *  szOutput,
long  nOutChars,
const char *  szIssuerCert,
const char *  szCertFileOrSerialNum,
const char *  szExtensions,
long  nOptions 
)

Creates an Online Certification Status Protocol (OCSP) request as a base64 string.

Parameters
[out]szOutputto receive output in base64 format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szIssuerCertwith name of issuer's X.509 certificate file (or base64 representation).
[in]szCertFileOrSerialNumwith either the name of X.509 certificate file to be checked or its serial number in hexadecimal format preceded by "#x".
[in]szExtensionsNot used. Set as empty string "" or NULL.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The output is a base64 string suitable for an OCSP request to an Online Certificate Status Manager. The issuer's X.509 certficate must be specified. The certificate to be checked can either be specified directly as a filename or as a serialNumber in hexadecimal format preceded by "#x", e.g. "#x01deadbeef". If the latter format is used, it must be in hexadecimal format, so the serial number 10 would be passed as "#x0a". It is an error (NO_MATCH_ERROR) if the issuer's name of the certificate to be checked does not match the subject name of the issuer's certificate. The default hash algorithm is SHA-1. Most Online Certificate Status Managers should accept MD5 and SHA-1. Other hash algorithms may not be accepted.

One way to obtain a response is to paste the URL in the address bar of a web browser to return the status information. The base64 value produced by this function should first be URL-encoded (i.e. "/" replaced by "%2F", "+" replaced by "%2B", and "=" by "%3D"). For example, typing in the Firefox browser URL box

http://ocsp.comodoca.com/MFIwUDBOMEwwSjAJBgUrDgMCGgUABBRtl6lMY2%2BiPob4twryIF%2BFfgUdvwQUK8NGq7oOyWUqRtF5R8Ri4uHa%2FLgCEQD7xyMijIyAItiFkiPe5wZg

should offer to save a file with a name like MFIwUDBOME.... This contains the response, which is a binary file that can be examined using the OCSP_ReadResponse() function.

◆ OCSP_ReadResponse()

long OCSP_ReadResponse ( char *  szOutput,
long  nOutChars,
const char *  szResponseFile,
const char *  szIssuerCert,
const char *  szExtensions,
long  nOptions 
)

Reads a response to an Online Certification Status Protocol (OCSP) request and outputs the main results in text form.

Parameters
[out]szOutputto receive output as ordinary text.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szResponseFilewith the name of the file containing the response data in BER format.
[in]szIssuerCert(optional) with name of issuer's X.509 certificate file (or base64 representation).
[in]szExtensionsNot used. Set as empty string "" or NULL.
[in]nOptionsOption flags. For future use. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The output is a text string outlining the main results in the response data. Typical result strings are:

Successful response:
 Produced at 2010-03-18T00:09:28Z
 CertStatus=good
 SerialNumber=00FBC723228C8C8022D8859223DEE70660
Successful response:
 Produced at 2010-03-27T12:13:11Z
 CertStatus=revoked at 2009-05-29T19:23:16Z
 SerialNumber=7FFED5D77FD1AEEC63716CA220B098A9
malformedRequest.
unauthorized.

Note that a revoked certificate will still result in a "Successful response".

The issuer's X.509 certficate szIssuerCert is optional. If provided, it will be used to check the signature on the OCSP reponse and and an error will result if the signature is not valid. CAUTION: For some CAs (e.g. VeriSign) the key used to sign the OCSP response is not the same as the key in the issuer's certificate, so specifying the issuer's certificate in this case will result in a signature error. If you can separately obtain the certificate used to sign the OCSP response, then specify this as the szIssuerCert; otherwise leave as the empty string "".

◆ PAD_BytesBlock()

long PAD_BytesBlock ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
long  nBlkLen,
long  nOptions 
)

Creates an input block suitably padded for encryption by a block cipher in ECB or CBC mode.

Parameters
[out]lpOutputarray to be filled with padded encryption block.
[in]nOutBytesspecifying the size of the output array in bytes.
[in]lpInputarray containing the plaintext bytes to be padded.
[in]nInputLenspecifying the length of the plaintext in bytes.
[in]nBlkLenspecifying the cipher block length in bytes (8 or 16).
[in]nOptionsoption flags. Select one of:
PKI_PAD_DEFAULT (0) to use the default PKCS5 padding
PKI_PAD_PKCS5 to use Pkcs5Padding (same as default)
PKI_PAD_1ZERO to use OneAndZeroesPadding
PKI_PAD_AX923 to use the padding scheme described in ANSI X9.23
PKI_PAD_W3C to use the padding scheme described in W3C <https://www.w3.org/TR/xmlenc-core1/#sec-Padding>
Returns
If successful, the return value is the number of bytes in the output; otherwise it returns a negative error code.
Remarks
The output will be padded according to the convention specified. If nOutBytes is set to zero or lpOutput set to 0 (or NULL in C or ByVal 0& in VBA) then the required number of bytes will be returned. The output is always longer than the input. Only block lengths of 8 or 16 bytes are supported.

◆ PAD_HexBlock()

long PAD_HexBlock ( char *  szOutput,
long  nOutChars,
const char *  szInput,
long  nBlkLen,
long  nOptions 
)

Creates a hex-encoded input block suitably padded for encryption by a block cipher in ECB or CBC mode.

Parameters
[out]szOutputto receive the hexadecimal-encoded padded encryption block.
[in]nOutCharsspecifying the maximum number of characters in szOutput.
[in]szInputcontaining the hexadecimal-encoded data to be padded.
[in]nBlkLenspecifying the cipher block length in bytes (8 or 16).
[in]nOptionsoption flags. Select one of:
PKI_PAD_DEFAULT (0) to use the default PKCS5 padding
PKI_PAD_PKCS5 to use Pkcs5Padding (same as default)
PKI_PAD_1ZERO to use OneAndZeroesPadding
PKI_PAD_AX923 to use the padding scheme described in ANSI X9.23
PKI_PAD_W3C to use the padding scheme described in W3C <https://www.w3.org/TR/xmlenc-core1/#sec-Padding>
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The output will be padded according to the convention specified in nOptions.

The output is always longer than the input. Only block lengths of 8 or 16 bytes are supported.

◆ PAD_UnpadBytes()

long PAD_UnpadBytes ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
long  nBlkLen,
long  nOptions 
)

Removes the padding from an encryption block.

Parameters
[out]lpOutputarray to be filled with the output.
[in]nOutBytesspecifying the size of the output array in bytes.
[in]lpInputarray containing the padded data.
[in]nInputLenspecifying the length of the input in bytes.
[in]nBlkLenspecifying the cipher block length in bytes (8 or 16).
[in]nOptionsoption flags. Select one of:
PKI_PAD_DEFAULT (0) to use the default PKCS5 padding
PKI_PAD_PKCS5 to use Pkcs5Padding (same as default)
PKI_PAD_1ZERO to use OneAndZeroesPadding
PKI_PAD_AX923 to use the padding scheme described in ANSI X9.23
PKI_PAD_W3C to use the padding scheme described in W3C <https://www.w3.org/TR/xmlenc-core1/#sec-Padding>
Returns
If successful, the return value is the number of bytes in the output; otherwise it returns a negative error code.
Remarks
The padding is expected according to the convention specified.

If nOutBytes is set to zero or lpOutput set to 0 (or NULL in C or ByVal 0& in VBA) then the required number of bytes will be returned. The output is always shorter than the input. Only block lengths of 8 or 16 bytes are supported.

◆ PAD_UnpadHex()

long PAD_UnpadHex ( char *  szOutput,
long  nOutChars,
const char *  szInput,
long  nBlkLen,
long  nOptions 
)

Removes the padding from a hex-encoded encryption block.

Parameters
[out]szOutputto receive the hexadecimal-encoded output.
[in]nOutCharsspecifying the maximum number of characters in szOutput.
[in]szInputcontaining the hexadecimal-encoded padded data.
[in]nBlkLenspecifying the cipher block length in bytes (8 or 16).
[in]nOptionsoption flags. Select one of:
PKI_PAD_DEFAULT (0) to use the default PKCS5 padding
PKI_PAD_PKCS5 to use Pkcs5Padding (same as default)
PKI_PAD_1ZERO to use OneAndZeroesPadding
PKI_PAD_AX923 to use the padding scheme described in ANSI X9.23
PKI_PAD_W3C to use the padding scheme described in W3C <https://www.w3.org/TR/xmlenc-core1/#sec-Padding>
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
The padding is expected according to the convention specified in nOptions.

The output is always shorter than the input. Only block lengths of 8 or 16 bytes are supported. Note that it is a valid result for szOutput to be an empty string.

For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

When using the VBA wrapper function padUnpadHex and there is an error, then the input is returned unchanged. The user should check for this and signal an error. See the VBA wrapper example below.

◆ PBE_Kdf2()

long PBE_Kdf2 ( unsigned char *  lpOutput,
long  nOutputLen,
const unsigned char *  lpPwd,
long  nPwdLen,
const unsigned char *  lpSalt,
long  nSaltLen,
long  nCount,
long  nOptions 
)

Derives a key of any length from a password using the PBKDF2 algorithm from PKCS #5.

Parameters
[out]lpOutputarray to be filled with derived key.
[in]nOutputLenspecifying the size of the required key in bytes.
[in]lpPwdarray containing the password.
[in]nPwdLenspecifying the length of the password in bytes.
[in]lpSaltarray containing the salt.
[in]nSaltLenspecifying the length of the salt in bytes.
[in]nCountspecifying the required iteration count.
[in]nOptionsOption flags. Select one of:
HMAC with:
PKI_HASH_SHA1 (0) to use the SHA-1 hash algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
If successful, the return value is 0; otherwise it returns a non-zero error code.
Remarks
The output buffer for the derived key abDerivedKey() must have been dimensioned to at least the required length.

◆ PBE_Kdf2Hex()

long PBE_Kdf2Hex ( char *  szOutput,
long  nMaxChars,
long  dkBytes,
const char *  szPwd,
const char *  szSaltHex,
long  nCount,
long  nOptions 
)

Derives a key of any length from a password using the PBKDF2 algorithm from PKCS #5 with the salt and output derived key encoded in hexadecimal.

Parameters
[out]szOutputto receive the hexadecimal-encoded derived key.
[in]nMaxCharsspecifying the maximum number of characters in szOutput.
[in]dkBytesspecifying the size of the required key in bytes.
[in]szPwdcontaining the password.
[in]szSaltHexcontaining the salt in hex format.
[in]nCountspecifying the required iteration count.
[in]nOptionsOption flags. Select one of:
HMAC with:
PKI_HASH_SHA1 (0) to use the SHA-1 hash algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
If successful, the return value is 0; otherwise it returns a non-zero error code.
Remarks
The output string szOutput should be pre-dimensioned to be at least double the required key length in bytes. (Hint: specify nMaxChars as Len(strOutput)). ANSI C users must add one to this value when allocating memory. The seed szSaltHex is specified in hex format and can be any even number of hex digits in length. The password szPassword is normal text, not hexadecimal.

◆ PBE_Scrypt()

long PBE_Scrypt ( unsigned char *  lpDerivedKey,
long  nKeyLen,
const unsigned char *  lpPwd,
long  nPwdLen,
const unsigned char *  lpSalt,
long  nSaltLen,
long  nParamN,
long  nParamR,
long  nParamP,
long  nOptions 
)

Derives a key of any length from a password using the SCRYPT algorithm.

Parameters
[out]lpDerivedKeyByte array to be filled with derived key.
[in]nKeyLensize of required key in bytes.
[in]lpPwdByte array containing the password.
[in]nPwdLenlength of the password in bytes.
[in]lpSaltByte array containing the salt.
[in]nSaltLenlength of the salt in bytes.
[in]nParamNCPU/Memory cost parameter N ("costParameter") a number greater than one and a power of 2.
[in]nParamRBlock size r ("blockSize")
[in]nParamPParallelization parameter p ("parallelizationParameter")
[in]nOptionsOption flags: not used in this release. Specify zero.
Returns
If successful, the return value is 0; otherwise it returns a non-zero error code.
Remarks
This uses the SCRYPT algorithm from [RFC7914]. There are restrictions on the values of the parameters N, r and p. In particular, N must be larger than 1 and a power of 2.

The output buffer for the derived key abDerivedKey must have been dimensioned to at least the required length nKeyLen in bytes.

◆ PBE_ScryptHex()

long PBE_ScryptHex ( char *  szOutput,
long  nMaxChars,
long  dkBytes,
const char *  szPwd,
const char *  szSaltHex,
long  nParamN,
long  nParamR,
long  nParamP,
long  nOptions 
)

Derives a key of any length from a password using the SCRYPT algorithm with the salt and derived key encoded in hexadecimal.

Parameters
[out]szOutputto receive the hexadecimal-encoded derived key.
[in]nMaxCharsspecifying the maximum number of characters in szOutput.
[in]dkBytesspecifying the size of the required key in bytes.
[in]szPwdcontaining the password (as normal text).
[in]szSaltHexcontaining the salt in hex format.
[in]nParamNCPU/Memory cost parameter N ("costParameter") a number greater than one and a power of 2.
[in]nParamRBlock size r ("blockSize")
[in]nParamPParallelization parameter p ("parallelizationParameter")
[in]nOptionsOption flags: not used in this release. Specify zero.
Returns
If successful, the return value is 0; otherwise it returns a non-zero error code.
Remarks
The output string szOutput should be pre-dimensioned to be at least double the required key length in bytes. (Hint: specify nMaxChars as Len(strOutput)). The seed szSaltHex is specified in hex format and can be any even number of hex digits in length. The password szPassword is normal text, not hexadecimal.

◆ PEM_FileFromBinFile()

long PEM_FileFromBinFile ( const char *  szFileOut,
const char *  szFileIn,
const char *  szHeader,
long  nLineLen 
)

Creates a PEM file from a binary file .

Parameters
[in]szFileOutwith name of output file to be created.
[in]szFileInwith the filename of the binary file to be converted.
[in]szHeaderspecifying the header to be used. Leave empty to omit the PEM header and footer.
[in]nLineLenthe maximum length of a line in the resulting PEM file (default = 64 characters).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
This function takes the contents of any file (usually an ASN.1 DER- or BER-encoded binary file), treats it as binary data, encodes in base64 format, and encapsulates in a PEM-style header and footer. Leave the header blank to omit the PEM encapsulation and just output plain base64. The default for nLineLen is 64 characters. The recommended limit is 72 characters.

A PEM file is a text file containing encapsulated base64 data of the form

-----BEGIN FOO BAR-----
MIAGCSqGSIb3DQEHA...
-----END FOO BAR-----

The label in the header between "BEGIN " and the following five dash characters "-----" is set using the szHeader parameter. In the above example, strHeader="FOO BAR". You are free to use whatever word or words you like. In this Toolkit, we make no checks that the content of the file matches the header. However, other applications may.

Here is a list of commonly-used headers for PKI-related files.

PEM HeaderType of fileTypical file extensionsComment
CERTIFICATEX.509 certificate.cer,.der,.pem,.crtShould contain exactly one certificate
CERTIFICATE REQUESTPKCS#10 certificate signing request.csr,.p10 
X509 CRLX.509 certificate revocation list.crl 
PKCS12PFX file to PKCS#12.p12,.pfx 
ENCRYPTED PRIVATE KEYPKCS#8 key.p8e,.key,(.epk)Our default private key format
RSA PUBLIC KEYPKCS#1 public key.p1,.pubOur default public key format
PUBLIC KEYSubjectPublicKeyInfo OpenSSL format (PKI_KEY_FORMAT_SSL)
PRIVATE KEYUnencrypted PKCS#8 private key info.p8,.pri,.keyOur private key info format
RSA PRIVATE KEYUnencrypted PKCS#1 private key OpenSSL format (PKI_KEY_FORMAT_SSL)
PKCS7CMS object to PKCS#7.p7m,.p7s,.p7c,.p7b,.p7zUsed by OpenSSL
PKCS #7 SIGNED DATAditto Used by Thawte for Microsoft users
NETSCAPE CERTIFICATE CHAIN"certs-only" PKCS#7.p7c,.p7bUsed by Thawte for Netscape users

Update April 2015: see RFC 7468 "Textual Encodings of PKIX, PKCS, and CMS Structures" [RFC7468] for more definitive rules and recommendations on this subject.

◆ PEM_FileFromBinFileEx()

long PEM_FileFromBinFileEx ( const char *  szFileOut,
const char *  szFileIn,
const char *  szHeader,
long  nLineLen,
long  nOptions 
)

Creates a PEM file from a binary file with extended options.

Parameters
[in]szFileOutwith name of output file to be created.
[in]szFileInwith the filename of the binary file to be converted.
[in]szHeaderspecifying the header to be used. Leave empty to omit the PEM header and footer.
[in]nLineLenthe maximum length of a line in the resulting PEM file (default = 64 characters).
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_KEY_FORMAT_SSL to create the output file with Unix/SSL line endings (default = Windows CR-LF line endings)
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
See the remarks for PEM_FileFromBinFile(). This extension was added to create PEM format files compatible with those created by Open SSL, which uses Unix line endings (a single LF character as opposed to the CR-LF pair used in Windows files).

◆ PEM_FileToBinFile()

long PEM_FileToBinFile ( const char *  szFileOut,
const char *  szFileIn 
)

Converts the contents of a PEM file into a binary file.

Parameters
[in]szFileOutwith name of output file to be created.
[in]szFileInwith the filename of the PEM-encoded file to be converted.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
Any base64-encoded data found between a PEM header and footer is converted into binary data and saved as a file.
-----BEGIN FOO BAR-----
MIAGCSqGSIb3DQEHA...
-----END FOO BAR-----

◆ PFX_MakeFile()

long PFX_MakeFile ( const char *  szFileOut,
const char *  szCertList,
const char *  szEpkFile,
const char *  szPassword,
const char *  szFriendlyName,
long  nOptions 
)

Creates a simple PFX (PKCS-12) file from an X.509 certificate and (optional) encrypted private key file.

Parameters
[in]szFileOutname of output file to be created.
[in]szCertList(required) filename of the subject's X.509 certificate (or a string containing the certificate in base64 representation) followed by optional extra certificates to be included separated by a semicolon (;).
[in]szEpkFilefilename of the subject's pkcs-8 encrypted private key (or a string containing the key in PEM format). Pass an empty string "" to exclude the private key.
[in]szPasswordpassword for the encrypted private key.
[in]szFriendlyNamefriendly name identification for the subject (optional).
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options: re-encrypt private key with "TripleDES-SHA1", encrypt certificate with 40-bit RC2, output in DER binary form.
PKI_PFX_CLONE_KEY to store the private key in the exact form of the pkcs-8 input file (default is to re-encrypt with 3DES)
Add one of the following:
PKI_PFX_PLAIN_CERT to store the certificate in unencrypted form (default is encrypted)
PKI_PFX_STRONG_CERT to encrypt the certificate with "stronger" TripleDES-SHA1 (default is "weak" 40-bit RC2)
Or, new in [v20.5], to override the above encryption options, use instead
PKI_PFX_AES256_SHA256 to encrypt both the private key and certificate using "AES256-SHA256"
Then add any of these options:
PKI_KEY_FORMAT_PEM to create the output file in PEM format (default is DER-encoded binary)
PKI_PFX_ALT_FORMAT to create a PFX file with the exact peculiarities used by Microsoft (default is OpenSSL format)
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
At least one certificate must be specified in the szCertList argument. Add additional certificate names (or base64 representations) separated by a semicolon (;). The first certificate in the list must be the matching certificate for the private key, if included. The default behaviour is to save the certificate(s) encrypted using the "standard" weak 40-bit RC2 encryption (pbeWithSHAAnd40BitRC2-CBC) as used (until recently) by Windows Certificate Manager and OpenSSL, and the private key is re-encrypted using the "standard" TripleDES-SHA1 algorithm (pbeWithSHAAnd3-KeyTripleDES-CBC).

[New in v12.3] Use the PKI_PFX_STRONG_CERT option to encrypt the certificate with "stronger" Triple DES, the same as the default key encryption algorithm. The PKI_PFX_PLAIN_CERT option takes precedence.

[New in v20.5] Use the PKI_PFX_AES256_SHA256 option to encrypt both the private key and certificate using "AES256-SHA256".

The szFriendlyName parameter is optional. To exclude the private key just pass an empty szKeyFile parameter.

To help users of a certain brain-dead web service in Mexico which cannot cope with anything else, the default file format is the exact format that would be created by OpenSSL. If you really need Microsoft's peculiaritiesλ, then add the PKI_PFX_ALT_FORMAT option flag.

Any form of PKCS-12 file created by this function should be importable into Windows Certificate Manager/Outlook (use a .pfx extension for the output file) and Mozilla/Firefox (use a .p12 extension). The PKCS-12 standard is notorious for its peculiarities - see PFX - How Not to Design a Crypto Protocol/Standard [GUTPFX]. If you do not have success with your target application, try changing the options. In particular, using the PKI_PFX_CLONE_KEY option may cause problems if the target application cannot decrypt the super-secure algorithm you've used to protect your private key (error messages about a missing cryptographic provider are a clue here). That's why the default behaviour is to re-encrypt using the "standard" algorithm.

If you specify both a certificate and a private key, their RSA keys must match or a PKI_NO_MATCH_ERROR error will occur. The PKCS-12 file will be protected using the specified szPassword, which must match the password for the encrypted private key file, if included. The password is optional for the case where there is just a certificate, but is required if you need the certificate to be encrypted. If you don't use a password for a cert-only file, just enter an empty password when importing the PFX into Windows.

If you use the PKI_KEY_FORMAT_PEM option, the output file will be in PEM format with the first line "-----BEGIN PKCS12-----". Be warned, Windows does not recognise such a file as a valid PFX/PKCS-12 format!

λ The difference between the OpenSSL and Microsoft forms is that the Microsoft form has a "preferredAbsent" NULL parameter added to the message digest object for "sha1" and uses 8 instead of 20 bytes for the MacData salt. Both combinations are perfectly valid according to the PKCS12 specification.

◆ PFX_VerifySig()

long PFX_VerifySig ( const char *  szFileName,
const char *  szPassword,
long  nOptions 
)

Verifies the signature in a pkcs-12 file.

Parameters
[in]szFileNamespecifies the PKCS-12 filename to be checked.
[in]szPasswordcontaining the password.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
Just checks that the MacData signature is OK using the given password. Makes no other checks. The PFX file can be in either BER-encoded binary or PEM format. You can also pass the data directly as a PEM string in the szPfxFile parameter.

[New in v3.8] If there is no MacData signature in the PFX file and the supplied szPassword is empty, it will consider that to be a "valid" signature and return zero.

◆ PKI_CompileTime()

long PKI_CompileTime ( char *  szOutput,
long  nOutChars 
)

Retrieves the date and time the toolkit executable was last compiled.

Parameters
[out]szOutputto receive the date and time string.
[in]nOutCharsspecifying the maximum length of the string to be copied.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

◆ PKI_ErrorCode()

long PKI_ErrorCode ( void  )

Returns the error code of the first error that occurred when calling the last function.

Returns
Returns the error code for the first error that occurred when calling the last function, or zero if no error occurred. This may be different from the error code returned by the function itself if more than one error occurred during the call to the function.
Remarks
The value returned is always a non-negative integer.

For example, a call to CMS_MakeEnvData with one invalid X.509 certificate out of three would return 2 indicating two successful recipients. A call to PKI_ErrorCode() will indicate the error code for the invalid certificate. PKI_LastError() should have a more detailed error message.

◆ PKI_ErrorLookup()

long PKI_ErrorLookup ( char *  szOutput,
long  nOutChars,
long  nErrCode 
)

Retrieves the error message associated with a given error code.

Parameters
[out]szOutputto receive error message.
[in]nOutCharsspecifying the maximum length of the string to be copied.
[in]nErrCodespecifying the error code for which the message is required.
Returns
The number of characters that have been set in szOutput. If the function is called with nOutChars set to zero or szOutput as NULL, the return value is the number of characters in the error message.
Remarks
Specify a zero nOutChars or an empty string for szOutput to find the required length of the output string. ANSI C users must add one to this value when allocating memory.

The error message will never be longer than 127 characters (PKI_MAX_ERRORLOOKUP_CHARS).

◆ PKI_FormatErrorMessage()

long PKI_FormatErrorMessage ( char *  szOutput,
long  nOutChars,
long  nErrCode,
const char *  szUserMsg 
)

Return a formatted error message string for the last error.

Parameters
[out]szOutputBuffer to receive output string.
[in]nOutCharsMaximum length of output string in bytes.
[in]nErrCodeError code returned by last call (or zero if no code available).
[in]szUserMsgOptional user message to add.
Returns
The number of characters that have been set in szOutput.
Remarks
This is a combination of PKI_ErrorLookup, PKI_ErrorCode and PKI_LastError to give a complete formatted error message, for example
ERROR (11): Value out of range (OUT_OF_RANGE_ERROR)
ERROR: User message! (11): Value out of range (OUT_OF_RANGE_ERROR)
ERROR (21): No match found (NO_MATCH_ERROR): (1) Cannot open input file (OPEN_ERROR): Private key does not match any certificate in list

The equivalent functions in other languages are written independently and will give similar but not identical outputs.

The error message will never be longer than 1023 characters plus the length of any user message. In the raw ANSI C function you can query the expected length, but it is recommended to write directly to a fixed size buffer, as in the example below.

◆ PKI_LastError()

long PKI_LastError ( char *  szOutput,
long  nOutChars 
)

Retrieves the last error message set by the toolkit.

Parameters
[out]szOutputto receive last error message.
[in]nOutCharsspecifying the maximum length of the string to be copied.
Returns
If the preceding function call before calling PKI_LastError was successful, the return value is zero indicating no error; otherwise it is the number of characters that have been set in szOutput. For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.
Remarks
Not all functions set the error message string. The error message will never be longer than 511 characters.

◆ PKI_LicenceType()

long PKI_LicenceType ( long  nOptions)

Returns the ASCII value of the licence type.

Parameters
[in]nOptionsnot used in this release. Specify zero.
Returns
Returns the ASCII value of the licence type, either "D" (68, 0x44) for the Developer Version or "T" (84, 0x54) for the Trial Version.
Remarks
Note the Australian/English spelling of ‘Licence’.

◆ PKI_ModuleInfo()

long PKI_ModuleInfo ( char *  szOutput,
long  nOutChars,
long  nOptions 
)

Get additional information about the core DLL module.

Parameters
[out]szOutputBuffer to receive output string.
[in]nOutCharsMaximum length of output string in bytes.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.

◆ PKI_ModuleName()

long PKI_ModuleName ( char *  szOutput,
long  nOutChars,
long  nOptions 
)

Retrieves the name of the current process's module.

Parameters
[out]szOutputto receive the name of the module.
[in]nOutCharsspecifying the maximum length of the string to be copied.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

If using the Win32 DLL in the system folder on a 64-bit system, Windows will return "C:\WINDOWS\SYSTEM32\diCrPKI.dll" when the DLL file path is actually "C:\WINDOWS\SYSWOW64\diCrPKI.dll". Use PKI_Platform to find out exactly which DLL is being used.

◆ PKI_Platform()

long PKI_Platform ( char *  szOutput,
long  nOutChars 
)

Gets the platform the core DLL was compiled for.

Parameters
[out]szOutputto receive output, either "Win32" or "X64".
[in]nOutCharsspecifying the maximum length of the string to be copied.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

◆ PKI_PowerUpTests()

long PKI_PowerUpTests ( long  nOptions)

Carries out on demand the full set of power-up tests automatically performed by the toolkit when first powered up (i.e.

when the DLL is first attached to the process).

Parameters
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, returns zero; otherwise it returns a nonzero error code.
Remarks
This is an optional function. Unlike the tests carried out on actual power-up, this function does not cause the DLL to quit. If errors do occur, an error event will be recorded in the Application event log for NT+ operating systems or in an error log file on W9x systems. For more information on error logging after a self-test error, see Self Tests. Users are warned not to use the toolkit if an error has occurred after using this optional test. In such an event, please contact us.

◆ PKI_Version()

long PKI_Version ( void *  nReserved1,
void *  nReserved2 
)

Retrieves the release version number.

Parameters
[in]nReserved1ignored in version 2.8 and above - use 0.
[in]nReserved2ignored in version 2.8 and above - use 0.
Returns
Version number as an integer in form Major*100*100 + Minor*100 + Revision. For example, version 20.1.2 would return 200102. If this function fails, it means the toolkit is not installed or the library cannot be found.
Remarks
The arguments nReserved1 and nReserved2 are ignored.

◆ PRF_Bytes()

long PRF_Bytes ( unsigned char *  lpOutput,
long  nOutBytes,
const void *  lpMessage,
long  nMsgLen,
const void *  lpKey,
long  nKeyLen,
const char *  szCustom,
long  nOptions 
)

Generate output bytes using a pseudorandom function (PRF).

Parameters
[out]lpOutputbyte buffer to receive the output.
[in]nOutBytessize of output buffer in bytes.
[in]lpMessagebyte array containing the input data.
[in]nMsgLenlength of the input data in bytes.
[in]lpKeybyte array containing the key.
[in]nKeyLenlength of the key in bytes.
[in]szCustomcustomization string (optional).
[in]nOptionsOption flags. Select one of:
PKI_KMAC_128 to use KMAC128 (KMAC with SHAKE128)
PKI_KMAC_256 to use KMAC256 (KMAC with SHAKE256).
Returns
If successful, the return value is the number of bytes in the output; otherwise it returns a negative error code.
Remarks
The output buffer lpOutput must exist. It will be filled with exactly nOutBytes bytes. Note there is no zero option for nOptions: a valid option flag must be specified. For KMAC, the default customization string szCustom is the empty string "".

◆ PWD_Prompt()

long PWD_Prompt ( char *  szPassword,
long  nPwdLen,
const char *  szCaption 
)

Prompts for a password in a dialog box.

Parameters
[out]szPasswordto receive the password entered by the user.
[in]nPwdLenspecifying the maximum length of the string to be received.
[in]szCaptionspecifying a caption for the dialog box (optional).
Returns
If the user enters a password in the dialog box and clicks "OK", the return value is the length of the password entered in bytes. This could be zero. If the user clicks "Cancel", the return value is -1.
Remarks
Specify a zero nOutChars or an empty string for szOutput to find the required length of the output string. ANSI C users must add one to this value when allocating memory.

The password string is limited to 255 characters. It's up to the developer to protect the secrecy of the password once it's been entered: see WIPE_Data().

◆ PWD_PromptEx()

long PWD_PromptEx ( char *  szPassword,
long  nPwdLen,
const char *  szCaption,
const char *  szPrompt,
long  nOptions 
)

Prompts for a password in a dialog box with option to change prompt wording.

Parameters
[out]szPasswordto receive the password entered by the user.
[in]nPwdLenspecifying the maximum length of the string to be received.
[in]szCaptionspecifying a caption for the dialog box (optional).
[in]szPromptspecifying the prompt (default="Enter password:").
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If the user enters a password in the dialog box and clicks "OK", the return value is the length of the password entered in bytes. This could be zero. If the user clicks "Cancel", the return value is -1.
Remarks
See PWD_Prompt().

◆ RNG_Bytes()

long RNG_Bytes ( unsigned char *  lpOutput,
long  nOutBytes,
const void *  lpSeed,
long  nSeedLen 
)

Generates a random set of byte data suitable for cryptographic keys.

Parameters
[out]lpOutputarray to receive the random data.
[in]nOutBytesspecifying the required length in bytes.
[in]lpSeedcontaining "user-supplied entropy" to be used by the random number generator. Specify an empty string ("") or NULL to ignore.
[in]nSeedLenspecifying the length of the seed string.
Returns
If successful, the return value is zero. If the parameters are invalid, it returns a negative error code.
Remarks
The maximum number of random bytes that can be requested in one call is 65,536 (64 kB). If you need more (!), make repeated calls.

The length of the seed must be specified (set nSeedLen as zero to ignore).

If the RNG fails its FIPS-140 continuous test, the DLL process will be terminated. There is no option to avoid this, but the chances of such a failure under normal conditions are absolutely miniscule

  • about 1 in 9 quintillion (billion billion billion). See Random Number Generator for more information on the RNG, entropy, and its compliance with the relevant standards.

◆ RNG_BytesWithPrompt()

long RNG_BytesWithPrompt ( unsigned char *  lpOutput,
long  nOutBytes,
const char *  szPrompt,
long  nOptions 
)

Generates a random set of byte data suitable for cryptographic keys with a prompt for the user to enter random keystrokes and mouse movements.

Parameters
[out]lpOutputarray to receive the random data.
[in]nOutBytesspecifying the required length in bytes.
[in]szPromptspecifying an (optional) prompt for the dialog. Specify an empty string ("") or NULL to use the default dialog.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_RNG_STRENGTH_112 to make user generate an estimated 112 bits of security (default)
PKI_RNG_STRENGTH_128 to make user generate an estimated 128 bits of security
PKI_RNG_STRENGTH_192 to make user generate an estimated 192 bits of security
PKI_RNG_STRENGTH_256 to make user generate an estimated 256 bits of security
Returns
If successful, the return value is zero. If the parameters are invalid, it returns a negative error code.
Remarks
Once started, there is no way to abandon the dialog that prompts the user except by terminating the process. Some applications may not handle the GUI dialog. Make your own tests to check. The maximum number of random bytes that can be requested in one call is 65,536 (64 kB). See Random Number Generator for more information on the RNG and its compliance with the relevant standards.

◆ RNG_Guid()

long RNG_Guid ( char *  szOutput,
long  nOutChars,
long  nOptions 
)

Generate a random 36-character Global Unique IDentifier (GUID) string.

Parameters
[out]szOutputString buffer to receive output.
[in]nOutCharsMaximum number of characters to be received.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string (always 36); otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

A Global Unique IDentifier (GUID) is also called a version 4 Universally Unique IDentifier (UUID) and is defined in section 4.4 of [RFC4122]. The output is always a 36-character string of the form "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" where 'x' is a hexadecimal digit [0-9a-f]. The constant PKI_RNG_GUID_CHARS equal to 36 is defined for convenience. It is an error (SHORT_BUF_ERROR) if the output buffer is too short.

◆ RNG_Initialize()

long RNG_Initialize ( const char *  szSeedFile,
long  nOptions 
)

Initializes the RNG generator with a seed file.

Parameters
[in]szSeedFilespecifying a seed file. May be the empty string "".
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_RNG_NO_INTEL_DRNG to turn off support for Intel(R) DRNG for the current session.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code. If "" is passed for szSeedFile, it returns the support status for Intel DRNG (see Remarks).
Remarks
A seed file maintains the entropy state between sessions. If the seed file does not exist, it will be created, using any existing entropy. The file must be writable by the user. File locking is used to prevent interference from simultaneous use by others. The seed file is automatically updated by this procedure. Any existing file will be overwritten without warning.

Intel(R) DRNG support: [New in v22.1] Pass an empty string "" for szSeedFile to query support for Intel(R) Digital Random Number Generator (DRNG) on your system (and add an extra 256 bits of entropy, if available). If supported, the return value is a positive integer (1,2,3), otherwise it returns the error code PRNG_ERR_NOTAVAIL (-214). See Intel(R) DRNG.

Alternatively, use the option PKI_RNG_NO_INTEL_DRNG to turn off support for Intel(R) DRNG for the current session. You might use this if calls to Intel(R) DRNG are causing problems on your system.

◆ RNG_MakeSeedFile()

long RNG_MakeSeedFile ( const char *  szSeedFile,
const char *  szPrompt,
long  nOptions 
)

Creates a new seed file suitable for use with RNG_Initialize().

Parameters
[in]szSeedFilespecifying the seed file to be created.
[in]szPromptspecifying an (optional) prompt for the dialog. Specify an empty string ("") or NULL to use the default dialog.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_RNG_STRENGTH_112 to make user generate an estimated 112 bits of security (default)
PKI_RNG_STRENGTH_128 to make user generate an estimated 128 bits of security
PKI_RNG_STRENGTH_192 to make user generate an estimated 192 bits of security
PKI_RNG_STRENGTH_256 to make user generate an estimated 256 bits of security
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
This uses a dialog window and expects the user to type in random keystrokes. Such a GUI interface may not be appropriate in all circumstances. A new seed file is always created. Any existing file with the same name will be overwritten without warning. Alternatively, use the command-line program, PkiMkRngSeed.exe, provided in the distribution to make a new seed file [updated in v22.1].

◆ RNG_Number()

long RNG_Number ( long  nLower,
long  nUpper 
)

Returns an integer selected at random between specified limits.

Parameters
[in]nLowerspecifying a lower limit.
[in]nUpperspecifying an upper limit.
Returns
An integer selected at random from the set {nLower, ..., nUpper}.
Remarks
The number returned is an integer selected at random with uniform probability from the set {nLower, ..., nUpper}.

◆ RNG_Test()

long RNG_Test ( const char *  szFileOut,
long  nOptions 
)

Carries out a NIST SP800-90 health check and FIPS140-2 statistical tests on the random number generator.

Parameters
[in]szFileOut(optional) specifying the test output file to be created.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
This function carries out, on demand, the health testing procedure from section 11.3 of [SP80090A] and the statistical tests for randomness from section 4.9.1 of the October 2001 version of FIPS-140-2 [FIPS140]. The statistical test results and the 20,000-bit sample are written to a text file. Specify an empty ("") or NULL szFileName to avoid creating an output file and just carry out the tests. The statistical tests have since been removed from FIPS-140-2, but we do them anyway. If any tests fail, a nonzero error code will be returned.

◆ RNG_TestDRBGVS()

long RNG_TestDRBGVS ( char *  szOutput,
long  nMaxChars,
long  nReturnedBitsLen,
const char *  szEntropyInput,
const char *  szNonce,
const char *  szPersonalizationString,
const char *  szAdditionalInput1,
const char *  szEntropyReseed,
const char *  szAdditionalInputReseed,
const char *  szAdditionalInput2,
long  nOptions 
)

Test the RNG for conformance to NIST SP800-90A using the relevant test specified in DRBGVS.

Parameters
[out]szOutputto receive the ReturnedBits in hexadecimal format.
[in]nMaxCharsspecifying the maximum number of hexadecimal characters to be received.
[in]nReturnedBitsLenspecifying the number of bits to be returned from each call to the generate function in the test.
[in]szEntropyInputcontaining the EntropyInput value in hex format.
[in]szNoncecontaining the Nonce value in hex format.
[in]szPersonalizationStringcontaining the PersonalizationString value in hex format.
[in]szAdditionalInput1containing the first AdditionalInput value in hex format.
[in]szEntropyReseedcontaining the EntropyReseed value in hex format.
[in]szAdditionalInputReseedcontaining the AdditionalInputReseed value in hex format.
[in]szAdditionalInput2containing the second AdditionalInput value in hex format.
[in]nOptionsOption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in the output string; otherwise it returns a negative error code.
Remarks
The test procedure, the input values and the expected output are described in the [DRBGVS] document and associated test vectors. The relevant DRBG mechanism is HMAC_DRBG SHA-512 without prediction resistance. Use the empty string "" to pass a zero-length input. All hex strings must have an even number of characters.

◆ RNG_UpdateSeedFile()

long RNG_UpdateSeedFile ( const char *  szSeedFile,
long  nOptions 
)

Updates an RNG seed file.

Parameters
[in]szSeedFilespecifying the seed file to be updated.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
This writes a fresh set of random data to the seed file. The seed file must be writable by the user. Use this function at periodic intervals or when exiting your application. If the file does not exist it will be created. Any existing file of the same name will be overwritten without warning.

◆ RSA_CheckKey()

long RSA_CheckKey ( const char *  szKeyString,
long  nOptions 
)

Checks if an RSA key is valid.

Parameters
[in]szKeyStringcontaining the RSA public or private key in internal format
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is PKI_VALID_PRIVATEKEY (0) if the key is a valid private key, or PKI_VALID_PUBLICKEY (1) if the key is a public key; otherwise it returns a negative error code.
Remarks
If the key is a private key, the system carries out a pairwise check using a random message block to verify that the key is a valid RSA key pair (the format used to store private keys contains both the public and private components). Such a check cannot be carried out with a public key.

◆ RSA_DecodeMsg()

long RSA_DecodeMsg ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
long  nOptions 
)

Decodes an EME or EMSA encoded message block according to PKCS#1 (EME = Encoding Method for Encryption, EMSA = Encoding Method for Signature with Appendix).

Parameters
[out]lpOutputarray to receive the decoded output.
[in]nOutBytesspecifying the maximum length of the output array.
[in]lpInputarray containing the data to be decoded.
[in]nInputLenspecifying the number of bytes in the input.
[in]nOptionsoption flags. Include one of the following:-
PKI_EME_PKCSV1_5 (0) to decode an 'Encoded Message for Encryption' block using PKCS#1 v1.5 method (default)
PKI_EME_OAEP to decode an 'Encoded Message for Encryption' block using OAEP method
PKI_EMSIG_PKCSV1_5 to decode an ‘Encoded Message for Signature’ block using PKCS#1 v1.5 method

If you have selected PKI_EMSIG_PKCSV1_5, then you can add:
PKI_EMSIG_DIGINFO to decode an 'Encoded Message for Signature' block and output the whole DigestInfo data instead of just the message digest.

If you have selected PKI_EME_OAEP, then add one of these options to match the hash function used for EME-OAEP encoding:
PKI_HASH_SHA1 (0) to use SHA-1 (default).
PKI_HASH_SHA224 to use SHA-224
PKI_HASH_SHA256 to use SHA-256
PKI_HASH_SHA384 to use SHA-384
PKI_HASH_SHA512 to use SHA-512
and, optionally, add:-
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (default = same as encoding hash function set above)
The encoding hash function and MGF hash function must match the hash functions used to encode the message.

Alternatively, ignore all the above and use the specialist option
PKI_EMSIG_ISO9796 to use the ISO9796-1 encoding for a signature. See AUTACK messages and ISO/IEC 9796-1 signatures for more details.

Returns
If successful, the return value is the number of bytes required to store the full output data. If an error occurs, it returns a negative error code.
Remarks
This function recovers the relevant data from an encoded message block according to the algorithms in PKCS#1.

Messages encoded for both encryption and signature using the PKCS#1 v1.5 method are self-contained: that is, they can be decoded with no further information other than the encoded message itself. However, a message encoded using the OAEP method will be assumed by default to have been encoded using the default SHA-1 function for both the encoding hash algorithm and MGF hash algorithm. If you used a different hash function when encoding you need to specify it explicitly in nOptions.

The algorithm RSA-PSS is not available for this function. Use SIG_VerifyData instead.

Decoding an EME Block

The objective is to recover the original message data which is encoded in the block. Use either

nOptions = PKI_EME_PKCSV1_5

or

nOptions = PKI_EME_OAEP

You need to know which algorithm was used to create the block in the first place.

Decoding an EMSA Block

The objective is to verify that the encoded message digest hash matches the message digest hash of the original message.

Note: it is much simpler (and safer) to use the RSA_EncodeMsg() function on the original message and then compare the result of that with the input block you have here. See Raw RSA Techniques. The options here are included for advanced users.

There are two choices when decoding an EMSA block:

  1. Extract the message digest bytes. Set
    nOptions = PKI_EMSIG_PKCSV1_5
  2. Extract the whole DigestInfo bytes. Set

    nOptions = PKI_EMSIG_PKCSV1_5 + PKI_EMSIG_DIGINFO

    You might use this if you come across a hash algorithm that is not supported by this Toolkit. Use this option to recover the entire DigestInfo and then inspect the bytes to work out what it is, using your knowledge of DER encoding.

Remember that the result of a decode operation for a signature is to compare the hash digest encoded in the signature with an independent digest of the original message. If they match, the signature is verified. To avoid an attacker exploiting flaws in the decoding operation, it is safer just to generate another EMSA block from the message and compare that directly.

◆ RSA_Decrypt()

long RSA_Decrypt ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
const char *  szPrivateKeyFile,
const char *  szPassword,
const char *  szParameters,
long  nOptions 
)

Decrypt a message encrypted using an RSA encryption scheme.

Parameters
[out]lpOutputbyte array to receive the decrypted output.
[in]nOutBytesmaximum length of the output array.
[in]lpInputbyte array containing the data to be decrypted.
[in]nInputLenlength of input in bytes.
[in]szPrivateKeyFilespecifying the name of the private key file (or a string containing the key in PEM format, or a valid internal private key string).
[in]szPasswordPassword for encrypted private key, or "" if password is not required.
[in]szParametersFor future use. Specify "".
[in]nOptionsoption flags. Include one of the following:-
PKI_EME_PKCSV1_5 (0) to decrypt using the RSAES-PKCS1-v1_5 encryption scheme (default).
PKI_EME_OAEP to decrypt using the RSAES-OAEP encryption scheme.

If you have selected PKI_EME_OAEP, then add one of these options to set the hash function used for EME-OAEP encoding:
PKI_HASH_SHA1 (0) to use SHA-1 (default).
PKI_HASH_SHA224 to use SHA-224
PKI_HASH_SHA256 to use SHA-256
PKI_HASH_SHA384 to use SHA-384
PKI_HASH_SHA512 to use SHA-512
and, optionally, add:-
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (default = same as encoding hash function set above)

Returns
If successful, the return value is the number of bytes required to store the full output data. If an error occurs, it returns a negative error code.
Remarks
Set nOutBytes to zero and/or lpOutput to 0 (or NULL) to return the required number of bytes. The output will always be shorter than the input length.

For RSA-OAEP you must set the correct options to match the parameters used for the encryption. For more details see RSA encryption and signature schemes.

◆ RSA_EncodeMsg()

long RSA_EncodeMsg ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
long  nOptions 
)

Creates an EME or EMSA encoded message block according to PKCS#1 (EME = Encoding Method for Encryption, EMSA = Encoding Method for Signature with Appendix).

Parameters
[out]lpOutputarray to receive the encoded output.
[in]nOutBytesspecifying the maximum length of the output array.
[in]lpInputarray containing the message to be encoded (or the message digest).
[in]nInputLenspecifying the number of bytes in the message.
[in]nOptionsoption flags. Include one of the following:-
PKI_EME_PKCSV1_5 (0) to encode for encryption using PKCS#1 v1.5 method (RSAES-PKCS1-v1_5) (default)
PKI_EME_OAEP to encode for encryption using OAEP method
PKI_EMSIG_PKCSV1_5 to encode for signature using PKCS#1 v1.5 method (RSASSA-PKCS1-v1_5)

If you have selected PKI_EMSIG_PKCSV1_5, then add one of these options to set the hash function for the signature message digest:
PKI_HASH_SHA1 (0) to use SHA-1 (default).
PKI_HASH_SHA224 to use SHA-224
PKI_HASH_SHA256 to use SHA-256
PKI_HASH_SHA384 to use SHA-384
PKI_HASH_SHA512 to use SHA-512
PKI_HASH_MD5 to use MD5 [legacy, not recommended]
PKI_HASH_MD2 to use MD2 [legacy, definitely not recommended]
and, optionally, add:-
PKI_EMSIG_DIGESTONLY as a flag to pass the message digest only as input to-be-signed (default = pass entire message)

If you have selected PKI_EME_OAEP, then add one of these options to set the hash function for EME-OAEP encoding:
PKI_HASH_SHA1 (0) to use SHA-1 (default).
PKI_HASH_SHA224 to use SHA-224
PKI_HASH_SHA256 to use SHA-256
PKI_HASH_SHA384 to use SHA-384
PKI_HASH_SHA512 to use SHA-512
and, optionally, add:-
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (default = same as encoding hash function set above)

Alternatively, ignore all the above and use the specialist option
PKI_EMSIG_ISO9796 to use the ISO9796-1 encoding for a signature. See AUTACK messages and ISO/IEC 9796-1 signatures for more details.

Returns
If successful, the return value is zero; otherwise it returns a negative error code. CAUTION: This function assumes you know the required length of the output. It does not return the length.
Remarks
There are two distinct operations available here (a design decision that we regret, in hindsight). One operation creates an 'Encoded Message for Encryption' (EME) block which you would then encrypt with an RSA public key using the RSA_RawPublic() function. The other creates an 'Encoded Message for Signature with Appendix' (EMSA) block which you would then sign by encrypting with an RSA private key using the RSA_RawPrivate() function.

To Encode an EME Block

Set either

nOptions = PKI_EME_PKCSV1_5

or

nOptions = PKI_EME_OAEP

The default operation PKI_EME_PKCSV1_5 will create an encoded EME message block according to PKCS#1 v1.5. The PKI_EME_OAEP alternative uses a more secure algorithm (OAEP = Optimal Asymmetric Encryption Padding).

To Encode an EMSA Block

To encode the message "Hello world" ready for signing, use the PKI_EMSIG_PKCSV1_5 option and set

nOptions = PKI_EMSIG_PKCSV1_5
abInput = StrConv("Hello world", vbFromUnicode)
nInputLen = UBound(abMessage) - LBound(abMessage) + 1
nOptions = PKI_EMSIG_PKCSV1_5;
input = "Hello world";
nInputLen = strlen(input);

If you need to be compatible with a legacy application that uses, say, MD5, add the hash flag to the option

nOptions = PKI_EMSIG_PKCSV1_5 + PKI_HASH_MD5

If you have already computed the message digest in byte array form, then pass this as input and set

nOptions = PKI_EMSIG_PKCSV1_5 + PKI_EMSIG_DIGESTONLY

The algorithm RSA-PSS is not available for this function. Use SIG_SignData instead.

◆ RSA_Encrypt()

long RSA_Encrypt ( unsigned char *  lpOutput,
long  nOutBytes,
const unsigned char *  lpInput,
long  nInputLen,
const char *  szPublicKeyFile,
const char *  szParameters,
long  nOptions 
)

Encrypt a short message using RSA encryption.

Parameters
[out]lpOutputbyte array to receive the encrypted output.
[in]nOutBytesmaximum length of the output array.
[in]lpInputbyte array containing the data to be encrypted.
[in]nInputLenlength of input in bytes.
[in]szPublicKeyFilespecifying the name of the public key file or X.509 certificate (or a string containing the key or certificate in PEM format, or a valid internal public key string).
[in]szParametersFor specialist use. Specify "". See remarks.
[in]nOptionsoption flags. Include one of the following:-
PKI_EME_PKCSV1_5 (0) to encrypt using the RSAES-PKCS1-v1_5 encryption scheme (default).
PKI_EME_OAEP to encrypt using the RSAES-OAEP encryption scheme.

If you have selected PKI_EME_OAEP, then add one of these options to set the hash function for EME-OAEP encoding:
PKI_HASH_SHA1 (0) to use SHA-1 (default).
PKI_HASH_SHA224 to use SHA-224
PKI_HASH_SHA256 to use SHA-256
PKI_HASH_SHA384 to use SHA-384
PKI_HASH_SHA512 to use SHA-512
and, optionally, add:-
PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (default = same as encoding hash function set above)

Returns
If successful, the return value is the number of bytes required to store the full output data. If an error occurs, it returns a negative error code.
Remarks
Set nOutBytes to zero and/or lpOutput to 0 (or NULL) to return the required number of bytes. The output is always the same length in bytes as the RSA modulus, which can be found directly using the RSA_KeyBytes() function.

There is a limit on the length of data that can be encrypted. For RSAES-PKCS1-V1_5, nInputLen must not be greater than the key length in bytes (k) minus 11. For RSAES-OAEP, nInputLen must not be greater than k - 2*hLen - 2, where hLen is the length in bytes of the hash function output. Note this means, for example, that you cannot use SHA-512 with a 1024-bit RSA key with RSAES-OAEP.

The default parameters for RSA-OAEP encoding are

hashAlgorithm = sha1,
maskGenAlgorithm = mgf1SHA1 (MGF1 with SHA-1)
pSourceAlgorithm =pSpecifiedEmpty (label L is the empty string)

You can change the hash algorithm using nOptions (and by default the MGF1 hash algorithm will be the same), and you can force the MGF1 hash algorithm to be SHA-1. You cannot change the mask generation algorithm (there isn't another!) or the pSourceAlgorithm parameter (i.e. the label is always the empty string). For more details see RSA encryption and signature schemes.

To carry out tests against known test vectors, you can pass a fixed seed value in szParameters. For example, "seed=18b776ea21069d69776a33e96bad48e1dda0a5ef". This string must begin with "seed=" and be followed by the seed value in hexadecimal encoding. This must represent a byte array of exactly hLen bytes, the length of the output of the hash function.

◆ RSA_FromXMLString()

long RSA_FromXMLString ( char *  szOutput,
long  nOutChars,
const char *  szXmlString,
long  nOptions 
)

Creates an RSA key string in internal format from an XML string.

Parameters
[out]szOutputto receive key data either public or private.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szXmlStringcontaining the RSA public or private key in XML format
[in]nOptionsoption flags:
PKI_DEFAULT (0) to include the private key, if present (default)
PKI_XML_EXCLPRIVATE to exclude the private key even if present
PKI_XML_REQPRIVATE to require the private key to exist in the XML input or fail
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

A key string created with this function can be used in the other RSA functions in this toolkit that require a key in "internal" format. Use this function to import an RSA key from another application.

Only US-ASCII characters are supported. The XML data should be well formed and must contain either an RSAKeyValue or RSAKeyPair element according to [XMLDSIG] or [XKMS2]. The parser has been designed to be pretty forgiving but don't push it too far.

The first such valid element found in the string will be converted and other data will be ignored. If the XML data only contains the public key elements, the resulting internal string will contain a public key and can be used in the functions in this toolkit that require a public key string. If the XML data contains all the private key elements, the internal string will contain a private key unless the PKI_XML_EXCLPRIVATE option is used. To convert a private key, all components of the key pair must be present; namely, the <Modulus>, <Exponent>, <D>, <P>, <Q>, <DP>, <DQ>, and <InverseQ> elements as specified in [XKMS2]. To allow compatibility with older versions of XKMS out there, the deprecated elements <QINV>, <PublicExponent> and <PrivateExponent> will be accepted.

[New in v20.0] Element names with a prefix, e.g. <ds:Modulus>, are now accepted.

To make life easier to import RSA key data that exists in hexadecimal format, the user can force the function to decode the data in hexadecimal format instead of base64 by adding an attribute with the value "hexBinary" to each of the component elements of the RSAKeyValue. For example

<Exponent EncodingType="hexBinary">010001</Exponent>

The attribute name is not important. This practice is not in conformance with any existing W3C standard (that we're aware of, anyway) but is included for convenience where the user is creating the XML file by hand using hex data.

◆ RSA_GetPrivateKeyFromPFX()

long RSA_GetPrivateKeyFromPFX ( const char *  szFileOut,
const char *  szPfxFile,
long  nOptions 
)

Extracts an encrypted private key from a PKCS-12 PKCS8ShroudedKeyBag, saving the output directly as a new file.

Parameters
[in]szFileOutspecifying the filename of the output file to be created.
[in]szPfxFilecontaining the PFX filename
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, it returns the number of bytes written to the output file; otherwise it returns a negative error code.
Remarks
The first pkcs-12-pkcs-8ShroudedKeyBag found in the PFX file will be extracted and saved directly as a BER-encoded EncryptedPrivateKeyInfo file. No decryption or other conversion is carried out.

◆ RSA_GetPublicKeyFromCert()

long RSA_GetPublicKeyFromCert ( char *  szOutput,
long  nOutChars,
const char *  szCertFile,
long  nOptions 
)

Reads a public key from an X.509 certificate into an "internal" public key string.

Parameters
[out]szOutputto receive encoded public key data.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szCertFilespecifying the filename of an X.509 certificate file (or base64 representation).
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
Call the function with an empty or NULL szOutput string or zero nOutChars parameter to find out the required length of the output string. C/C++ users should add one to this value when allocating memory. Both binary BER-encoded and PEM-style base64-encoded certificates can be read, or the certificate can be passed directly as a string in base64 representation.

Woops! The name of this function is an exception to our usual convention that "Read" means read-into-internal-string and "Get" means extract-and-save-as-a-file. By rights this function should be called "RSA_ReadPublicKeyFromCert". Sorry.

◆ RSA_KeyBits()

long RSA_KeyBits ( const char *  szKeyString)

Returns the length of key in bits given the public or private key string.

Parameters
[in]szKeyStringcontaining the RSA private or public key string.
Returns
returns the number of significant bits in the key modulus or a negative error code.

◆ RSA_KeyBytes()

long RSA_KeyBytes ( const char *  szKeyString)

Returns the length of key in complete bytes (octets) given the public or private key string.

Parameters
[in]szKeyStringcontaining the RSA private or public key string.
Returns
returns the number of complete bytes (8-bit octets) in the key modulus or a negative error code.
Remarks
Use this function to find out the required length of the encryption block for "raw" RSA encryption.

◆ RSA_KeyHashCode()

long RSA_KeyHashCode ( const char *  szKeyString)

Computes the hash code of an "internal" RSA public or private key string.

Parameters
[in]szKeyStringcontaining the RSA private or public key string in internal format.
Returns
A 32-bit hash code for the key, or zero on error.
Remarks
Use this function to compare internal key strings. As of version 3.0, internal key strings are encrypted and cannot be compared directly. The actual string values may or may not be the same even though the underlying key is. The hash code value will be the same for a given key. The hash code is computed to an internal algorithm and may return any integer value between -2,147,483,648 and 2,147,483,647.

If the key string is invalid, the return value is zero and a nonzero error code will be set (use PKI_ErrorCode to check). There is a very small chance (one in 4 billion) that a valid key string returns a hash code of zero.

◆ RSA_KeyMatch()

long RSA_KeyMatch ( const char *  szPrivateKey,
const char *  szPublicKey 
)

Verifies that a pair of "internal" RSA private and public key strings are matched.

Parameters
[in]szPrivateKeycontaining an "internal" RSA private key string.
[in]szPublicKeycontaining an "internal" RSA public key string.
Returns
If the pair of private and public keys match, the return value is zero (0); if the key strings are valid but not matched, the return value is NO_MATCH_ERROR (-21). If an error occurs, it returns a nonzero error code.
Remarks
This function allows you to check that a private key file is matched with the public key in an X.509 certificate. You must read the keys into "internal" key strings before comparing. Note that the return value for success is zero.

◆ RSA_KeyValue()

long RSA_KeyValue ( char *  szOutput,
long  nOutChars,
const char *  szKeyString,
const char *  szFieldName,
long  nOptions 
)

Extracts a base64-encoded RSA key value from internal key string.

Parameters
[out]szOutputstring of sufficient length to receive the output
[in]nOutCharsspecifying the maximum number of characters to be received
[in]szKeyStringPublic or private key in internal string format
[in]szFieldNameName of field to be extracted: "Modulus" or "Exponent"
[in]nOptionsoption flags. Set to zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The output is a continuous string of base64 characters suitable for a <RSAKeyValue> node in an XML-DSIG document.

A typical <RSAKeyValue> node looks like this:

<RSAKeyValue>
  <Modulus>
    4IlzOY3Y9fXoh3Y5f06wBbtTg94Pt6vcfcd1KQ0FLm0S36aGJtTSb6pYKfyX7PqCUQ8wgL6xUJ5GRPEsu9gyz8
    ZobwfZsGCsvu40CWoT9fcFBZPfXro1Vtlh/xl/yYHm+Gzqh0Bw76xtLHSfLfpVOrmZdwKmSFKMTvNXOFd0V18=
  </Modulus>
  <Exponent>AQAB</Exponent>
</RSAKeyValue>

Use this function to populate the fields <Modulus> and <Exponent> for a given RSA key, or to use the values in other computations.

◆ RSA_MakeKeys()

long RSA_MakeKeys ( const char *  szPubKeyFile,
const char *  szEpkFile,
long  nBits,
long  nExpFermat,
long  nTests,
long  nCount,
const char *  szPassword,
const void *  lpSeed,
long  nSeedLen,
long  nOptions 
)

Generate an RSA key pair and save as two key files.

[Superseded by RSA_MakeKeysXtd.]

Parameters
[in]szPubKeyFilename of public key file to be created.
[in]szEpkFilename of encrypted private key file to be created.
[in]nBitsrequired key size in bits (minimum 96).
[in]nExpFermatexponent e to be used. Select from:
PKI_RSAEXP_EQ_3 for 3
PKI_RSAEXP_EQ_5 for 5
PKI_RSAEXP_EQ_17 for 17 (0x11)
PKI_RSAEXP_EQ_257 for 257 (0x101)
PKI_RSAEXP_EQ_65537 for 65537 (0x10001) (default)
[in]nTestsspecifying the number of Rabin-Miller tests to be performed (recommended at least 50).
[in]nCountspecifying the iteration count to be used when encrypting the private key (default = 1; recommended at least 1000).
[in]szPasswordpassword to be used to encrypt the private key file.
[in]lpSeedan (optional) user-specified seed to be used by the random number generator (specify "" or NULL to ignore).
[in]nSeedLenlength of the seed in bytes.
[in]nOptionsa flag to indicate the algorithm to be used to encrypt the private key file. Select from:
PKI_PBE_SHA_3DES (0) for "pbeWithSHAAnd3-KeyTripleDES-CBC" (default)
or PKI_PBE_PBES2 for "pkcs5PBES2" plus one of
  • PKI_BC_DESEDE3 to use des-EDE3-CBC (default)
  • PKI_BC_AES128 to use AES128-CBC
  • PKI_BC_AES192 to use AES192-CBC
  • PKI_BC_AES256 to use AES256-CBC
(there are more options - see security options for encrypted private keys)
and optionally add
PKI_KEYGEN_INDICATE to indicate progress in a console window (see remarks below),
plus one of
PKI_KEY_FORMAT_PEM to save the key files in PEM form (default is binary BER-encoded format)
or PKI_KEY_FORMAT_SSL to save the key files in PEM form with the public key as an OpenSSL-compatible subjectPublicKeyInfo file.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The RSA key is stored by default as a pair of DER-encoded binary files. The public and private keys are encoded into ASN.1 values of type RSAPublicKey and RSAPrivateKey respectively (defined in PKCS #1). The private key is then encrypted and encoded into a PKCS #8 EncryptedPrivateKeyInfo type. Any existing files of the same names will be overwritten without warning. The key length must be greater than 96 bits. The value of the exponent is limited to the five values listed. The password and iteration count are used to encrypt the private key according to the specified PBE algorithm specified in nOptionFlags. The password should be a string of ASCII characters and must not contain any NUL characters (i.e. Chr). The seed is optional and is used to supplement the seeding of the random number generator. The user may use the seed to provide some additional value ("user-supplied entropy") that is unique when the keys are being generated. See Random Number Generator and Seeds for more information.

The default format for the files is binary DER-encoded format. Use either the PKI_KEY_FORMAT_PEM or the PKI_KEY_FORMAT_SSL flag to save in base64 "PEM" format. Files saved with the PKI_KEY_FORMAT_SSL flag should be compatible with OpenSSL. For more details on the formats, see RSA_SavePublicKey() and RSA_SaveEncPrivateKey().

Generating RSA key pairs can take some time. On a 1GHz P3 test machine, the following times were typical:

Key sizeTime
512< 1 second
10245 seconds
20481 minute
40966 minutes
81921 hour

Some programs like Office Access will get bored waiting for the longer processes to finish and may hang. Setting the PKI_KEYGEN_INDICATE flag will show progress in a separate console window (actually two, one for p and one for q). Having a console window show progress will keep the parent application happy. A dot "." indicates a new candidate is being tested, and an asterisk "*" indicates that a Rabin-Miller test has been carried out (that is the expensive part of the process). The program will close these console windows down automatically. Do not use the PKI_KEYGEN_INDICATE option in a multi-threaded environment. For console-based programs, this option just shows the progress in the standard output.

Caution: pressing Ctrl-C or Ctrl-Break in the console window will kill your entire process altogether; that is, abort your whole application, which may not be what you want.

There is a very, very small possibility that the generator may fail to find a suitable prime number candidate within the number of iterations it carries out. If this happens (we've never seen it, but it could in theory), the function will return a KEYGEN_FAILED_ERROR error code 24. This in itself does not indicate a systemic problem with the Toolkit, just an incredibly unlucky event. Let us know if it happens more than once.

◆ RSA_MakeKeysXtd()

long RSA_MakeKeysXtd ( const char *  szPubKeyFile,
const char *  szPriKeyFile,
const char *  szPassword,
long  nBits,
long  nExpFermat,
const char *  szParams,
long  nOptions 
)

Generate an RSA key pair and save as two key files.

Parameters
[in]szPubKeyFileOutput filename for public key.
[in]szPriKeyFileOutput filename for (encrypted) private key.
[in]szPasswordPassword for encrypted private key (required).
[in]nBitsRequired key modulus size in bits (minimum 96).
[in]nExpFermatexponent e to be used. Select from:
PKI_RSAEXP_EQ_3 for 3
PKI_RSAEXP_EQ_5 for 5
PKI_RSAEXP_EQ_17 for 17 (0x11)
PKI_RSAEXP_EQ_257 for 257 (0x101)
PKI_RSAEXP_EQ_65537 for 65537 (0x10001) (default)
[in]szParamsOptional parameters. Set as the empty string "" for defaults. Otherwise include a set of attribute-value pairs separated by a semi-colon ";" to set options from the following
  • count=<nnn> to set the iteration count in the encrypted private key used in the PBKDF method, e.g. "count=5000;" [default=2048]
  • prf=<hmac-name> to change the HMAC algorithm used in the PBKDF2 method, e.g. "prf=hmacWithSHA256;" [default=hmacwithSHA1]
  • rngseed=<string> to add some extra user-specified additional seed for the random number generator, e.g. "rngseed=pqrrr1234xyz;"
Valid values for hmac-name are {hmacWithSHA1|hmacWithSHA224|hmacWithSHA256|hmacWithSHA384|hmacWithSHA512}.
[in]nOptionsa flag to indicate the password-based encryption scheme to be used to encrypt the private key file. Select from:
PKI_PBE_SHA_3DES (0) for "pbeWithSHAAnd3-KeyTripleDES-CBC" from PKCS12 (default)
PKI_PBE_PBKDF2_DESEDE3 for PBKDF2 using des-EDE3-CBC
PKI_PBE_PBKDF2_AES128 for PBKDF2 using aes128-CBC
PKI_PBE_PBKDF2_AES192 for PBKDF2 using aes192-CBC
PKI_PBE_PBKDF2_AES256 for PBKDF2 using aes256-CBC
(there are more options - see security options for encrypted private keys)
and optionally add
PKI_KEYGEN_INDICATE to indicate progress in a console window (see remarks below),
plus one of
PKI_KEY_FORMAT_PEM to save the key files in PEM form (default is binary DER-encoded format)
or PKI_KEY_FORMAT_SSL to save the key files in PEM form with the public key as an OpenSSL-compatible subjectPublicKeyInfo file.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The RSA keys are stored by default as a pair of DER-encoded binary files.

Setting the PKI_KEYGEN_INDICATE flag will show progress in a separate console window (actually two, one for p and one for q). Having a console window show progress will keep a parent application (like MS Access) happy and prevent it hanging due to boredom. The program will close these console windows down automatically (do not use Ctrl-C or Ctrl-Break: it will kill your entire process altogether!). Do not use the PKI_KEYGEN_INDICATE option in a multi-threaded environment. For console-based programs, this option just shows the progress in the standard output.

◆ RSA_PublicKeyFromPrivate()

long RSA_PublicKeyFromPrivate ( char *  szOutput,
long  nOutChars,
const char *  szKeyString,
long  nOptions 
)

Converts an internal RSA private key string into an internal public key string.

Parameters
[out]szOutputto receive public key data in encoded "internal" format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyStringcontaining a private key in "internal" format.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

Use this function if you need a public key string but only have the corresponding private key file. The format used to store RSA private keys contains both the public and private components (that is, n and e are present in both) so we can obtain the public key from its corresponding private key.

Note that internal key strings are only valid for the current session.

◆ RSA_RawPrivate()

long RSA_RawPrivate ( unsigned char *  lpData,
long  nDataLen,
const char *  szPrivateKey,
long  nOptions 
)

Transforms (that is, encrypts or decrypts) raw data using an RSA private key.

Parameters
[in,out]lpDataarray containing the data to be transformed.
[in]nDataLenspecifying the number of bytes of data.
[in]szPrivateKeycontaining the RSA private key string.
[in]nOptionsoption flags. Set to zero.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The data must be the same length as the RSA key modulus (use RSA_KeyBytes() to find out this). The output is written over the input. The RSA private key must be provided in the internal key string format.

◆ RSA_RawPublic()

long RSA_RawPublic ( unsigned char *  lpData,
long  nDataLen,
const char *  szPublicKey,
long  nOptions 
)

Transforms (that is, encrypts or decrypts) raw data using an RSA public key.

Parameters
[in,out]lpDataarray containing the data to be transformed.
[in]nDataLenspecifying the number of bytes of data.
[in]szPublicKeycontaining the RSA public key string.
[in]nOptionsoption flags. Set to zero.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The data must be the same length as the RSA key modulus (use RSA_KeyBytes() to find out this). The output is written over the input. The RSA public key must be provided in the internal key string format.

◆ RSA_ReadAnyPrivateKey()

long RSA_ReadAnyPrivateKey ( char *  szOutput,
long  nOutChars,
const char *  szKeyFileOrString,
const char *  szPassword,
long  nOptions 
)

Reads from a file or string containing a private key into an "internal" private key string.

Parameters
[out]szOutputto receive encoded private key data in "internal" format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyFileOrStringspecifying either the name of file containing the private key or a string containing the key in PEM format or XML format.
[in]szPasswordcontaining the password, if the key is encrypted, or "" if not encrypted.
[in]nOptionsnot used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This function will attempt to read the private key from "any" supported format. The output will be an ephemeral "internal" key string suitable for the current session only.

Supported formats are:

  • Encrypted or unencrypted PKCS#8 private key (.p8e, .p8) file in either binary DER format or text PEM format
  • PKCS#12 (.p12, .pfx) file containing a PKCSShroudedKeyBag. [v20.5] Added support for AES256-SHA256 encryption.
  • OpenSSL-compatible PKCS#1 RSA private key file in either binary DER format or text PEM format
  • String containing contents of any of the above files in text form as a PEM string
  • XML file or string containing an XKMS-conforming RSAKeyPair element
  • JSON file or string containing a plaintext RSA private key represented in JSON Web Key (JWK) format.

This supersedes the following functions:

  • RSA_ReadEncPrivateKey
  • RSA_ReadPrivateKeyInfo
  • RSA_ReadPrivateKeyFromPFX

◆ RSA_ReadAnyPublicKey()

long RSA_ReadAnyPublicKey ( char *  szOutput,
long  nOutChars,
const char *  szKeyFileOrString,
long  nOptions 
)

Reads from a file or string containing a public key into an "internal" public key string.

Parameters
[out]szOutputto receive encoded public key data in "internal" format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyFileOrStringspecifying the name of file containing the key or a string containing the key in PEM format or XML format.
[in]nOptionsnot used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This function will attempt to read the public key from "any" supported format. The output will be an ephemeral "internal" key string suitable for the current session only.

Supported formats are:

  • X.509 certificate (.cer, .crt) file in either binary DER format or text PEM format
  • String containing the contents of an X.509 certificate file in base64 encoding
  • PKCS#1 RSA Public Key (.p1) file in either binary DER format or text PEM format
  • File containing X.509 SubjectPublicKeyInfo data (OpenSSL public key) in either binary DER format or text PEM format
  • String containing contents of any of the above files in text form as a PEM string
  • XML file or string containing an XKMS-conforming RSAKeyValue or RSAKeyPair element
  • JSON file or string containing a plaintext RSA public key represented in JSON Web Key (JWK) format.

To read in a public key from a PFX/p12 file, use RSA_ReadAnyPrivateKey then RSA_PublicKeyFromPrivate.

This supersedes the following functions:

  • RSA_ReadPublicKey
  • RSA_GetPublicKeyFromCert

◆ RSA_ReadEncPrivateKey()

long RSA_ReadEncPrivateKey ( char *  szOutput,
long  nOutChars,
const char *  szEpkFile,
const char *  szPassword,
long  nOptions 
)

Reads from an encrypted PKCS#8 private key info file into an "internal" private key string.

[Superseded by RSA_ReadAnyPrivateKey.]

Parameters
[out]szOutputto receive encoded private key data in "internal" format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szEpkFilespecifying the filename of a PKCS-8 encrypted private key info file (or a string containing the key in PEM format).
[in]szPasswordcontaining the password
[in]nOptionsnot used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
Only PKCS-8 EncryptedPrivateKeyInfo data using the rsaEncryption algorithm is supported. The file must be either in binary BER-encoded format or PEM format.

◆ RSA_ReadPrivateKeyFromPFX()

long RSA_ReadPrivateKeyFromPFX ( char *  szOutput,
long  nOutChars,
const char *  szPfxFile,
const char *  szPassword,
long  nOptions 
)

Reads a private key directly from an encrypted PFX/PKCS-12 file into an "internal" private key string.

[Superseded by RSA_ReadAnyPrivateKey.]

Parameters
[out]szOutputto receive private key data in "internal" encoded format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szPfxFilecontaining the PFX filename (or a string containing the PFX data in PEM format)
[in]szPasswordcontaining the password.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
This will read the private key from the first pkcs8ShroudedKeyBag object it finds and can decrypt in the PFX file. The result is a string in "internal" key string format valid only for the current session. Call the function with an empty or NULL szOutput string or zero nOutChars parameter to find out the required length of the output string. C/C++ users should add one to this value when allocating memory.

If you need the public key instead from a PFX file, then use this function followed by RSA_PublicKeyFromPrivate().

If you just want to extract the encrypted private key and save directly as a pkcs-8 file, then use the RSA_GetPrivateKeyFromPFX() function.

◆ RSA_ReadPrivateKeyInfo()

long RSA_ReadPrivateKeyInfo ( char *  szOutput,
long  nOutChars,
const char *  szKeyFile,
long  nOptions 
)

Reads from an (unencrypted) PKCS-8 private key info file into an "internal" private key string.

[Superseded by RSA_ReadAnyPrivateKey.]

Parameters
[out]szOutputto receive private key data in "internal" encoded format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyFilespecifying the filename of a PrivateKeyInfo file (or a string containing the key in PEM format).
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
Only PKCS-8 PrivateKeyInfo files specifying the rsaEncryption algorithm are supported together with OpenSSL-compatible RSA PRIVATE KEY files. Files may be in either binary BER/DER-encoded format or PEM format. Call the function with an empty or NULL szOutput string or zero nOutChars parameter to find out the required length of the output string. C/C++ users should add one to this value when allocating memory.

◆ RSA_ReadPublicKey()

long RSA_ReadPublicKey ( char *  szOutput,
long  nOutChars,
const char *  szPubKeyFile,
long  nOptions 
)

Reads from an RSA public key file into an "internal" public key string.

[Superseded by RSA_ReadAnyPublicKey.]

Parameters
[out]szOutputto receive public key data in encoded "internal" format.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szPubKeyFilespecifying the filename of a public key file (or a string containing the key in PEM format).
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
Both PKCS-1 RSAPublicKey and OpenSSL SubjectPublicKeyInfo formats are supported. The file can be in binary BER-encoded format or PEM format, or be passed as a string containing the data in PEM format. Call the function with an empty or NULL szOutput string or zero nOutChars parameter to find out the required length of the output string. C/C++ users should add one to this value when allocating memory.

◆ RSA_SaveEncKey()

long RSA_SaveEncKey ( const char *  szFileOut,
const char *  szIntKeyString,
const char *  szPassword,
const char *  szParams,
long  nOptions 
)

Save an internal RSA key string to an encrypted key file.

Parameters
[in]szFileOutName of output file to be created.
[in]szIntKeyStringThe private RSA key as an internal key string.
[in]szPasswordPassword for encrypted private key (required).
[in]szParamsOptional parameters. Set as the empty string "" for defaults. Otherwise include a set of attribute-value pairs separated by a semi-colon ";" to set options from the following
  • count=<nnn> to set the iteration count in the encrypted private key used in the PBKDF method, e.g. "count=5000;" [default=2048]
  • prf=<hmac-name> to change the HMAC algorithm used in the PBKDF2 method, e.g. "prf=hmacWithSHA256;" [default=hmacwithSHA1]
Valid values for hmac-name are {hmacWithSHA1|hmacWithSHA224|hmacWithSHA256|hmacWithSHA384|hmacWithSHA512}.
[in]nOptionsoption flags: to specify the PBE algorithm. Select one of:
PKI_PBE_SHA_3DES (0) to use pbeWithSHAAnd3-KeyTripleDES-CBC from PKCS12 (default)
PKI_PBE_PBKDF2_DESEDE3 for PBKDF2 using des-EDE3-CBC
PKI_PBE_PBKDF2_AES128 for PBKDF2 using aes128-CBC
PKI_PBE_PBKDF2_AES192 for PBKDF2 using aes192-CBC
PKI_PBE_PBKDF2_AES256 for PBKDF2 using aes256-CBC
(there are more options - see security options for encrypted private keys)
and optionally add
PKI_KEY_FORMAT_PEM to export an ENCRYPTED PRIVATE KEY PEM-format file (default is binary BER-encoded format).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
[New in v20.3]

◆ RSA_SaveEncPrivateKey()

long RSA_SaveEncPrivateKey ( const char *  szFileOut,
const char *  szKeyString,
long  nCount,
const char *  szPassword,
long  nOptions 
)

Saves a private key string to a PKCS-8 encrypted private key info file.

Parameters
[in]szFileOutspecifying the filename of the output file to be created.
[in]szKeyStringcontaining the private key string
[in]nCountspecifying the number of iterations to carry out
[in]szPasswordcontaining the password
[in]nOptionsoption flags: to specify the PBE algorithm. Select one of:
PKI_PBE_SHA_3DES (0) to use pbeWithSHAAnd3-KeyTripleDES-CBC (default)
PKI_PBE_PBKDF2_DESEDE3 for PBKDF2 using des-EDE3-CBC
PKI_PBE_PBKDF2_AES128 for PBKDF2 using aes128-CBC
PKI_PBE_PBKDF2_AES192 for PBKDF2 using aes192-CBC
PKI_PBE_PBKDF2_AES256 for PBKDF2 using aes256-CBC
(there are more options - see security options for encrypted private keys)
and optionally add
PKI_KEY_FORMAT_PEM to export an ENCRYPTED PRIVATE KEY PEM-format file (default is binary BER-encoded format).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The default is to save as a binary BER-encoded PKCS-8 EncryptedPrivateKeyInfo file. If the PKI_KEY_FORMAT_PEM option is added, the file be will in PEM format. The PEM encrypted private key format uses the header and footer lines:
 -----BEGIN ENCRYPTED PRIVATE KEY-----
 -----END ENCRYPTED PRIVATE KEY-----

◆ RSA_SavePrivateKeyInfo()

long RSA_SavePrivateKeyInfo ( const char *  szFileOut,
const char *  szKeyString,
long  nOptions 
)

Saves a private key string to an (unencrypted) PKCS-8 private key info file.

Parameters
[in]szFileOutspecifying the filename of the output file to be created.
[in]szKeyStringcontaining the private key string
[in]nOptionsOption flags. Select one of:
PKI_DEFAULT (0) to export a binary BER-encoded file (default)
PKI_KEY_FORMAT_PEM to export a PEM-like PRIVATE KEY file
PKI_KEY_FORMAT_SSL to export an OpenSSL-compatible RSA PRIVATE KEY PEM file
and optionally add
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
Caution: this data is saved in unencrypted form. Do not use for a production key.

Any existing file of the specified name will be overwritten without warning. Saves by default as a binary BER-encoded file compatible with the PKCS-8 PrivateKeyInfo format. The PEM key format saved with the PKI_KEY_FORMAT_PEM option uses the header and footer lines:

 -----BEGIN PRIVATE KEY-----
 -----END PRIVATE KEY-----

The OpenSSL-compatible PEM key format saved with the PKI_KEY_FORMAT_SSL option uses the header and footer lines:

 -----BEGIN RSA PRIVATE KEY-----
 -----END RSA PRIVATE KEY-----

and is compatible with the PKCS-1 RSAPrivateKey format.

◆ RSA_SavePublicKey()

long RSA_SavePublicKey ( const char *  szFileOut,
const char *  szKeyString,
long  nOptions 
)

Saves a public key string to PKCS-1 public key file.

Parameters
[in]szFileOutspecifying the filename of the output file to be created.
[in]szKeyStringcontaining the public key string (or a private key string)
[in]nOptionsOption flags. Select one of:
PKI_DEFAULT (0) to export a binary DER/BER-encoded file (default)
PKI_KEY_FORMAT_PEM to export a PEM-like "RSA PUBLIC KEY" file
PKI_KEY_FORMAT_SSL to export an OpenSSL-compatible "PUBLIC KEY" PEM file
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
Any existing file of the specified name will be overwritten without warning. Saves by default as binary DER/BER-encoded PKCS-1 RSAPublicKey data. The file saved with the PKI_KEY_FORMAT_PEM option is the same data in PEM format with header and footer lines:
 -----BEGIN RSA PUBLIC KEY-----
 -----END RSA PUBLIC KEY-----

The file saved with the PKI_KEY_FORMAT_SSL option is compatible with the format used by OpenSSL. The data is saved as X.509 SubjectPublicKeyInfo format encoded with header and footer lines:

 -----BEGIN PUBLIC KEY-----
 -----END PUBLIC KEY-----

The OpenSSL format key is saved with "Unix" line endings and a line length of strictly 64 characters.

You can use this function to extract a public key from a private key. Just pass the internal private key string instead of the public key string.

◆ RSA_ToXMLString()

long RSA_ToXMLString ( char *  szOutput,
long  nOutChars,
const char *  szKeyString,
long  nOptions 
)

Creates an XML string representation of an RSA internal key string.

Parameters
[out]szOutputto receive XML data.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyStringcontaining the RSA public or private key in internal format
[in]nOptionsoption flags: Select and combine:
PKI_DEFAULT (0) to output in appropriate W3C standard format (RSAKeyValue for public key and RSAKeyPair for private key)
PKI_XML_RSAKEYVALUE to force private key output as .NET-compatible RSAKeyValue format (instead of W3C RSAKeyPair)
PKI_XML_EXCLPRIVATE to exclude the private key (use to get a public key RSAKeyValue from a private key)
PKI_XML_HEXBINARY to output with data in non-conforming hexBinary format
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

Caution: the private key is saved in unencrypted form. Do not use for a production key.

Both public and private key data can be output. The key must have been read first into an internal key string using one of the other RSA key input functions in this toolkit.

If the internal key is a public key, or if the PKI_XML_EXCLPRIVATE option is used with a private key, the output will always be a RSAKeyValue element containing just <Modulus> and <Exponent> elements as per [XMLDSIG].

If the internal key is a private key and the PKI_XML_EXCLPRIVATE option is not used, the default output will be a a XKMS-conforming RSAKeyPair element with the private key parameters included. Including the PKI_XML_RSAKEYVALUE option will force a .NET-compatible RSAKeyValue element instead. The only difference between RSAKeyPair and RSAKeyValue is in the name of the outer XML element. The default behaviour is to comply with the W3C standards [XKMS] and [XMLDSIG]. Users who wish to export a private key to use in the .NET world will probably want to use the PKI_XML_RSAKEYVALUE option.

The PKI_XML_HEXBINARY option will output the binary data in hexBinary encoding format instead of base64. This latter format is not in conformance with any W3C standard, but is provided to allow users to see the data in more readable hex format. Such a format can be read by
this toolkit's RSA_FromXMLString() function, but don't try using it anywhere else.

◆ RSA_ToXMLStringEx()

long RSA_ToXMLStringEx ( char *  szOutput,
long  nOutChars,
const char *  szKeyString,
const char *  szPrefix,
long  nOptions 
)

Creates an XML string representation of an RSA internal key string with option to add a namespace prefix.

Parameters
[out]szOutputto receive XML data.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szKeyStringcontaining the RSA public or private key in internal format
[in]szPrefixthe namespace prefix to be added to all elements
[in]nOptionsoption flags: Select and combine:
PKI_DEFAULT (0) to output in appropriate W3C standard format (RSAKeyValue for public key and RSAKeyPair for private key)
PKI_XML_RSAKEYVALUE to force private key output as .NET-compatible RSAKeyValue format (instead of W3C RSAKeyPair)
PKI_XML_EXCLPRIVATE to exclude the private key (use to get a public key RSAKeyValue from a private key)
PKI_XML_HEXBINARY to output with data in non-conforming hexBinary format
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

Use this extended function to add a namespace prefix to all elements in the XML output; for example, <ds:RSAKeyValue>. Note that it's up to the user to map the prefix to a URI somewhere in the final XML document (for reference, the correct form is xmlns:ds="http://www.w3.org/2000/09/xmldsig#").

See also the remarks for RSA_ToXMLString.

◆ SIG_SignData()

long SIG_SignData ( char *  szOutput,
long  nOutChars,
const unsigned char *  lpData,
long  nDataLen,
const char *  szKeyFile,
const char *  szPassword,
const char *  szAlgName,
long  nOptions 
)

Compute a signature value over data in a byte array.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]lpDatabyte array containing the input data to be signed.
[in]nDataLenspecifying the length of the input data in bytes.
[in]szKeyFilespecifying the name of the private key file (or a string containing the key in PEM format, or a valid internal private key string).
[in]szPasswordcontaining the password for the private key, or "" if not required.
[in]szAlgNamespecifying the signature algorithm (case insensitive):
"sha1WithRSAEncryption" (default - CAUTION)
"sha224WithRSAEncryption"
"sha256WithRSAEncryption" [minimum recommended]
"sha384WithRSAEncryption"
"sha512WithRSAEncryption"
"md5WithRSAEncryption" [for legacy applications - not recommended for new implementations]
"ecdsaWithSHA1"
"ecdsaWithSHA224"
"ecdsaWithSHA256"
"ecdsaWithSHA384"
"ecdsaWithSHA512"
"RSA-PSS-SHA1"
"RSA-PSS-SHA224"
"RSA-PSS-SHA256"
"RSA-PSS-SHA384"
"RSA-PSS-SHA512"
"Ed25519" [New in v20.0] (see Remarks)
"Ed448" [New in v22.0] (see Remarks)
or "" to use the signature algorithm flag in nOptions, see Specifying the signature algorithm in a SIG_ function.
[in]nOptionsZero (0) for defaults.
Add the bitflag:
  • PKI_SIG_USEDIGEST to pass the digest value of the data-to-be-signed as a byte array in the lpData parameter instead of the data itself (except with Ed25519).
To change the format of the output (default base64 encoded), add one of:
  • PKI_ENCODE_BASE64URL to encode the output in the URL-safe "base64url" encoding of [RFC4648]; or
  • PKI_ENCODE_HEX to encode the output in hexadecimal (base16) encoding
Options for ECDSA signatures only:
  • PKI_SIG_DETERMINISTIC to use the deterministic digital signature generation procedure of [RFC6979] for ECDSA signatures (default=random k)
  • PKI_SIG_ASN1DER to form the signature value as a DER-encoded ASN.1 structure (as used by Bitcoin); (default=simple concatenation r||s)
Options for RSA-PSS signatures only: [New in v12.0] (see RSA signature and encryption schemes)
Add one of the following to specify the salt length:
  • PKI_PSS_SALTLEN_HLEN (0) to set the salt length to hLen, the length of the output of the hash function (default).
  • PKI_PSS_SALTLEN_MAX to set the salt length to the maximum possible (OpenSSL does this by default)
  • PKI_PSS_SALTLEN_20 to set the salt length to be exactly 20 bytes regardless of the hash algorithm
  • PKI_PSS_SALTLEN_ZERO to set the salt length to be zero
and, optionally, add:-
  • PKI_MGF_MGF1SHA1 to force the MGF hash function to be SHA-1 (default = same as signature hash algorithm)

Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

Computes the signature value over the input data (or its digest value) using the private key provided. The default output is a continuous string of base64 characters suitable to include in the <SignatureValue> node of an XML-DSIG document. Alternative output encodings (base64url and hex) can be specified using the PKI_ENCODE_ options.

The PKI_SIG_USEDIGEST option cannot be used with Ed25519 or Ed448. The data to be signed must be passed in toto to the signature function. All options except the PKI_ENCODE_ options are ignored for the Ed25519 and Ed448 algorithms.

◆ SIG_SignFile()

long SIG_SignFile ( char *  szOutput,
long  nOutChars,
const char *  szDataFile,
const char *  szKeyFile,
const char *  szPassword,
const char *  szAlgName,
long  nOptions 
)

Compute a signature value over data in a file.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szDataFilespecifying the file containing the input data to be signed.
[in]szKeyFilespecifying the name of the private key file (or a string containing the key in PEM format, or a valid internal private key string).
[in]szPasswordcontaining the password for the private key, or "" if not required.
[in]szAlgNamespecifying the signature algorithm (case insensitive):
"sha1WithRSAEncryption" (default - CAUTION)
"sha224WithRSAEncryption"
"sha256WithRSAEncryption" [minimum recommended]
"sha384WithRSAEncryption"
"sha512WithRSAEncryption"
"md5WithRSAEncryption" [for legacy applications - not recommended for new implementations]
"ecdsaWithSHA1"
"ecdsaWithSHA224"
"ecdsaWithSHA256"
"ecdsaWithSHA384"
"ecdsaWithSHA512"
"RSA-PSS-SHA1"
"RSA-PSS-SHA224"
"RSA-PSS-SHA256"
"RSA-PSS-SHA384"
"RSA-PSS-SHA512"
(Note that Ed25519 and Ed448 are not available with this function - see Remarks)
or "" to use the signature algorithm flag in nOptions, see Specifying the signature algorithm in a SIG_ function.
[in]nOptionsZero (0) for defaults.
To change the format of the output (default base64 encoded), add one of:
  • PKI_ENCODE_BASE64URL to encode the output in the URL-safe "base64url" encoding of [RFC4648]; or
  • PKI_ENCODE_HEX to encode the output in hexadecimal (base16) encoding
Options for ECDSA signatures only:
  • PKI_SIG_DETERMINISTIC to use the deterministic digital signature generation procedure of [RFC6979] for ECDSA signatures (default=random k)
  • PKI_SIG_ASN1DER to form the signature value as a DER-encoded ASN.1 structure (as used by Bitcoin); (default=simple concatenation r||s)
Options for RSA-PSS signatures only: [New in v12.0] (see RSA signature and encryption schemes)
Add one of the following to specify the salt length:
  • PKI_PSS_SALTLEN_HLEN (0) to set the salt length to hLen, the length of the output of the hash function (default).
  • PKI_PSS_SALTLEN_MAX to set the salt length to the maximum possible (OpenSSL does this by default)
  • PKI_PSS_SALTLEN_20 to set the salt length to be exactly 20 bytes regardless of the hash algorithm
  • PKI_PSS_SALTLEN_ZERO to set the salt length to be zero

Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This function is identical to SIG_SignData except the data to be signed is in a file.

The Ed25519 and Ed448 signature algorithms are not available with this function. To sign using Ed25519 or Ed448, read in the file to a byte array and use SIG_SignData.

◆ SIG_VerifyData()

long SIG_VerifyData ( const char *  szSignature,
const unsigned char *  lpData,
long  nDataLen,
const char *  szCertOrKeyFile,
const char *  szAlgName,
long  nOptions 
)

Verify a signature value over data in a byte array.

Parameters
[in]szSignaturestring containing the signature value encoded in base64.
[in]lpDatabyte array containing the input data to be verified.
[in]nDataLenspecifying the length of the input data in bytes.
[in]szCertOrKeyFilespecifying the X.509 certificate or public key file (or a string containing the certificate or key in PEM format or base64 representation).
[in]szAlgNamespecifying the signature algorithm (case insensitive):
"sha1WithRSAEncryption" (default)
"sha224WithRSAEncryption"
"sha256WithRSAEncryption"
"sha384WithRSAEncryption"
"sha512WithRSAEncryption"
"md5WithRSAEncryption"
"ecdsaWithSHA1"
"ecdsaWithSHA224"
"ecdsaWithSHA256"
"ecdsaWithSHA384"
"ecdsaWithSHA512"
"RSA-PSS-SHA1"
"RSA-PSS-SHA224"
"RSA-PSS-SHA256"
"RSA-PSS-SHA384"
"RSA-PSS-SHA512"
"Ed25519" [New in v20.0] (see Remarks)
"Ed448" [New in v22.0] (see Remarks)
or "" to use the signature algorithm flag in nOptions, see Specifying the signature algorithm in a SIG_ function.
[in]nOptionsZero (0) for defaults.
PKI_SIG_USEDIGEST to pass the digest value of the data-to-be-verified as a byte array in the lpData parameter instead of the data itself.
PKI_MGF_MGF1SHA1 (RSA-PSS only) to force the MGF hash function to be SHA-1 (default = same as signature hash algorithm).
Returns
Zero (0) if the signature is valid; otherwise it returns a negative error code.
Remarks
A signature value is considered valid if it can be decrypted by the public key in szCertOrKeyFile and the digest of the data matches the original digest of the data in the signature. The signature algorithm and hash algorithm used to create the signature value must be provided.

For RSA-PSS, the MGF hash algorithm is assumed to be the same as the signature hash algorithm (see RSA signature and encryption schemes). If the signature was created using mgf1SHA1 with a signature hash algorithm other than SHA-1, then you must add the option PKI_MGF_MGF1SHA1. Other combinations of signature hash algorithm/MGF hash algorithm are not supported.

The PKI_SIG_USEDIGEST option cannot be used with Ed25519 or Ed448. The data to be verified must be passed in toto to the verify function.

◆ SIG_VerifyFile()

long SIG_VerifyFile ( const char *  szSignature,
const char *  szDataFile,
const char *  szCertOrKeyFile,
const char *  szAlgName,
long  nOptions 
)

Verify a signature value over data in a file.

Parameters
[in]szSignaturestring containing the signature value encoded in base64.
[in]szDataFilespecifying the file containing the input data to be verified.
[in]szCertOrKeyFilespecifying the X.509 certificate or public key file (or a string containing the certificate or key in PEM format or base64 representation).
[in]szAlgNamespecifying the signature algorithm (case insensitive):
"sha1WithRSAEncryption" (default)
"sha224WithRSAEncryption"
"sha256WithRSAEncryption"
"sha384WithRSAEncryption"
"sha512WithRSAEncryption"
"md5WithRSAEncryption" [for legacy applications - not recommended for new implementations]
"ecdsaWithSHA1"
"ecdsaWithSHA224"
"ecdsaWithSHA256"
"ecdsaWithSHA384"
"ecdsaWithSHA512"
"RSA-PSS-SHA1"
"RSA-PSS-SHA224"
"RSA-PSS-SHA256"
"RSA-PSS-SHA384"
"RSA-PSS-SHA512"
(Note that Ed25519 and Ed448 are not available with this function - see Remarks)
or "" to use the signature algorithm flag in nOptions, see Specifying the signature algorithm in a SIG_ function.
[in]nOptionsZero (0) for defaults.
PKI_MGF_MGF1SHA1 (RSA-PSS only) to force the MGF hash function to be SHA-1 (default = same as signature hash algorithm).
Returns
Zero (0) if the signature is valid; otherwise it returns a negative error code.
Remarks
This function is identical to SIG_VerifyData except the data to be verified is in a file.

The Ed25519 and Ed448 signature algorithms are not available with this function. To verify using Ed25519 or Ed448, read in the file to a byte array and use SIG_VerifyData.

◆ SMIME_Extract()

long SMIME_Extract ( const char *  szFileOut,
const char *  szFileIn,
long  nOptions 
)

Extract the body from an S/MIME entity.

Parameters
[in]szFileOutstring specifying the filename of the output file to be created.
[in]szFileInstring specifying the filename of the input file.
[in]nOptionsZero (0) for defaults.
PKI_SMIME_ENCODE_BASE64 to encode the output in base64 encoding (default is binary).
Returns
A positive number giving the size of the output file in bytes; or a negative error code.
Remarks
This is designed to extract the body from an S/MIME entity with a content type of application/pkcs7-mime with base64 or binary transfer encoding. In practice, it will extract the body from almost any type of S/MIME (or MIME) file, except one with quoted-printable transfer encoding.

◆ SMIME_Query()

long SMIME_Query ( char *  szOutput,
long  nOutChars,
const char *  szFileIn,
const char *  szQuery,
long  nOptions 
)

Query an S/MIME entity.

Parameters
[out]szOutputstring of sufficient length to receive the output.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szFileInstring specifying the filename of the input file.
[in]szQueryspecifying the query (see Remarks below).
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is a positive number indicating the number of characters (bytes) in the output string, or number of characters required if nOutChars was set to zero. If the item queried cannot be found, the return value is zero. If there is an error (e.g. invalid input), it returns a negative error code.
Remarks
Valid queries are (case-insensitive):
Query StringReturns
content-typeValue of Content-Type, e.g. "application/pkcs7-mime"
smime-typeValue of smime-type parameter of Content-Type, e.g. "enveloped-data"
encodingValue of Content-Transfer-Encoding, e.g. "base64"
nameValue of name parameter of Content-Type, e.g. "smime.p7m"
filename

Value of filename parameter of Content-Disposition, e.g. "smime.p7m"

If no value is found corresponding to the query then the zero-length empty string "" is output.

For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

◆ SMIME_Wrap()

long SMIME_Wrap ( const char *  szFileOut,
const char *  szFileIn,
const char *  szFeatures,
long  nOptions 
)

Wrap a CMS object in an S/MIME entity.

Parameters
[in]szFileOutstring specifying the filename of the output file to be created.
[in]szFileInstring specifying the filename of the input file.
[in]szFeaturesstring to specify special features. For future use. Leave empty "" or NULL for defaults.
[in]nOptionsZero (0) for defaults.
PKI_SMIME_ENCODE_BINARY to encode the body in binary encoding (default is base64).
PKI_SMIME_ADDX to add an "x-" to the content subtype.
Returns
A positive number giving the size of the output file in bytes; or a negative error code.
Remarks
This forms an S/MIME entity with a Content-Type of application/pkcs7-mime from a binary CMS object. It works in file-to-file mode only. The input file is expected to be a binary CMS object of type enveloped-data, signed-data or compressed-data; otherwise it is an error. The type of input file is detected automatically. The output is a text file with the correct S/MIME headers according to [SMIME-MSG]. By default the body is encoded in base64. Use the PKI_SMIME_ENCODE_BINARY option to encode the body in "binary" instead.

Use the PKI_SMIME_ADDX option to change the Content-Type to application/x-pkcs7-mime for compatibility with legacy applications.

S/MIME signed messages with the multipart/signed format are currently not supported.

◆ TDEA_B64Mode()

long TDEA_B64Mode ( char *  szOutput,
const char *  szInput,
const char *  szKey,
long  fEncrypt,
const char *  szMode,
const char *  szIV 
)

Encrypts or decrypts data encoded in base64 using a specified mode.

The key and initialization vector are required in base64.

Parameters
[out]szOutputof sufficient length to receive the output.
[in]szInputcontaining the input data in base64.
[in]szKeycontaining the key in base64 format.
[in]fEncryptdirection flag: set as ENCRYPT (True) to encrypt or DECRYPT (False) to decrypt.
[in]szModespecifying the confidentiality mode:
"ECB" for Electronic Codebook mode,
"CBC" for Cipher Block Chaining mode,
"CFB" for 64-bit Cipher Feedback mode,
"OFB" for Output Feedback mode, or
"CTR" for Counter mode.
[in]szIVcontaining the initialization vector (IV), if required, in base64 format.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
For ECB and CBC modes, the input string szInput must represent an exact multiple of eight bytes when decoded otherwise a "Data not a valid length" error will result. The key string szKey must represent exactly 24 bytes when decoded. The initialization vector string szIV must represent exactly 8 bytes when decoded unless szMode is ECB, in which case szIV is ignored (use ""). Valid base64 characters are [A-Za-z0-9+/] with '=' used as a padding character. The output string szOutput must be set up with at least the same number of characters as the input string before calling. The variables szOutput and szInput should be different.

◆ TDEA_BytesMode()

long TDEA_BytesMode ( unsigned char *  lpOutput,
const unsigned char *  lpData,
long  nDataLen,
const unsigned char *  lpKey,
long  fEncrypt,
const char *  szMode,
const unsigned char *  lpIV 
)

Encrypts or decrypts an array of Bytes in one step using a specified mode.

Parameters
[out]lpOutputarray of sufficient length to receive the output.
[in]lpDataarray containing the input data.
[in]nDataLenequal to length of the input data in bytes.
[in]lpKeyarray containing the key.
[in]fEncryptdirection flag: set as ENCRYPT (True) to encrypt or DECRYPT (False) to decrypt.
[in]szModespecifying the confidentiality mode:
"ECB" for Electronic Codebook mode,
"CBC" for Cipher Block Chaining mode,
"CFB" for 64-bit Cipher Feedback mode,
"OFB" for Output Feedback mode, or
"CTR" for Counter mode.
[in]lpIVarray containing the initialization vector (IV), or zero (0) for ECB mode.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
For ECB and CBC modes, the input data lpInput must be a multiple of 8 bytes long otherwise a "Data not a valid length" error will result. The key lpKey must be exactly 24 bytes long and the IV, if required, exactly 8 bytes long. The output array lpOutput must be at least nDataLen bytes long. lpOutput and lpInput may be the same.

◆ TDEA_File()

long TDEA_File ( const char *  szFileOut,
const char *  szFileIn,
const unsigned char *  lpKey,
long  fEncrypt,
const char *  szMode,
const unsigned char *  lpIV 
)

Encrypts or decrypts a file using a specified mode.

The key and initialization vector are passed as arrays of bytes. PKCS-5/7 padding is used.

Parameters
[in]szFileOutwith the full path name of the output file to be created.
[in]szFileInwith the full path name of the input file to be processed.
[in]lpKeyarray containing the key.
[in]fEncryptdirection flag: set as ENCRYPT (True) to encrypt or DECRYPT (False) to decrypt.
[in]szModespecifying the confidentiality mode:
"ECB" for Electronic Codebook mode,
"CBC" for Cipher Block Chaining mode,
"CFB" for 64-bit Cipher Feedback mode,
"OFB" for Output Feedback mode, or
"CTR" for Counter mode.
[in]lpIVarray containing the initialization vector (IV), or zero (0) for ECB mode.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The key array abKey() must be exactly 16 bytes long. The initialization vector abInitV() must be exactly the block size of 16 bytes long, except for ECB mode, where it is ignored (use 0).

The output file szFileOut will be overwritten without warning. If there is an error, the output file will not exist. The input and output files must not be the same.

In ECB and CBC modes, a padding string will be added or assumed according to the method outlined in Section 6.3 of [CMS], which is the same as the padding method in [PKCS7] section 10.3 and [PKCS5] section 6.1.1 and [RFC1423] para 1.1.

◆ TDEA_HexMode()

long TDEA_HexMode ( char *  szOutput,
const char *  szInput,
const char *  szKey,
long  fEncrypt,
const char *  szMode,
const char *  szIV 
)

Encrypts or decrypts data represented as a hexadecimal string using a specified mode.

The key and initialization vector are represented as a hexadecimal string.

Parameters
[out]szOutputof sufficient length to receive the output.
[in]szInputcontaining the input data in hex format.
[in]szKeycontaining the key in hex format.
[in]fEncryptdirection flag: set as ENCRYPT (True) to encrypt or DECRYPT (False) to decrypt.
[in]szModespecifying the confidentiality mode:
"ECB" for Electronic Codebook mode,
"CBC" for Cipher Block Chaining mode,
"CFB" for 64-bit Cipher Feedback mode,
"OFB" for Output Feedback mode, or
"CTR" for Counter mode.
[in]szIVcontaining the initialization vector (IV), if required, in hex format.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
For ECB and CBC modes, the length of the input string szInput must be a multiple of 16 hex characters long (i.e. representing a multiple of 8 bytes) otherwise an error will result. The key string szKey must be exactly 48 hex characters long (i.e. representing exactly 24 bytes/192 bits). The initialization vector string szIV must be exactly 16 hex characters long (i.e. representing exactly the block size of 8 bytes) unless szMode is ECB, in which case szIV is ignored (use ""). Valid hexadecimal characters are [0-9A-Fa-f]. The output string szOutput must be set up with the same number of characters as the input string before calling. The variables szOutput and szInput should be different.

◆ WIPE_Data()

long WIPE_Data ( void *  lpData,
long  nDataLen 
)

Zeroise data in memory.

Parameters
[in,out]lpDataarray to be cleared.
[in]nDataLennumber of bytes in array to be cleared.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
This function does not free any memory; it just zeroises it.

◆ WIPE_File()

long WIPE_File ( const char *  szFileName,
long  nOptions 
)

Wipe and delete a file using secure 7-pass DOD standards.

Parameters
[in]szFileNamespecifying the file to be deleted.
[in]nOptionsOption flags [New in v12.0]. Select one of:
PKI_WIPEFILE_DOD7 (0) to use DOD 7-pass (default)
PKI_WIPEFILE_SIMPLE to overwrite with single pass of zero bytes (quicker but less secure).
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
Wipes a file using the 7-pass DOD Standard according to [NISPOM] before deleting.

◆ X509_CertExpiresOn()

long X509_CertExpiresOn ( const char *  szCertFile,
char *  szOutput,
long  nOutChars,
long  nOptions 
)

Returns the date and time an X.509 certificate expires.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
[out]szOutputto receive the time-date string.
[in]nOutCharsspecifying the maximum length of the time-date string.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
Returns the number of characters set in szOutput. If nOutChars is zero it returns the maximum number of characters required (currently 20, but don't assume that for future releases). C/C++ users should allocate one extra for the terminating NUL character. If an error occurs, it returns a negative error code.
Remarks
The time format is in accordance with ISO 8601 and will always be of the form YYYY-MM-DDThh:mm:ssZ. The time is always given as GMT (Greenwich Mean Time, UTC, Zulu Time).

◆ X509_CertIssuedOn()

long X509_CertIssuedOn ( const char *  szCertFile,
char *  szOutput,
long  nOutChars,
long  nOptions 
)

Returns the date and time an X.509 certificate was issued.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
[out]szOutputto receive the time-date string.
[in]nOutCharsspecifying the maximum length of the time-date string.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
Returns the number of characters set in szOutput. If nOutChars is zero it returns the maximum number of characters required (currently 20, but don't assume that for future releases). C/C++ users should allocate one extra for the terminating NUL character. If an error occurs, it returns a negative error code.
Remarks
The time format is in accordance with ISO 8601 and will always be of the form YYYY-MM-DDThh:mm:ssZ. The time is always given as GMT (Greenwich Mean Time, UTC, Zulu Time).

◆ X509_CertIssuerName()

long X509_CertIssuerName ( const char *  szCertFile,
char *  szOutput,
long  nOutChars,
const char *  szDelim,
long  nOptions 
)

Extracts issuer's distinguished name from X.509 certificate.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
[out]szOutputto receive the name string.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szDelimspecifying the character to use as a delimiter (default ";").
[in]nOptionsOption flags. Select one of:
PKI_DEFAULT (0) (default)
PKI_X509_LDAP to output the LDAP string representation as per RFC 4514
PKI_X509_LATIN1 to try and convert Unicode/UTF-8/T.61 attribute strings to Latin-1 (8-bit ASCII)
Returns
Returns the number of characters set in szOutput. If nOutChars is zero it returns the maximum number of characters required. C/C++ users should allocate one extra for the terminating NUL character. If an error occurs, it returns a negative error code. The output using the PKI_X509_LDAP option is suitable as content for an <X509IssuerName> node in an XML-DSIG document.
Remarks
See the remarks for X509_CertSubjectName().

◆ X509_CertIsValidNow()

long X509_CertIsValidNow ( const char *  szCertFile,
long  nOptions 
)

Verifies that an X.509 certificate is currently valid.

Parameters
[in]szCertFilewith the filename of the certificate (or base64 representation).
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
Zero (0) if the certificate is valid at the current time. If the certificate has expired or is not yet valid, the return value is PKI_X509_EXPIRED (+16 = EXPIRED_ERROR); otherwise it returns a positive error code.
Remarks
Note that the return value for "success" is zero, not "true". Uses the system clock. The certificate may be in binary DER format or base64 PEM format.

[Changed in v12.0] If the certificate is otherwise of correct format but has expired or is not yet valid, this function returns EXPIRED_ERROR (16). Previous versions would return -1.

◆ X509_CertRequest()

long X509_CertRequest ( const char *  szNewReqFile,
const char *  szPriKeyFile,
const char *  szDistName,
const char *  szExtensions,
const char *  szPassword,
long  nOptions 
)

Creates a PKCS #10 certificate signing request (CSR) using the subject's private key file.

Parameters
[in]szNewReqFileName of new certificate request file to be created.
[in]szPriKeyFileName of subject's private key file (encrypted or unencrypted) or a PEM string containing the key.
[in]szDistNameDistinguished name string. See Specifying Distinguished Names for more details.
[in]szExtensions(optional) Extensions: a list of attribute-value pairs separated by semicolons (;) to be added to an extensionRequest element. See X.509 Extensions Parameter. [New in v10.0].
[in]szPasswordPassword for subject's encrypted private key file. Specify the empty string "" if key not encrypted [New in v12.0].
[in]nOptionsOption flags. Choose one signature algorithm from:
PKI_SIG_SHA1RSA (0) to use sha1WithRSAEncryption (default - CAUTION)
PKI_SIG_SHA224RSA to use sha224WithRSAEncryption
PKI_SIG_SHA256RSA to use sha256WithRSAEncryption [minimum recommended]
PKI_SIG_SHA384RSA to use sha384WithRSAEncryption
PKI_SIG_SHA512RSA to use sha512WithRSAEncryption
PKI_SIG_MD5RSA to use md5WithRSAEncryption [legacy, not recommended]
PKI_SIG_MD2RSA to use md2WithRSAEncryption [legacy, definitely not recommended]
PKI_SIG_RSA_PSS_SHA1 to use RSA-PSS-SHA1
PKI_SIG_RSA_PSS_SHA224 to use RSA-PSS-SHA224
PKI_SIG_RSA_PSS_SHA256 to use RSA-PSS-SHA256
PKI_SIG_RSA_PSS_SHA384 to use RSA-PSS-SHA384
PKI_SIG_RSA_PSS_SHA512 to use RSA-PSS-SHA512
PKI_SIG_ECDSA_SHA1 to use ecdsaWithSHA1
PKI_SIG_ECDSA_SHA224 to use ecdsaWithSHA224
PKI_SIG_ECDSA_SHA256 to use ecdsaWithSHA256
PKI_SIG_ECDSA_SHA384 to use ecdsaWithSHA384
PKI_SIG_ECDSA_SHA512 to use ecdsaWithSHA512
PKI_SIG_ED25519 to use Ed25519 [New in v20.0]
PKI_SIG_ED448 to use Ed448 [New in v22.0]

And add any combination of these:-
PKI_X509_FORMAT_BIN to create a BER-encoded binary file (default = base64 PEM format)
PKI_X509_REQ_KLUDGE to create a request with the "kludge" that omits the strictly mandatory attributes completely (default = include attributes with zero-length field)
PKI_X509_UTF8 to encode the DN as UTF8String (default = PrintableString)

Specialist options:-
PKI_PSS_SALTLEN_ZERO to use a zero-length salt in an RSA-PSS signature.
PKI_SIG_DETERMINISTIC to use the deterministic digital signature generation procedure of [RFC6979] for an ECDSA signature.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The default output is a base64 PEM format CSR file ready for sending to the issuer of your choice. Any existing file of the same name will be overwritten without warning.

◆ X509_CertSerialNumber()

long X509_CertSerialNumber ( const char *  szCertFile,
char *  szOutput,
long  nOutChars,
long  nOptions 
)

Returns the serial number of an X.509 certificate.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
[out]szOutputto receive the serial number.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default output in hexadecimal format
PKI_X509_DECIMAL to output number in decimal format
Returns
Returns the number of characters set in szOutput. If nOutChars is zero it returns the maximum number of characters required. C/C++ users should allocate one extra for the terminating NUL character. If an error occurs, it returns a negative error code.
Remarks
The certificate may be in binary DER format or base64 PEM format.

◆ X509_CertSubjectName()

long X509_CertSubjectName ( const char *  szCertFile,
char *  szOutput,
long  nOutChars,
const char *  szDelim,
long  nOptions 
)

Extracts subject's distinguished name from X.509 certificate.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
[out]szOutputto receive the name string.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]szDelimspecifying the character to use as a delimiter (default ";").
[in]nOptionsOption flags.
PKI_DEFAULT (0) (default)
PKI_X509_LDAP to output the LDAP string representation as per RFC 4514
PKI_X509_LATIN1 to try and convert Unicode/UTF-8/T.61 attribute strings to Latin-1 (8-bit ASCII)
Returns
Returns the number of characters set in szOutput. If nOutChars is zero it returns the maximum number of characters required. C/C++ users should allocate one extra for the terminating NUL character. If an error occurs, it returns a negative error code.
Remarks
The distinguished name will be returned in a string expressed in the same format described in Distinguished Names, e.g. "C=AU;O=myorg;CN=Dave". Only the first character in szDelim is used. The default delimiter is a semi-colon (;) if an empty string or NULL is specified for szDelim. If the attribute key is not in our set of supported types, the OID will be expressed in dot notation, e.g. "2.5.4.4=My Surname".

If an attribute value is encoded in a multi-byte-character string format (such as UTF8String or BMPString), the value will be expressed as a hexadecimal-encoded string [NB changed in v3.9]
preceded by the hash symbol ('#' U+0023) and small letter x ('x' U+0078), e.g.

"C=TW;<span class="withdrawn">O=E8 A1 8C E6 94 BF E9 99 A2</span>" (v3.8 and earlier)
"C=TW;O=#xE8A18CE694BFE999A2" (v3.9 and later)

Use the PKI_X509_LATIN1 option to return the string encoded in Latin-1, if possible, so it will display properly on systems that cannot cope with UTF-8.

[New in v3.9] Use the PKI_X509_LDAP option to obtain the distinguished name in LDAP string form instead. The examples above would be returned as "CN=Dave,O=myorg,C=AU" and "O=\E8\A1\8C\E6\94\BF\E9\99\A2,C=TW", with commas as delimiters, the RDNs in reverse order, and non-printable-ASCII characters escaped in hexadecimal form "\xx" as per [RFC4514]. See LDAP string representation for more details. The szDelim parameter is ignored with the PKI_X509_LDAP option.

The output using the PKI_X509_LDAP option is suitable as content for an <X509SubjectName> node in an XML-DSIG document.

◆ X509_CertThumb()

long X509_CertThumb ( const char *  szCertFile,
char *  szOutput,
long  nOutChars,
long  nOptions 
)

Calculates the thumbprint (message digest hash) of an X.509 certificate.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
[out]szOutputto receive the message digest.
[in]nOutCharsspecifying the maximum length of the digest string.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
the number of digits set in the output string or a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The maximum length of the output string is PKI_MAX_HASH_CHARS (C/C++ users add one). The default hash algorithm is SHA-1 and the result should match the SHA-1 thumbprint shown in the Windows Certificate Viewer.

◆ X509_CheckCertInCRL()

long X509_CheckCertInCRL ( const char *  szCertFile,
const char *  szCrlFile,
const char *  szCRLIssuerCert,
const char *  szDate,
long  nOptions 
)

Checks whether an X.509 certificate has been revoked in a Certificate Revocation List (CRL).

Parameters
[in]szCertFilewith name of X.509 certificate to be checked (or base64 representation).
[in]szCrlFilewith name of CRL file.
[in]szCRLIssuerCert(optional) with name of X.509 certificate file for the entity that issued the CRL (or base64 representation).
[in]szDate(optional) with date in ISO date format (e.g. 2009-12-31T12:59:59Z) on or after you wish to check for revocation. Leave empty "" for any date. The time must be in GMT (UTC, Zulu time).
[in]nOptionsOption flags. Not used. Specify zero.
Returns
Zero (0) if the certificate is not in the CRL (i.e has not been revoked by that particular CRL). If the certificate has been revoked it returns PKI_X509_REVOKED (+42=REVOCATION_ERROR); otherwise a negative error code.
Remarks
The optional szDate parameter allows you to check whether a certificate was revoked only after the given date-time, which must be in GMT (UTC). If the optional szCRLIssuerCert is specified, the signature of the CRL will be checked against the key in the issuer's certificate and a SIGNATURE_ERROR will result if the signature is invalid.

You can directly verify the signature in the CRL file using the X509_VerifyCert() function.

[Changed in v12.0] If the certificate is otherwise of correct format but has been revoked, this function returns REVOCATION_ERROR (42). Previous versions would return +1.

◆ X509_GetCertCountInP7Chain()

long X509_GetCertCountInP7Chain ( const char *  szP7cFile,
long  nOptions 
)

Return number of certificates in a PKCS-7 "certs-only" certificate chain file.

Parameters
[in]szP7cFilefilename of the PKCS-7 "certs-only" file, or a string containing its PEM textual representation.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
Number of X.509 certificates found or a negative error code.
Remarks
This function will also work with CMS signed data objects, too.

◆ X509_GetCertFromP7Chain()

long X509_GetCertFromP7Chain ( const char *  szNewCertFile,
const char *  szP7cFile,
long  nIndex,
long  nOptions 
)

Extracts an X.509 certificate from a PKCS-7 "certs-only" certificate chain file (typically saved with extension .p7c or .p7b), saving the output directly as a new file.

Parameters
[in]szNewCertFilefilename of the output file to be created.
[in]szP7cFilefilename of the PKCS-7 "certs-only" file, or a string containing its PEM textual representation.
[in]nIndexspecifying which certificate (1,2,...) in the chain to extract, or 0 (deprecated) to return the count of certificates in the set.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful and nIndex is greater than zero, it returns the number of bytes written to the output file, which may be zero if no certificate could be found at the given index. If an error occurred, it returns a negative error code.
Remarks
If nIndex is specified as a number greater than zero, the nIndex'th certificate found in the list, if any, will be extracted and saved directly as a DER-encoded X.509 certificate file. This function will also extract certificates from CMS signed data objects, too.

[New in v12.2] To find the number of certificates in the chain, use X509_GetCertCountInP7Chain. The old (deprecated) way to find the count of certificates was to set nIndex to zero.

◆ X509_GetCertFromPFX()

long X509_GetCertFromPFX ( const char *  szNewCertFile,
const char *  szPfxFile,
const char *  szPassword,
long  nOptions 
)

Extracts an X.509 certificate from a PKCS-12 PFX/.p12 file, saving the output directly as a new file.

Parameters
[in]szNewCertFilespecifying the filename of the output file to be created.
[in]szPfxFilecontaining the PFX filename
[in]szPasswordcontaining password or "" if certificate is not encrypted
[in]nOptionsoption flags:
PKI_DEFAULT (0) to export a single DER-encoded X.509 certificate.
PKI_PFX_P7CHAIN to output all certificates in a PKCS7 certificate chain file (.p7b or .p7c).
Returns
If successful, it returns the number of bytes written to the output file; otherwise it returns a negative error code.
Remarks
The default behaviour is to extract one certificate from the PFX file and save directly as a DER-encoded X.509 certificate file. Any existing file of the same name will be overwritten without warning. It will attempt to find a matching certificate for any private key, otherwise it will save the first pkcs-12-certBag found in the PFX file containing a x509Certificate.

Both unencrypted certificates and certificates encrypted with the weak 40-bit encryption used by "default" in Microsoft and OpenSSL PKCS-12 files are supported, but not any other encryption algorithm.

If no certificate can be found the function will return a negative NO_DATA_ERROR error code.

The PKI_PFX_P7CHAIN option will output all X.509 certificates found into a single PKCS#7 certificate chain file. The correct MIME-designated file extension for such a file is .p7c, but for historical reasons Microsoft use .p7b instead.

◆ X509_HashIssuerAndSN()

long X509_HashIssuerAndSN ( const char *  szCertFile,
char *  szOutput,
long  nOutChars,
long  nOptions 
)

Returns the message digest hash of the PKCS #7 issuerAndSerialNumber value of an X.509 certificate in hexadecimal format.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
[out]szOutputto receive the hash digest.
[in]nOutCharsspecifying the maximum number of characters to be received.
[in]nOptionsOption flags. Select one of:
PKI_HASH_SHA1 (0) to use the SHA-1 algorithm (default)
PKI_HASH_SHA224 to use the SHA-224 algorithm
PKI_HASH_SHA256 to use the SHA-256 algorithm
PKI_HASH_SHA384 to use the SHA-384 algorithm
PKI_HASH_SHA512 to use the SHA-512 algorithm
PKI_HASH_MD5 to use the MD5 algorithm
Returns
Returns the number of characters set in szOutput. If nOutChars is zero it returns the maximum number of characters required. C/C++ users should allocate one extra for the terminating NUL character. If an error occurs, it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The certificate may be in binary BER format or base64 PEM format.

◆ X509_KeyUsageFlags()

long X509_KeyUsageFlags ( const char *  szCertFile)

Returns a bitfield containing the keyUsage flags for an X.509 certificate.

Parameters
[in]szCertFilewith the filename of the X.509 certificate (or base64 representation).
Returns
If successful, it returns a positive integer containing the keyUsage flags; or 0 if no keyUsage flags are set; otherwise it returns a negative error code.
Remarks
The certificate may be in binary BER format or base64 PEM format. The presence of a key usage flag can be ascertained by AND'ing the result with the bitfield value for each flag.
digitalSignature 0x0001
nonRepudiation   0x0002
keyEncipherment  0x0004
dataEncipherment 0x0008
keyAgreement     0x0010
keyCertSign      0x0020
cRLSign          0x0040
encipherOnly     0x0080
decipherOnly     0x0100

These values are defined as PKI_X509_KEYUSAGE_DIGITALSIGNATURE, etc.

◆ X509_MakeCert()

long X509_MakeCert ( const char *  szNewCertFile,
const char *  szIssuerCertFile,
const char *  szSubjectPubKeyFile,
const char *  szIssuerPriKeyFile,
long  nCertNum,
long  nYearsValid,
const char *  szDistName,
const char *  szExtensions,
long  nKeyUsageFlags,
const char *  szPassword,
long  nOptions 
)

Creates an X.509 certificate using subject's public key and issuer's private key files.

Parameters
[in]szNewCertFileName of new certificate file to be created.
[in]szIssuerCertFileName of issuer's X.509 certificate file (or its base64 representation or as a PEM string).
[in]szSubjectPubKeyFileName of subject's public key file or a PEM string containing the key, or a valid internal key string.
[in]szIssuerPriKeyFileName of issuer's private key file (encrypted or unencrypted) or a PEM string containing the key, or a valid internal key string.
[in]nCertNumSerial number for new certificate. Ignored if serialNumber is set in szExtensions.
[in]nYearsValidNumber of years certificate is to be valid from current date and hour (can be changed with szExtensions).
[in]szDistNameDistinguished name string. See Specifying Distinguished Names for more details.
[in]szExtensionsExtensions: a list of attribute-value pairs separated by semicolons (;). See X.509 Extensions Parameter. Specify "" or NULL to ignore.
[in]nKeyUsageFlagsBit flags to set Key Usage extension:
OptionTo set
PKI_X509_KEYUSAGE_DIGITALSIGNATUREdigitalSignature
PKI_X509_KEYUSAGE_NONREPUDIATIONnonRepudiation
PKI_X509_KEYUSAGE_KEYENCIPHERMENTkeyEncipherment
PKI_X509_KEYUSAGE_DATAENCIPHERMENTdataEncipherment
PKI_X509_KEYUSAGE_KEYAGREEMENTkeyAgreement
PKI_X509_KEYUSAGE_KEYCERTSIGNkeyCertSign
PKI_X509_KEYUSAGE_CRLSIGNcRLSign
PKI_X509_KEYUSAGE_ENCIPHERONLYencipherOnly
PKI_X509_KEYUSAGE_DECIPHERONLYdecipherOnly
Add to combine options. Specify zero to omit Key Usage extension.
[in]szPasswordPassword for issuer's encrypted private key file. Specify the empty string "" if key not encrypted [New in v12.0].
[in]nOptionsOption flags. Choose one signature algorithm from:
PKI_SIG_SHA1RSA (0) to use sha1WithRSAEncryption (default - CAUTION)
PKI_SIG_SHA224RSA to use sha224WithRSAEncryption
PKI_SIG_SHA256RSA to use sha256WithRSAEncryption [minimum recommended]
PKI_SIG_SHA384RSA to use sha384WithRSAEncryption
PKI_SIG_SHA512RSA to use sha512WithRSAEncryption
PKI_SIG_MD5RSA to use md5WithRSAEncryption [legacy, not recommended]
PKI_SIG_MD2RSA to use md2WithRSAEncryption [legacy, definitely not recommended]
PKI_SIG_RSA_PSS_SHA1 to use RSA-PSS-SHA1
PKI_SIG_RSA_PSS_SHA224 to use RSA-PSS-SHA224
PKI_SIG_RSA_PSS_SHA256 to use RSA-PSS-SHA256
PKI_SIG_RSA_PSS_SHA384 to use RSA-PSS-SHA384
PKI_SIG_RSA_PSS_SHA512 to use RSA-PSS-SHA512
PKI_SIG_ECDSA_SHA1 to use ecdsaWithSHA1
PKI_SIG_ECDSA_SHA224 to use ecdsaWithSHA224
PKI_SIG_ECDSA_SHA256 to use ecdsaWithSHA256
PKI_SIG_ECDSA_SHA384 to use ecdsaWithSHA384
PKI_SIG_ECDSA_SHA512 to use ecdsaWithSHA512
PKI_SIG_ED25519 to use Ed25519 [New in v20.0]
PKI_SIG_ED448 to use Ed448 [New in v22.0]

And add any combination of these:-
PKI_X509_VERSION1 to generate a Version 1 certificate, i.e. no extensions (default = Version 3).
PKI_X509_CA_TRUE to set the basicConstraints subject type to be a CA (default = End Entity)
PKI_X509_NO_BASIC to disable the basicConstraints extension (default = include)
PKI_X509_UTF8 to encode the subject's DN fields as UTF8String (default = PrintableString)
PKI_X509_FORMAT_PEM to save the certificate in PEM format (default = DER-encoded binary)
PKI_X509_AUTHKEYID to add the issuer's KeyIdentifier, if present, as an AuthorityKeyIdentifer (default = do not add)

Specialist options:-
PKI_PSS_SALTLEN_ZERO to use a zero-length salt in an RSA-PSS signature.
PKI_SIG_DETERMINISTIC to use the deterministic digital signature generation procedure of [RFC6979] for an ECDSA signature.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
At least one valid attribute for the subject's distinguished name (DN) must be included. A version 1 certificate created using the PKI_X509_VERSION1 flag will, by definition, exclude any version 3 extensions.

If the PKI_X509_UTF8 flag is set, each attribute of the subject's DN will be encoded as a UTF8String. Otherwise the default encoding will be PrintableString or, if a non-printable character is specified, then as either IA5String or T61String - see Specifying Distinguished Names for more details. The encoding of the issuer's DN will be exactly as in the issuer's certficate.

If the PKI_X509_AUTHKEYID flag is set then an authorityKeyIdentifer extension will be set if there is a corresponding subjectKeyIdentifer in the issuer's certificate. Otherwise no such extension will be set.

The default validity period is from one minute ago by the system clock for a period of a whole number of years set by the nYearsValid parameter. This time will always have the seconds set to 01. A different validity period can be set using the notBefore and notAfter attributes in the szExtensions parameter (see X509 Extensions Parameter).

The serial number can be set to be an integer in the range 1 to 2,147,483,647 using the nCertNum parameter, or (once you have used these up!) it can be set to a larger value, perhaps a random large integer represented by a hexadecimal string, using the serialNumber attribute in the szExtensions parameter (see X509 Extensions Parameter).

As an alternative, you can create a new X.509 certificate using a PKCS-10 certificate signing request (CSR) file. Pass the name of the CSR file in the szSubjectPubKeyFile parameter and set the szDistName empty "". The empty distinguished name parameter is a flag that a CSR file is being used. See the example below.

[New in v12.0] Added support for unencrypted private key files for szIssuerPriKeyFile as well as encrypted ones. Specify szPassword="" to flag an unencrypted key.

[New in v12.0] Added support for RSA-PSS and ECDSA signatures. Both the signing key and the subject's public key must be either both RSA keys for the RSA options, or both EC keys for the ECDSA signature options. The MGF hash function for RSA-PSS signatures in an X.509 certificate is always the same as the signature hash function. The signing key must be long enough to include the specified digest value and other encoding bytes. For example, a 1024-bit RSA key is too short to sign using RSA-PSS-SHA512 (see RSA signature and encryption schemes). Not all signature options provided may be accepted by other applications. Note also that both these signature schemes are probabilistic and each new signature contains randomly generated salt values, so you won't reproduce the same certificate even with identical inputs. Use the specialist options PKI_PSS_SALTLEN_ZERO and PKI_SIG_DETERMINISTIC with RSA-PSS and ECDSA, respectively, to force a deterministic (fixed) result.

[New in v12.3] Added ability to specify an empty subjectName, to set extKeyUsage extension purposes in the X.509 Extensions Parameter, and mark an arbitrary extension as critical. Setting szDistName = "$" will create an X.509 document with an empty subjectName. At least one field for a subject alternative name extension (altSubjectName) must be specified and the extension will automatically be marked critical.

char *dn = "$";
char *extns = "iPAddress=192.168.15.1;extKeyUsage=serverAuth,clientAuth,emailProtection,critical;";

[New in v20.5] Added ability to pass an internal key string for the subject's public key and signer's private key.

◆ X509_MakeCertSelf()

long X509_MakeCertSelf ( const char *  szNewCertFile,
const char *  szPriKeyFile,
long  nCertNum,
long  nYearsValid,
const char *  szDistName,
const char *  szExtensions,
long  nKeyUsageFlags,
const char *  szPassword,
long  nOptions 
)

Creates a self-signed X.509 certificate.

Parameters
[in]szNewCertFileName of new certificate file to be created.
[in]szPriKeyFileName of issuer's private key file (encrypted or unencrypted) or a PEM string containing the key, or a valid internal key string.
[in]nCertNumSerial number for new certificate. Ignored if serialNumber is set in szExtensions.
[in]nYearsValidNumber of years certificate is to be valid starting at current date and hour (can be changed with szExtensions).
[in]szDistNameDistinguished name string (required). See Specifying Distinguished Names for more details.
[in]szExtensionsExtensions: optional list of attribute-value pairs separated by semicolons (;). See X.509 Extensions Parameter. Specify "" or NULL to ignore.
[in]nKeyUsageFlagsFlags to set Key Usage extensions:
PKI_X509_KEYUSAGE_DIGITALSIGNATUREto set digitalSignature
PKI_X509_KEYUSAGE_NONREPUDIATIONto set nonRepudiation
PKI_X509_KEYUSAGE_KEYENCIPHERMENTto set keyEncipherment
PKI_X509_KEYUSAGE_DATAENCIPHERMENTto set dataEncipherment
PKI_X509_KEYUSAGE_KEYAGREEMENTto set keyAgreement
PKI_X509_KEYUSAGE_KEYCERTSIGNto set keyCertSign
PKI_X509_KEYUSAGE_CRLSIGNto set cRLSign
PKI_X509_KEYUSAGE_ENCIPHERONLYto set encipherOnly
PKI_X509_KEYUSAGE_DECIPHERONLYto set decipherOnly
Add to combine options. Specify zero to omit Key Usage extension.
[in]szPasswordcontaining password for Issuer's encrypted private key file. Specify the empty string "" if key not encrypted [New in v12.0].
[in]nOptionsOption flags. Choose one signature algorithm from:
PKI_SIG_SHA1RSA (0) to use sha1WithRSAEncryption (default - CAUTION)
PKI_SIG_SHA224RSA to use sha224WithRSAEncryption
PKI_SIG_SHA256RSA to use sha256WithRSAEncryption [minimum recommended]
PKI_SIG_SHA384RSA to use sha384WithRSAEncryption
PKI_SIG_SHA512RSA to use sha512WithRSAEncryption
PKI_SIG_MD5RSA to use md5WithRSAEncryption [legacy, not recommended]
PKI_SIG_MD2RSA to use md2WithRSAEncryption [legacy, definitely not recommended]
PKI_SIG_RSA_PSS_SHA1 to use RSA-PSS-SHA1
PKI_SIG_RSA_PSS_SHA224 to use RSA-PSS-SHA224
PKI_SIG_RSA_PSS_SHA256 to use RSA-PSS-SHA256
PKI_SIG_RSA_PSS_SHA384 to use RSA-PSS-SHA384
PKI_SIG_RSA_PSS_SHA512 to use RSA-PSS-SHA512
PKI_SIG_ECDSA_SHA1 to use ecdsaWithSHA1
PKI_SIG_ECDSA_SHA224 to use ecdsaWithSHA224
PKI_SIG_ECDSA_SHA256 to use ecdsaWithSHA256
PKI_SIG_ECDSA_SHA384 to use ecdsaWithSHA384
PKI_SIG_ECDSA_SHA512 to use ecdsaWithSHA512
PKI_SIG_ED25519 to use Ed25519 [New in v20.0]
PKI_SIG_ED448 to use Ed448 [New in v22.0]

And add any combination of these:-
PKI_X509_VERSION1 to generate a Version 1 certificate, i.e. no extensions (default = Version 3).
PKI_X509_CA_TRUE to set the basicConstraints subject type to be a CA (default = End Entity)
PKI_X509_NO_BASIC to disable the basicConstraints extension (default = include)
PKI_X509_UTF8 to encode the subject's DN fields as UTF8String (default = PrintableString)
PKI_X509_FORMAT_PEM to save the certificate in PEM format (default = DER-encoded binary)

Specialist options:-
PKI_PSS_SALTLEN_ZERO to use a zero-length salt in an RSA-PSS signature.
PKI_SIG_DETERMINISTIC to use the deterministic digital signature generation procedure of [RFC6979] for an ECDSA signature.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
See the remarks for X509_MakeCert(). A self-signed certificate has the same Issuer and Subject distinguished name. Add the PKI_X509_UTF8 flag to encode the distinguished names in UTF-8. The BasicConstraints subject type will always be a CA for a version 3 self-signed certificate, unless explicitly excluded with the PKI_X509_NO_BASIC flag.

◆ X509_MakeCRL()

long X509_MakeCRL ( const char *  szCrlFile,
const char *  szIssuerCert,
const char *  szIssuerKeyFile,
const char *  szPassword,
const char *  szRevokedCertList,
const char *  szExtensions,
long  nOptions 
)

Creates an X.509 Certificate Revocation List (CRL).

Parameters
[in]szCrlFilewith name of new CRL file to be created.
[in]szIssuerCertwith name of issuer's X.509 certificate file (or base64 representation).
[in]szIssuerKeyFilewith name of issuer's encrypted private key file.
[in]szPasswordcontaining password for issuer's encrypted private key file.
[in]szRevokedCertListwith list of revoked certificates in format serialNumber,revocationDate; ... or the empty string "" for no revoked certificates. See the Remarks section below for more details.
[in]szExtensions(optional) containing one or more attribute-value pairs separated by semicolons (;). Valid attribute-value pairs are:
  • thisUpdate=<iso-date-string>
  • nextUpdate=<iso-date-string>
[in]nOptionsOption flags. Choose one signature algorithm from:
PKI_SIG_SHA1RSA (0) to use sha1WithRSAEncryption (default - CAUTION)
PKI_SIG_SHA224RSA to use sha224WithRSAEncryption
PKI_SIG_SHA256RSA to use sha256WithRSAEncryption [minimum recommended]
PKI_SIG_SHA384RSA to use sha384WithRSAEncryption
PKI_SIG_SHA512RSA to use sha512WithRSAEncryption
PKI_SIG_MD5RSA to use md5WithRSAEncryption [legacy, not recommended]
PKI_SIG_MD2RSA to use md2WithRSAEncryption [legacy, definitely not recommended]
PKI_SIG_RSA_PSS_SHA1 to use RSA-PSS-SHA1
PKI_SIG_RSA_PSS_SHA224 to use RSA-PSS-SHA224
PKI_SIG_RSA_PSS_SHA256 to use RSA-PSS-SHA256
PKI_SIG_RSA_PSS_SHA384 to use RSA-PSS-SHA384
PKI_SIG_RSA_PSS_SHA512 to use RSA-PSS-SHA512
PKI_SIG_ECDSA_SHA1 to use ecdsaWithSHA1
PKI_SIG_ECDSA_SHA224 to use ecdsaWithSHA224
PKI_SIG_ECDSA_SHA256 to use ecdsaWithSHA256
PKI_SIG_ECDSA_SHA384 to use ecdsaWithSHA384
PKI_SIG_ECDSA_SHA512 to use ecdsaWithSHA512
PKI_SIG_ED25519 to use Ed25519 [New in v20.0]
PKI_SIG_ED448 to use Ed448 [New in v22.0]

And add any combination of these:-
PKI_X509_FORMAT_PEM to save the certificate in PEM format (default = DER-encoded binary)

Specialist options:-
PKI_PSS_SALTLEN_ZERO to use a zero-length salt in an RSA-PSS signature.
PKI_SIG_DETERMINISTIC to use the deterministic digital signature generation procedure of [RFC6979] for an ECDSA signature.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
This function creates a version 1 CRL file with no extensions or cRLReason's. The parameter szRevokedCertList must be in the form
serialNumber,revocationDate;serialNumber,revocationDate; ...

The serialNumber must either be a positive decimal number (e.g. 123) or the number in hex format preceded by "#x" (e.g. "#x0102deadbeef"). The revocation date must be in ISO date format (e.g. 2009-12-31 or 2009-12-31T12:59:59Z).

By default, the lastUpdate time in the CRL is set to the time given by the system clock, and nextUpdate time is left empty. You can specify your own times using the lastUpdate and nextUpdate attributes in the szExtensions parameter. Times, if specified, must be in ISO 8601 format and are always interpreted as GMT times whether or not you add a "Z".

◆ X509_QueryCert()

long X509_QueryCert ( char *  szOutput,
long  nOutChars,
const char *  szCertFile,
const char *  szQuery,
long  nOptions 
)

Queries an X.509 certificate file for selected information.

Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the length of the output string.
[in]szCertFilewith name of X.509 certificate file (or base64 representation).
[in]szQueryspecifying the query (see Remarks below).
[in]nOptionsoption flags:
PKI_DEFAULT (0) for default options
PKI_QUERY_GETTYPE to return the type of data returned for a given query.
PKI_X509_LATIN1 to try and convert Unicode/UTF-8/T.61 attribute strings to Latin-1 (ISO-8859-1)
PKI_X509_UTF8 to output attribute strings encoded in UTF-8 [New in v20.3]
PKI_X509_LDAP to output the distinguished name in LDAP string representation (for queries "issuerName" and "subjectName" only)
PKI_X509_DECIMAL to output the serial number in decimal format instead of hex (for query "serialNumber" only)
Returns
If successful, the return value is a positive integer giving either the result itself (if the result is a number) or the number of characters in the output string (if the query is looking for a string). If the item queried is not present, the return value is zero. If there is an error (e.g. a missing or invalid certificate file), it returns a negative error code.
Remarks
Valid queries are (case-insenitive):
Query StringReturnsData Type
versionX.509 version number, e.g. 1 or 3. Number
serialNumberSerial number in hex-encoded formatString
signatureAlgorithmSignature algorithm used, e.g. "sha1WithRSAEncryption". String
sigAlgIdID of signature algorithm used, see PKI_SIG_* valuesNumber
signatureValueSignature value in hex-encoded formatString
notBeforeDate on which the certificate validity period begins in format yyyy-mm-ddThh:nn:ssZString
notAfterDate on which the certificate validity period ends in format yyyy-mm-ddThh:nn:ssZString
issuerNameDistinguished name (DN) of entity who has signed and issued the certificateString
subjectNameDistinguished name (DN) of the subjectString
subjectPublicKeyAlgorithmAlgorithm used in subject's public key, e.g. "dsa" or "rsaEncryption". String
subjectKeyIdentifierThe subject key identifier extension, if present, in hex-encoded formatString
authorityKeyIdentifierThe authority key identifier extension, if present, in hex-encoded formatString
rfc822NameFirst internet mail address found contained in a subjectAltName extension, if presentString
isCAReturns 1 if the subject type is a CA, otherwise returns 0. Number
keyUsageStringkeyUsage flags in text format, e.g. "digitalSignature,nonRepudiation"String
extKeyUsageStringextKeyUsage purposes in text format, e.g. "codeSigning,timeStamping"String
cRLDistributionPointsURIFirst URI found in cRLDistributionPoints, if anyString
authorityInfoAccessURIFirst URI found in authorityInfoAccess, if anyString
subjectAltNameSubject alternative name extension, if present. [New in v10.0]String
hashAlgorithmHash algorithm used in signature, e.g. "sha256". [New in v12.0]String
pssParamsParameters used for RSA-PSS (if applicable). [New in v12.0]

String

Some of these queries duplicate or complement existing functions:

The "raw" VBA/C function behaves differently depending on whether the output is a string or a number. If the result data type is a number then it returns the value directly. If the result is a string, then it sets szOutput and returns the number of characters in the string. The required number of characters can be found by passing zero for nOutChars or a null string for szOutput. ANSI C users must add one to this value when allocating memory.

Note that the VBA wrapper function and the C#/VB.NET methods always return a string, which is different from the behaviour of the raw VB6/C function.

To find out the type of data returned for a given query, use the PKI_QUERY_GETTYPE option. The function will return either PKI_QUERY_NUMBER (1) or PKI_QUERY_STRING (2), or a negative "invalid query" error. For example

nRet = X509_QueryCert("", 0, "", "version", PKI_QUERY_GETTYPE);

will return PKI_QUERY_NUMBER.

If an attribute value is encoded in a multi-byte-character string format (such as UTF8String or BMPString), the value will be expressed as a hexadecimal-encoded string [NB changed in v3.9] preceded by the hash symbol ('#' U+0023), e.g.

"C=TW;<span class="withdrawn">O=E8 A1 8C E6 94 BF E9 99 A2</span>" (v3.8 and earlier)
"C=TW;O=#E8A18CE694BFE999A2" (v3.9 and later)

Use the PKI_X509_LATIN1 option to return the string encoded in Latin-1, if possible, to help with display issues.

The output from the queries "issuerName" and "subjectName" using the PKI_X509_LDAP option are suitable as content for the <X509IssuerName> and <X509SubjectName> nodes, respectively, in the <X509Data> node of an XML-DSIG document.

◆ X509_ReadCertStringFromP7Chain()

long X509_ReadCertStringFromP7Chain ( char *  szOutput,
long  nOutChars,
const char *  szP7cFile,
long  nIndex,
long  nOptions 
)

Reads an X.509 certificate into a base64 string from PKCS-7 "certs-only" data.

Parameters
[out]szOutputstring buffer to receive the output.
[in]nOutCharssize of the output buffer in bytes.
[in]szP7cFilefilename of a PKCS-7 "certs-only" file, or a string containing its PEM textual representation.
[in]nIndexspecifying which certificate (1,2,...) in the chain to extract, or (deprecated) 0 to return the count of certificates in the set.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful and nIndex is greater than zero, the return value is a positive number indicating the number of characters in or required for the output string, which may be zero if no certificate could be found at the given index. However, if nIndex is zero, it returns the count of certificates found in the list. If an error occurred, it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The output is a base64 string representation of the extracted X.509 certificate.

If nIndex is specified as a number greater than zero, the nIndex'th certificate found in the list, if any, will be extracted to a base64-encoded string which can be used to represent the X.509 certificate directly in this Toolkit.

This function will also extract certificates from CMS signed data objects, too.

[New in v12.2] To find the number of certificates in the chain, use X509_GetCertCountInP7Chain. The old (deprecated) way to find the count of certificates was to set nIndex to zero.

◆ X509_ReadCertStringFromPFX()

long X509_ReadCertStringFromPFX ( char *  szOutput,
long  nOutChars,
const char *  szPfxFile,
const char *  szPassword,
long  nOptions 
)

Reads an X.509 certificate into a base64 string from PKCS-12 PFX/.p12 data.

Parameters
[out]szOutputstring buffer to receive the output.
[in]nOutCharssize of the output buffer in bytes.
[in]szPfxFilefilename of a PFX file, or a string containing its PEM textual representation.
[in]szPasswordcontaining password or "" if certificate is not encrypted
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
If successful, the return value is a positive number indicating the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The default behaviour is to extract one certificate from the PFX file and output as a base64 string representation of the extracted X.509 certificate. It will attempt to find a matching certificate for any private key, otherwise it will save the first pkcs-12-certBag found in the PFX file containing a x509Certificate.

Both unencrypted certificates and certificates encrypted with the weak 40-bit encryption used by "default" in Microsoft and OpenSSL PKCS-12 files are supported, but not any other encryption algorithm.

If no certificate can be found the function will return a negative NO_DATA_ERROR error code.

◆ X509_ReadStringFromFile()

long X509_ReadStringFromFile ( char *  szOutput,
long  nOutChars,
const char *  szCertFile,
long  nOptions 
)

Creates a base64 string of an X.509 certificate file.

Parameters
[out]szOutputto receive the output.
[in]nOutCharsspecifying the length of the output string.
[in]szCertFilewith name of X.509 certificate file.
[in]nOptionsoption flags: not used. Set to zero.
Returns
If successful, the return value is a positive number indicating the number of characters in the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

This function reads in the complete X.509 certificate as a continuous base64 string. The same certificate will always produce exactly the same string. This string can be used, for example, when creating an XML file which requires the certificate as an attribute, e.g.

<?xml version="1.0" encoding="UTF-8"?>
<Comprobante fecha="2005-09-02T16:30:00" folio="1" noAprobacion="1" 
noCertificado="00001000000000000114" 
certificado="MIIDWjCCAkKgAwIBAgIUMDAwMDExMDAwMDAyMDA..."
serie="A" version="1.0">

The output string must be long enough to receive the complete output or a SHORT_BUF_ERROR error will result.

◆ X509_SaveFileFromString()

long X509_SaveFileFromString ( const char *  szNewCertFile,
const char *  szCertString,
long  nOptions 
)

Creates an X.509 certificate file from its base64 string representation.

Parameters
[in]szNewCertFilewith name of X.509 certificate file to be created.
[in]szCertStringcontaining the base64 representation of the certificate.
[in]nOptionsoption flags:
PKI_X509_FORMAT_PEM to save the certificate in PEM format (default = DER-encoded binary)
Returns
If successful, the return value is zero; otherwise it returns a negative error code.
Remarks
This function creates a new X.509 certificate file from a base64 string. It is the reverse of X509_ReadStringFromFile(). Any existing file of the same name will be overwritten without warning. The default option (nOptions = 0) is to save the file in binary (BER, DER) format. A PEM format file will start with --—BEGIN CERTIFICATE--— and will contain the same base64 characters as in the certificate string. Both formats should be equally readable with the usual certificate manager programs and both should have the same message digest "thumbprint".

◆ X509_TextDump()

long X509_TextDump ( const char *  szFileOut,
const char *  szCertFile,
long  nOptions 
)

Dumps details of an X.509 certificate (or a X.509 certificate revocation list (CRL) or a PKCS-10 certificate signing request (CSR)) to a text file.

Parameters
[in]szFileOutwith the filename of text file to be created.
[in]szCertFilewith the filename of Certificate file (or base64 representation).
[in]nOptionsoption flags:
PKI_X509_LATIN1 to try and convert UTF-8 attribute strings to Latin-1 (for display purposes).
PKI_X509_UTF8 to output attribute strings encoded in UTF-8 [New in v20.3]
PKI_X509_LDAP to output the distinguished name in LDAP string representation.
PKI_X509_DECIMAL to output the serial number in decimal format instead of hexadecimal.
Returns
If successful, the return value is zero; otherwise it returns a nonzero error code.
Remarks
The input file may be in binary BER/DER format or base64 PEM file format, or may be passed in base64 representation or as a PEM string. It produces a text file containing the basic details of an X.509 certificate, X.509 certificate revocation list (CRL) or PKCS-10 certificate signing request (CSR).

[New in v12.3] The notation [!] denotes a critical extension, e.g. Key Usage[!]:.

◆ X509_TextDumpToString()

long X509_TextDumpToString ( char *  szOutput,
long  nOutChars,
const char *  szCertFile,
long  nOptions 
)

Dumps details of an X.509 certificate or a X.509 certificate revocation list (CRL) or a PKCS-10 certificate signing request (CSR) to a string.

Parameters
[out]szOutputString buffer to receive output.
[in]nOutCharsMaximum number of characters to be received.
[in]szCertFileName of input file (or its base64 or PEM string representation).
[in]nOptionsoption flags:
PKI_X509_LATIN1 to try and convert UTF-8 attribute strings to Latin-1 (for display purposes).
PKI_X509_UTF8 to output attribute strings encoded in UTF-8 (C/C++ only) [New in v20.3]
PKI_X509_LDAP to output the distinguished name in LDAP string representation.
PKI_X509_DECIMAL to output the serial number in decimal format instead of hexadecimal.
Returns
If successful, the return value is the number of characters in or required for the output string; otherwise it returns a negative error code.
Remarks
For the "raw" VBA/C function, the user must allocate an output string buffer szOutput of the required length. Specify a zero nOutChars or an empty string for szOutput to find the required length. ANSI C users must add one to this value when allocating memory.

The input file may be a an X.509 certificate, X.509 certificate revocation list (CRL) or PKCS-10 certificate signing request (CSR) and may be a file in binary BER/DER or base64 PEM file format, or may be passed in base64 representation or as a PEM string.

The output string must be long enough to receive the complete output or a SHORT_BUF_ERROR error will result.

◆ X509_ValidatePath()

long X509_ValidatePath ( const char *  szCertListOrP7File,
const char *  szTrustedCert,
long  nOptions 
)

Validates a certificate path.

Parameters
[in]szCertListOrP7Fileeither a list of certificate names separated by a semicolon or the name of a PKCS-7 "certs-only" file containing the certificates to be validated.
[in]szTrustedCertname of the trusted certificate (or base64 representation).
[in]nOptionsoption flags:
PKI_X509_NO_TIMECHECK to avoid checking if the certificates are valid now (default = check validity dates against system clock).
Returns
Zero (0) if the certification path is valid. If the certificates are otherwise of correct format but the validation fails, the return value is PKI_X509_INVALID (+43 = CERT_PATH_ERROR); otherwise a negative error code.
Remarks
A basic validation is carried out confirming that the subject of certificate x is the issuer of certificate x+1, that certficate x was signed by certificate x-1, and that each certificate is valid as at the time on the system clock. Only distinguished names are used to identify subjects and issuers, not alternative names or IDs. Certificate policies are ignored and no checks are made for revocation (use X509_CheckCertInCRL() individually). The order of the certificates in the input list is not important, but a complete chain must exist. Note that the certificates must either all exist inside one .p7c cert chain file, or exist individually as .cer files. In the latter case, specify all the file names in a semi-colon-separated list. You can also pass the individual certificate information in its base64 representation rather than filenames, as in szCertList="MIHgMIGaAgE...se348UN/Q=;MIHgMIGaAgEB...9j8eEtvHw=;...etc.

The szTrustedCert parameter is required unless a self-signed trust anchor is included in the list. If there is no self-signed certificate, then you must specify a trusted certificate which has signed the certificate at the top of your chain. If specified, this must exist separately as a .cer file.

All certificates must be valid at the time the check is made or an error will result, unless the PKI_X509_NO_TIMECHECK option is used. More information on the reason for an invalid certification path may be available by using PKI_LastError().

[Changed in v12.0] If the certificates are otherwise of correct format but the validation fails, this function returns CERT_PATH_ERROR (+43). Previous versions would return +1.

◆ X509_VerifyCert()

long X509_VerifyCert ( const char *  szCertToVerify,
const char *  szIssuerCert,
long  nOptions 
)

Verifies that an X.509 certificate - or X.509 certificate revocation list (CRL) or PKCS-10 certificate signing request (CSR) - has been signed by its issuer.

Parameters
[in]szCertToVerifyName of the file to be verified (or a PEM string).
[in]szIssuerCertName of the issuer's certificate file (or a PEM string). Leave empty "" for a PKCS#10 CSR.
[in]nOptionsoption flags: not used in this release. Specify zero.
Returns
Zero (0) if the certificate's signature is valid. If the certificate is otherwise of correct format but the validation fails, the return value is PKI_X509_VERIFY_FAILURE (+22 = SIGNATURE_ERROR); otherwise it returns a positive error code.
Remarks
This function verifies only that the certificate was signed by the owner of the public key in the issuer's certificate. It does not check the validity dates of either certificate (to do that use X509_CertIsValidNow()). Nor does it check that the certficate has been revoked (to do that use X509_CheckCertInCRL()). Only certificates signed with supported signature algorithms can be checked: see Supported Algorithms. The certificate file may be in binary BER/DER format or base64 PEM file format, or may be passed in base64 representation or as a PEM string.

This function can also be used to verify that an X.509 Certificate Revocation List (CRL) has been signed by the owner of the issuer's certificate or that the self-signed signature in a PKCS#10 Certificate Signing Request (CSR) is valid. Just pass the name of the file (or its PEM string form) as szCertToVerify.

[New in v12.0] A PKCS#10 Certificate Signing Request (CSR) contains its own public key which it can use to verify its own signature directly. To verify a CSR, pass its name in szCertToVerify and set szIssuerCert="". See example below.

[Changed in v12.0] If the certificate is otherwise of correct format but the validation fails, this function returns SIGNATURE_ERROR (22). Previous versions would return -1.

◆ XOF_Bytes()

long XOF_Bytes ( unsigned char *  lpOutput,
long  nOutBytes,
const void *  lpMessage,
long  nMsgLen,
long  nOptions 
)

Generate bytes using an extendable output function (XOF).

Parameters
[out]lpOutputbyte buffer to receive the output.
[in]nOutBytessize of output buffer in bytes.
[in]lpMessagebyte array containing the input data.
[in]nMsgLenlength of the input data in bytes.
[in]nOptionsOption flags. Select one of:
PKI_XOF_SHAKE128 to use SHAKE128
PKI_XOF_SHAKE256 to use SHAKE256
PKI_XOF_MGF1_SHA1 to use MGF1-SHA-1
PKI_XOF_MGF1_SHA256 to use MGF1-SHA-256
PKI_XOF_MGF1_SHA512 to use MGF1-SHA-512
Returns
If successful, the return value is the number of bytes in the output; otherwise it returns a negative error code.
Remarks
The output buffer lpOutput must exist. It will be filled with exactly nOutBytes bytes. Note there is no zero option for nOptions: a valid option flag must be specified.

SHAKE128 and SHAKE256 are described in [FIPS202]. MGF1, despite its name as a Mask Generation Function (MGF), is also an eXtendable Output Function (XOF) using the SHA1/SHA-2 hash functions, and is described in [PKCS1].

Copyright © 2004-24 D.I. Management Services Pty Limited t/a CryptoSys ABN 78 083 210 584 Australia. All rights reserved. <www.di-mgt.com.au> <www.cryptosys.net>. Generated on Mon Sep 23 2024 20:48:24 by Doxygen 1.9.1.