Enveloped Message Example 2

The following example code demonstrates the process of encoding a signed message, using that signed message as the inner-content for an enveloped message, and finally, testing the inner-content of the enveloped message to determine its inner-content type in preparation for decoding.

//=============================================================
// EXAMPLE CODE FOR CREATING A "BARE" SIGNED MESSAGE.
//=============================================================

// Use this constant definition (or one similar to it) to define
// a single encoding type that can be used in all parameters and
// data members that require one or the other or both.
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | CRYPT_ASN_ENCODING)

//-------------------------------------------------------------
// Get a pointer to the message content- this code creates 
// the message content and gets a pointer to it. In reality, 
// the content will usually exist somewhere and a pointer to it
// will get passed to the application. 
//-------------------------------------------------------------
char szContent[] = "A Razzle-Dazzle \n"
                        "Signed Message";        // The data
char* pszContent = szContent;                    // A string pointer
BYTE* pbContent = (BYTE*) pszContent;            // A byte pointer
DWORD cbContent = sizeof(szContent);             // Size of message

AfxMessageBox(pszContent);    // Display original message

//-------------------------------------------------------------
// Get a handle to a cryptographic provider. 
//-------------------------------------------------------------
HCRYPTPROV hCryptProv = NULL;         // Handle returned here
BOOL fReturn = FALSE;

fReturn = CryptAcquireContext(
              &hCryptProv,       // Address for handle to be returned
              NULL,              // Use the current user's logon name
              NULL,              // Use the default provider
              PROV_RSA_FULL,     // Specifies the provider type
              0);                // Zero allows access to private keys
if(!fReturn)
{
    AfxMessageBox("CryptAcquireContext failed");
    return;
}

// If the function succeeded, the handle to the cryptographic
// provider resides at hCryptProv.

//-------------------------------------------------------------
// Open the system certificate store.
//-------------------------------------------------------------
HCERTSTORE        hStoreHandle = NULL;

// Call CertOpenSystemStore to open the store.
hStoreHandle = CertOpenSystemStore(hCryptProv, "MY");
if (!hStoreHandle)
{
    AfxMessageBox( "Error Getting Store Handle");
    return;
}

// If the call was successful, the cert store handle now resides
// at the location pointed to by hStoreHandle.

//-------------------------------------------------------------
// Get a pointer to your signature certificate.
//-------------------------------------------------------------
PCCERT_CONTEXT    pSignerCert = NULL;

// For the implementation of GetMySignerCert(), see the function
// at the end of the example code in the "Signed Data" section 
// of this chapter.
pSignerCert = GetMySignerCert(hStoreHandle);
if(!pSignerCert)
{
    AfxMessageBox( "Error Getting Signer Cert");
    return;
}

//-------------------------------------------------------------
// Initialize the Algorithm Identifier struct.
//-------------------------------------------------------------
DWORD                        HashAlgSize;
CRYPT_ALGORITHM_IDENTIFIER    HashAlgorithm;
HashAlgSize = sizeof(HashAlgorithm);
memset(&HashAlgorithm, 0, HashAlgSize);     // Init. to zero.
HashAlgorithm.pszObjId = szOID_RSA_MD5;     // Then set the 
                                            //   necessary field.

//-------------------------------------------------------------
// Initialize the CMSG_SIGNER_ENCODE_INFO structure.
//-------------------------------------------------------------
CMSG_SIGNER_ENCODE_INFO    SignerEncodeInfo;

memset(&SignerEncodeInfo, 0, sizeof(CMSG_SIGNER_ENCODE_INFO));
SignerEncodeInfo.cbSize = sizeof(CMSG_SIGNER_ENCODE_INFO);
SignerEncodeInfo.pCertInfo = pSignerCert->pCertInfo;
SignerEncodeInfo.hCryptProv = hCryptProv;
SignerEncodeInfo.dwKeySpec = AT_SIGNATURE;
SignerEncodeInfo.HashAlgorithm = HashAlgorithm;
SignerEncodeInfo.pvHashAuxInfo = NULL;

