Creating encrypted messages

The following code sample demonstrate creation of an encrypted CMS message using PKIFv2

Supported Languages

C++

void CreatingEncryptedMessages()
{
      //Create an encrypted content object to hold the data to encrypt
      CPKIFEncryptedContentInfoPtr encContent(new CPKIFEncryptedContentInfo);
      encContent->SetContent(CPKIFBufferPtr(new CPKIFBuffer((unsigned char*)g_buf, g_bufSize))); 

      //Create a mediator object and pass it to a CPKIFEnvelopedData object
      //via the AddMediator function.
      IPKIFMediatorPtr mediator = MakeDefaultMediator();
      CPKIFEnvelopedData envelopedData;
      envelopedData.AddMediator(mediator); 

      //Give the data to encrypt to the enveloped data object.
      envelopedData.SetDataToEncrypt(encContent); 

      IPKIFDefaultKeyManagement* cDKM = envelopedData.GetMediator()->GetMediator<IPKIFDefaultKeyManagement>();
      IPKIFCryptoKeyIDOperations* iKIDO = mediator->GetMediator<IPKIFCryptoKeyIDOperations>();
      CPKIFCredentialList creds;
      std::bitset<9> ku = DataEncipherment;
      iKIDO->GetKeyList(creds, &ku);

      bool addAnother = false;
      int count = 0;
      do
      {
            cout << "The following " << creds.size() << " credentials are available for signature generation purposes" << endl;
            CPKIFCredentialList::iterator pos = creds.begin();
            CPKIFCredentialList::iterator end = creds.end();
            for(int slot = 0; pos != end; ++pos)
            {
                  cout << slot++ << ": Name - " << (*pos)->Name() << "  ID: " << (*pos)->ID() << endl;
            } 

            int selection = -1;
            do
            {
                  cout << "Enter the number corresponding to the credential with which you would like to sign: ";
                  cin >> selection;
                  if(selection > creds.size())
                        cout << "ERROR: invalid selection" << endl;
                  else
                  {
                        //Add selected credential as a recipient. Pass PVS_NOT_VALIDATED or PVS_BASIC_CHECKS_PASSED
                        //when path validation less than complete w/rev status check is acceptable.
                        envelopedData.AddRecipient(creds[selection]->GetCertificate(), PVS_NOT_VALIDATED);
                        count++;
                        //Set the first selected key as default for this mediator for decryption purposes.
                        if(0 == count)
                              cDKM->SetDefaultKey(creds[selection]->ID(), DECRYPTION); 

                        break;
                  }
            }while(1); 

            addAnother = SolicitBool("Would you like to add another recipient");
      }while(addAnother);
 

      //Add a colleague that targets the current MY store to permit encryption using personal
      //certificates instead of or in addition to certificates for other people.
      CPKIFCAPIUserRepository2Ptr personalStore(new CPKIFCAPIUserRepository2(CERT_SYSTEM_STORE_CURRENT_USER, "MY"));
      CPKIFCacheMediator2 * i = envelopedData.GetMediator()->GetMediator<CPKIFCacheMediator2>();
            if(i)
                  i->AddColleague(dynamic_pointer_cast<IPKIFColleague, CPKIFCAPIUserRepository2>(personalStore));     

      try
      {
            //Generate the encrypted message
            CPKIFBufferPtr tmp = envelopedData.Encode(); 

            //Wrap the encrypted message in a ContentInfo and store the
            //encoded result in the global g_envelopedDataBuffer for
            //use in the DecryptingEncryptdMessages function.
            CPKIFContentInfo contentInfo;
            contentInfo.SetContentType(g_envelopedData);
            contentInfo.SetContent(tmp);           

            g_envelopedDataBuffer = contentInfo.Encode();
      }
      catch(CPKIFException& e)
      {
            cout << "Unexpected exception thrown by CreatingEncryptedMessages: ";
            cout << e.print()->c_str() << endl;
            return;

      }
}

 

C#