// Create an array of one. NOTE: Currently, there can be only one
// signer.
CMSG_SIGNER_ENCODE_INFO SignerEncodeInfoArray[1];
SignerEncodeInfoArray[0] = SignerEncodeInfo;

//-------------------------------------------------------------
// Initialize the CMSG_SIGNED_ENCODE_INFO structure.
//-------------------------------------------------------------
CERT_BLOB    SignerCertBlob;

SignerCertBlob.cbData = pSignerCert->cbCertEncoded;
SignerCertBlob.pbData = pSignerCert->pbCertEncoded;

// Create an array of one. Only one certificate is included.
CERT_BLOB    SignerCertBlobArray[1];
SignerCertBlobArray[0] = SignerCertBlob;

CMSG_SIGNED_ENCODE_INFO SignedMsgEncodeInfo;

memset(&SignedMsgEncodeInfo, 0, sizeof(CMSG_SIGNED_ENCODE_INFO));
SignedMsgEncodeInfo.cbSize = sizeof(CMSG_SIGNED_ENCODE_INFO);
SignedMsgEncodeInfo.cSigners = 1;
SignedMsgEncodeInfo.rgSigners = SignerEncodeInfoArray;
SignedMsgEncodeInfo.cCertEncoded = 1;
SignedMsgEncodeInfo.rgCertEncoded = SignerCertBlobArray;
SignedMsgEncodeInfo.rgCrlEncoded = NULL;

//-------------------------------------------------------------
// Get the size of the encoded message blob.
//-------------------------------------------------------------
DWORD        cbSignedBlob;
BYTE        *pbSignedBlob = NULL;

    cbSignedBlob = CryptMsgCalculateEncodedLength(
                        MY_ENCODING_TYPE,       // Msg encoding type
                        0,                      // Flags
                        CMSG_SIGNED,            // Msg type
                        &SignedMsgEncodeInfo,   // Pointer to
                                                //   structure
                        NULL,                   // Inner content ObjID
                        cbContent);             // Size of content
if(0 == cbSignedBlob)
{
    AfxMessageBox("Getting cbSignedBlob length failed");
    return;
}

//-------------------------------------------------------------
// Allocate memory for the encoded blob.
//-------------------------------------------------------------
pbSignedBlob = (BYTE *) malloc(cbSignedBlob);
if(NULL == pbSignedBlob)
{
    AfxMessageBox("Malloc failed");
    return;
}

//-------------------------------------------------------------
// Open a message to encode.
//-------------------------------------------------------------
HCRYPTMSG    hMsg = NULL;

hMsg = CryptMsgOpenToEncode(
            MY_ENCODING_TYPE,        // Encoding type
            0,                       // Flags
            CMSG_SIGNED,             // Msg type
            &SignedMsgEncodeInfo,    // Pointer to structure
            NULL,                    // Inner content ObjID
            NULL);                   // Stream Info (not used)
if(NULL == hMsg)
{
    AfxMessageBox("OpenToEncode Envelope failed");
    free(pbSignedBlob);
    return;
}

//-------------------------------------------------------------
// Update the message with the data.
//-------------------------------------------------------------
BOOL fResult;

fResult = CryptMsgUpdate(
               hMsg,            // Handle to the message
               pbContent,       // Pointer to the unsigned content
               cbContent,       // Size of the unsigned content
               TRUE);           // Last call
if(!fResult)
{
    AfxMessageBox("Encode Enveloped MsgUpdate failed");
    free(pbSignedBlob);
    return;
}

//-------------------------------------------------------------
// Get the resultant message.
//-------------------------------------------------------------
fResult = CryptMsgGetParam(
               hMsg,                       // Handle to the message
               CMSG_BARE_CONTENT_PARAM,    // Parameter type
               0,                          // Index
               pbSignedBlob,               // Pointer to signed
                                           //   data blob
               &cbSignedBlob);             // Size of the blob
if(!fResult)
{
    AfxMessageBox("MsgGetParam failed");
    free(pbSignedBlob);
    CryptMsgClose(hMsg);
    return;
}else
    AfxMessageBox("Signed message encoded sucessfully");

// If the call was successful, pbEncodedBlob now points to the
// encoded, signed content.

CertCloseStore(hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG);
CryptMsgClose(hMsg);