public void CreatingEncryptedMessages()
{
    //Create an encrypted content object to hold the data to encrypt
    CPKIFEncryptedContentInfoPtr encContent = pkif_module.make_CPKIFEncryptedContentInfoPtr();
    encContent.SetContent(pkif_module.StringToBuffer(g_buf)); 

    //Create a mediator object and pass it to a CPKIFEnvelopedData object
    //via the AddMediator function.
    IPKIFColleaguePtr mediator = pkif_module.MakeDefaultMediator();
    CPKIFEnvelopedData envelopedData = new CPKIFEnvelopedData();
    envelopedData.AddMediator(mediator); 

    //Give the data to encrypt to the enveloped data object.
    envelopedData.SetDataToEncrypt(encContent); 

    IPKIFDefaultKeyManagement cDKM = pkif_module.Get_IPKIFDefaultKeyManagement(mediator);
    IPKIFCryptoKeyIDOperations iKIDO = pkif_module.Get_IPKIFCryptoKeyIDOperations(mediator);
    CPKIFCredentialList creds = new CPKIFCredentialList();
    CPKIFKeyUsagePtr keyUsage = pkif_module.make_CPKIFKeyUsagePtr();
    keyUsage.SetDataEncipherment();
    iKIDO.GetKeyList(creds, keyUsage); 

    bool addAnother = false;
    int count = 0;
    do
    {
        Console.WriteLine("The following " + creds.Count + " credentials are available for signature generation purposes"); 

        for (int ii = 0; ii < creds.Count; ii++)
        {
            Console.WriteLine(ii+ ": Name - " + creds[ii].Name() + "  ID: " + creds[ii].ID());
        } 

        int selection = -1;
        do
        {
            Console.Write("Enter the number corresponding to the credential with which you would like to sign: ");
            string selectionStr = Console.ReadLine();
            selection = Convert.ToInt32(selectionStr);
            if (selection > creds.Count)
                Console.WriteLine("ERROR: invalid selection");
            else
            {
                //Add selected credential as a recipient. Pass PVS_NOT_VALIDATED or PVS_BASIC_CHECKS_PASSED
                //when path validation less than complete w/rev status check is acceptable.
                envelopedData.AddRecipient(creds[selection].GetCertificate(), CMSPathValidationStatus.PVS_NOT_VALIDATED);
                count++;

                //Set the first selected key as default for this mediator for decryption purposes.
                if (0 == count)
                    cDKM.SetDefaultKey(creds[selection].ID(), DefaultKeyType.DECRYPTION);
                break;
            }
        } while (true); 

        addAnother = SolicitBool("Would you like to add another recipient");
    } while (addAnother); 

    try
    {
        //Generate the encrypted message
        CPKIFBufferPtr tmp = envelopedData.Encode();
 

        //Wrap the encrypted message in a ContentInfo and store the
        //encoded result in the global g_envelopedDataBuffer for
        //use in the DecryptingEncryptdMessages function.
        CPKIFContentInfo contentInfo = new CPKIFContentInfo();
        contentInfo.SetContentType(pkif_module.g_envelopedData);
        contentInfo.SetContent(tmp); 

        g_envelopedDataBuffer = contentInfo.Encode();
    }
    catch (Exception e)
    {

        Console.WriteLine("Unexpected exception thrown by CreatingEncryptedMessages: ");
        Console.WriteLine(e.Message);

        return;
    }
 }

JAVA

public void CreatingEncryptedMessages()
{
   
//Create an encrypted content object to hold the data to encrypt
    CPKIFEncryptedContentInfoPtr encContent = pkif_module.make_CPKIFEncryptedContentInfoPtr();
    encContent.SetContent(pkif_module.StringToBuffer(
g_buf)); 

    //Create a mediator object and pass it to a CPKIFEnvelopedData object
    //via the AddMediator function.
    IPKIFColleaguePtr mediator = pkif_module.MakeDefaultMediator();
    CPKIFEnvelopedData envelopedData =
new CPKIFEnvelopedData();
    envelopedData.AddMediator(mediator);
 

    //Give the data to encrypt to the enveloped data object.
    envelopedData.SetDataToEncrypt(encContent);

    IPKIFDefaultKeyManagement cDKM = pkif_module.Get_IPKIFDefaultKeyManagement(mediator); 
    IPKIFCryptoKeyIDOperations iKIDO = pkif_module.Get_IPKIFCryptoKeyIDOperations(mediator);
    CPKIFCredentialList creds =
new CPKIFCredentialList();
    CPKIFKeyUsagePtr keyUsage = pkif_module.make_CPKIFKeyUsagePtr();
    keyUsage.SetDataEncipherment();
    iKIDO.GetKeyList(creds, keyUsage);
 

    boolean addAnother = false;
   
int count = 0;
   
do
    {
        System.
out.println("The following " + creds.size() + " credentials are available for signature generation purposes"); 

        for (int ii = 0; ii < creds.size(); ii++)
        {
            System.
out.println(ii+ ": Name - " + creds.get(ii).Name() + "  ID: " + creds.get(ii).ID());
        }
 

        int selection = -1;
       
do
        {
            System.
out.print("Enter the number corresponding to the credential with which you would like to sign: ");
            BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
            String selectionStr =
"";
           
try
            {
                  selectionStr = in.readLine();

            }catch(IOException e)
            {

                  System.out.println("Error reading user input");
                 
try
                {
                  in.close();                 

                }catch(IOException k)
                {
                  System.
out.println("Error closing BufferedReader");
                }
            }
            selection = Integer.parseInt(selectionStr);
           
if (selection > creds.size())
                System.
out.println("ERROR: invalid selection");
           
else
            {
               
//Add selected credential as a recipient. Pass PVS_NOT_VALIDATED or PVS_BASIC_CHECKS_PASSED
                //when path validation less than complete w/rev status check is acceptable.
                envelopedData.AddRecipient(creds.get(selection).GetCertificate(), CMSPathValidationStatus.PVS_NOT_VALIDATED);
                count++;
               
//Set the first selected key as default for this mediator for decryption purposes.
                if (0 == count)
                    cDKM.SetDefaultKey(creds.get(selection).ID(), DefaultKeyType.
DECRYPTION); 

                break;
            }
        }
while (true); 

        addAnother = SolicitBool("Would you like to add another recipient");
    }
while (addAnother); 

    try
    {
       
//Generate the encrypted message
        CPKIFBufferPtr tmp = envelopedData.Encode(); 

        //Wrap the encrypted message in a ContentInfo and store the
        //encoded result in the global g_envelopedDataBuffer for
        //use in the DecryptingEncryptdMessages function.
        CPKIFContentInfo contentInfo = new CPKIFContentInfo();
        contentInfo.SetContentType(pkif_module.getG_envelopedData());
        contentInfo.SetContent(tmp);
 

        g_envelopedDataBuffer = contentInfo.Encode();
    }
   
catch (Exception e)
    {
        System.
out.println("Unexpected exception thrown by CreatingEncryptedMessages: ");
        System.
out.println(e.getMessage()); 

        return;
    }
}