//=============================================================
// EXAMPLE CODE FOR ENVELOPING A SIGNED MESSAGE.
//=============================================================

//-------------------------------------------------------------
// Open the system certificate store.
//-------------------------------------------------------------

// Call CertOpenSystemStore to open the store.
hStoreHandle = CertOpenSystemStore(hCryptProv, "Friend");
if (!hStoreHandle)
{
    AfxMessageBox( "Error Getting Store Handle");
    return;
}

// If the call was successful, the cert store handle now resides
// at the location pointed to by hStoreHandle.

//-------------------------------------------------------------
// Get a pointer to the recipient certificate.
//-------------------------------------------------------------
PCCERT_CONTEXT    pRecipCert = NULL;
LPSTR             pszRecipientName = "James Allard";

// For the implementation of GetRecipientCert(), see the function
// at the end of the example code in the "Enveloped Message Example
// 2" section of this chapter.
pRecipCert = GetRecipientCert(hStoreHandle, pszRecipientName);
if(!pRecipCert)
{
    AfxMessageBox( "Error Getting Recipient Cert");
    return;
}

// Create an array of CERT_INFOs. In this example there is only a 
// single recipient.
PCERT_INFO        RecipCertArray[1];
RecipCertArray[0] = pRecipCert->pCertInfo;

//-------------------------------------------------------------
// Initialize the symmetric encryption Algorithm Identifier
// structure.
//-------------------------------------------------------------
DWORD                         ContentEncryptAlgSize;
CRYPT_ALGORITHM_IDENTIFIER    ContentEncryptAlgorithm;
ContentEncryptAlgSize = sizeof(ContentEncryptAlgorithm);
memset(&ContentEncryptAlgorithm, 0, 
                        ContentEncryptAlgSize); // Init. to zero.

// Set the necessary fields. This particular OID doesn't
// need any parameters. Some OIDs, however will need the
// parameter's member to be initialized.
ContentEncryptAlgorithm.pszObjId = szOID_RSA_RC4;    

//-------------------------------------------------------------
// Initialize the CMSG_ENVELOPED_ENCODE_INFO structure.
//-------------------------------------------------------------
CMSG_ENVELOPED_ENCODE_INFO    EnvelopedEncodeInfo;

memset(&EnvelopedEncodeInfo, 0, 
                        sizeof(CMSG_ENVELOPED_ENCODE_INFO));
EnvelopedEncodeInfo.cbSize = sizeof(CMSG_ENVELOPED_ENCODE_INFO);
EnvelopedEncodeInfo.hCryptProv = hCryptProv;
EnvelopedEncodeInfo.ContentEncryptionAlgorithm = 
                                        ContentEncryptAlgorithm;
EnvelopedEncodeInfo.pvEncryptionAuxInfo = NULL;
EnvelopedEncodeInfo.cRecipients = 1;
EnvelopedEncodeInfo.rgpRecipients = RecipCertArray;

//-------------------------------------------------------------
// Get the size of the encoded message blob.
//-------------------------------------------------------------
DWORD        cbEncodedBlob;
BYTE        *pbEncodedBlob = NULL;

cbEncodedBlob = CryptMsgCalculateEncodedLength(
                     MY_ENCODING_TYPE,        // Msg encoding type
                     0,                       // Flags
                     CMSG_ENVELOPED,          // Msg type
                     &EnvelopedEncodeInfo,    // Ptr. to struct.
                     szOID_RSA_signedData,    // Inner content ObjID
                     cbSignedBlob);           // size of content
if(0 == cbEncodedBlob)
{
    AfxMessageBox("Getting Enveloped cbEncodedBlob length failed");
    return;
}

//-------------------------------------------------------------
// Allocate memory for the encoded blob.
//-------------------------------------------------------------
pbEncodedBlob = (BYTE *) malloc(cbEncodedBlob);
if(NULL == pbEncodedBlob)
{
    AfxMessageBox("Enveloped Malloc failed");
    return;
}

//-------------------------------------------------------------
// Open a message to encode.
//-------------------------------------------------------------

hMsg = CryptMsgOpenToEncode(
            MY_ENCODING_TYPE,        // Encoding type
            0,                       // Flags
            CMSG_ENVELOPED,          // Msg type
            &EnvelopedEncodeInfo,    // Pointer to structure
            szOID_RSA_signedData,    // Inner content ObjID
            NULL);                   // Stream Info (not used)
if(NULL == hMsg)
{
    AfxMessageBox("Enveloped OpenToEncode failed");
    free(pbEncodedBlob);
    return;
}

//-------------------------------------------------------------
// Update the message with the data.
//-------------------------------------------------------------

fResult = CryptMsgUpdate(
               hMsg,              // Handle to the message
               pbSignedBlob,      // Pointer to the signed data blob
               cbSignedBlob,      // Size of the data blob
               TRUE);             // Last call
if(!fResult)
{
    AfxMessageBox("Enveloped MsgUpdate failed");
    free(pbEncodedBlob);
    return;
}

//-------------------------------------------------------------
// Get the resultant message.
//-------------------------------------------------------------
fResult = CryptMsgGetParam(
               hMsg,                  // Handle to the message
               CMSG_CONTENT_PARAM,    // Parameter type
               0,                     // Index
               pbEncodedBlob,         // Pointer to the enveloped,
                                      //   signed data blob
               &cbEncodedBlob);       // Size of the blob
if(!fResult)
{
    AfxMessageBox("Enveloped MsgGetParam failed");
    free(pbEncodedBlob);
    return;
}else
    AfxMessageBox("Enveloped message encoded sucessfully");

// If the call was successful, pbEncodedBlob now points to the
// encoded, enveloped, signed content.

BOOL fForceFlag = 0;
BOOL fAllCertsClosed = 1;
// If CERT_CLOSE_STORE_FORCE_FLAG is used with CertCloseStore,
// all open certificate contexts are closed and freed, and
// the store is closed. In some cases, such as multi-
// threaded programs, this may not be desirable. If 
// CERT_CLOSE_STORE_CHECK_FLAG is used instead, the store will
// close but will warn you if all of the opened or duplicated
// certificate contexts have not been closed. Use
// CertFreeCertificateContext to close them when appropriate (as
// demonstrated in the "else" section of the following code).
if(fForceFlag)
{
    CertCloseStore(hStoreHandle, CERT_CLOSE_STORE_FORCE_FLAG);
    CryptMsgClose(hMsg);
}
else
{
    CertFreeCertificateContext(pRecipCert);
    fAllCertsClosed = CertCloseStore(hStoreHandle,
                                CERT_CLOSE_STORE_CHECK_FLAG);
    if(!fAllCertsClosed)
        AfxMessageBox("Certs are still open");
    CryptMsgClose(hMsg);
}

//=============================================================
// EXAMPLE CODE FOR DECODING AN ENVELOPED MESSAGE
//=============================================================

//-------------------------------------------------------------
// Open a message for decoding.
//-------------------------------------------------------------

hMsg = CryptMsgOpenToDecode(
            MY_ENCODING_TYPE,       // Encoding type
            0,                      // Flags
            0,                      // Message type (get from msg.)
            hCryptProv,             // Cryptographic provider
            NULL,                   // Recipient info
            NULL);                  // Stream info
if(NULL == hMsg)
{
    AfxMessageBox("OpenToDecode Enveloped message failed");
    free(pbSignedBlob);
    free(pbEncodedBlob);
    return;
}

//-------------------------------------------------------------
// Update the message with the encoded blob, using the data
// that was encoded in the previous section of code.
//-------------------------------------------------------------
fResult = CryptMsgUpdate(
               hMsg,                 // Handle to the message
               pbEncodedBlob,        // Pointer to the encoded, signed
                                     //   data blob
               cbEncodedBlob,        // Size of the encoded blob
               TRUE);                // Last call
if(!fResult)
{
    AfxMessageBox("Enveloped Decode MsgUpdate failed");
    free(pbSignedBlob);
    free(pbEncodedBlob);
    return;
}

//-------------------------------------------------------------
// Get the message type.
//-------------------------------------------------------------
DWORD cbData = sizeof(DWORD);
DWORD dwMsgType = 0;

fResult = CryptMsgGetParam(
               hMsg,               // Handle to the message
               CMSG_TYPE_PARAM,    // Parameter type
               0,                  // Index
               &dwMsgType,         // Address for returned info
               &cbData);           // Size of the returned info
if(!fResult)
{
    AfxMessageBox("Enveloped Decode CMSG_TYPE_PARAM failed");
    free(pbSignedBlob);
    free(pbEncodedBlob);
    return;
}

// Some applications may need to use a "switch" statement here
// and process the message differently, depending on the
// message type.
if(dwMsgType != CMSG_ENVELOPED)
{
    AfxMessageBox("Wrong message type");
    free(pbEncodedBlob);
    return;
}

//-------------------------------------------------------------
// Get the size of inner content type BYTE string. If there is
// prior knowledge of inner data type, the next two function
// calls and the tests for the inner content type can be
// eliminated, and the decoding for that type of inner content
// can be implemented directly.
//-------------------------------------------------------------
DWORD   cbInnerContentObjId = sizeof(DWORD);

fResult = CryptMsgGetParam(
           hMsg,                          // Handle to the message
           CMSG_INNER_CONTENT_TYPE_PARAM, // Parameter type
           0,                             // Index
           NULL,                          // Address for returned info
           &cbInnerContentObjId);         // Size of the returned info
if(!fResult)
{
    AfxMessageBox("Decode CMSG_INNER_CONTENT_TYPE_PARAM failed");
    free(pbSignedBlob);
    free(pbEncodedBlob);
    return;
}

//-------------------------------------------------------------
// Allocate memory for the string.
//-------------------------------------------------------------
PBYTE   pbInnerContentObjId = NULL;

pbInnerContentObjId = (PBYTE) malloc(cbInnerContentObjId);
if(NULL == pbInnerContentObjId)
{
    AfxMessageBox("Decode inner content malloc failed");
    free(pbSignedBlob);
    free(pbEncodedBlob);
    return;
}

//-------------------------------------------------------------
// Get the inner content type.
//-------------------------------------------------------------
fResult = CryptMsgGetParam(
           hMsg,                          // Handle to the message
           CMSG_INNER_CONTENT_TYPE_PARAM, // Parameter type
           0,                             // Index
           pbInnerContentObjId,           // Address for returned info
           &cbInnerContentObjId);         // Size of the returned info
if(!fResult)
{
    AfxMessageBox("Decode CMSG_INNER_CONTENT_TYPE_PARAM #2 failed");
    free(pbSignedBlob);
    free(pbEncodedBlob);
    free(pbInnerContentObjId);
    return;
}

//-------------------------------------------------------------
// Process according to the inner content type.
//-------------------------------------------------------------
LPSTR    pszInnerContentObjId = (LPSTR) pbInnerContentObjId;

// Test for the "data" data type.
if(!strcmp(pszInnerContentObjId, szOID_RSA_data))
{
    // Decode the "data" data type here.
    AfxMessageBox("Data data type");
    free(pbEncodedBlob);
    free(pbInnerContentObjId);
    return;

}
// Test for the "signed" data type.
else if(!strcmp(pszInnerContentObjId, szOID_RSA_signedData))
{
    // Decode the signed data type here.
    AfxMessageBox("Signed data type");
    free(pbEncodedBlob);
    free(pbInnerContentObjId);
    return;
}
// Test for the "enveloped" data type.
else if(!strcmp(pszInnerContentObjId, szOID_RSA_envelopedData))
{
    // Decode the enveloped data type here.
    AfxMessageBox("Enveloped data type");
    free(pbEncodedBlob);
    free(pbInnerContentObjId);
    return;
}
// Test for the "hashed" data type.
else if(!strcmp(pszInnerContentObjId, szOID_RSA_digestedData))
{
    // Decode the hashed data type here.
    AfxMessageBox("Hashed data type");
    free(pbEncodedBlob);
    free(pbInnerContentObjId);
    return;
}

//-------------------------------------------------------------
// Clean up.
//-------------------------------------------------------------
free(pbSignedBlob);
free(pbEncodedBlob);
free(pbInnerContentObjId);
CryptMsgClose(hMsg);

}