How to: Envelope a Message for One Recipient

[Note: This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

This example creates a CMS/PKCS #7 enveloped message by using System.Security.Cryptography.Pkcs. The message is encrypted for a single recipient. The message is then decrypted using that recipient's private key. The example uses the EnvelopedCms object, which allows messages to be encrypted for one or more recipients, or enveloped.

This example uses the following classes:

To run on a single computer, the following example requires that a public key certificate with the subject name "Recipient1" be contained in both the AddressBook and My certificate stores. It also requires that the associated private key be stored on that computer. This example first acts as the message sender, and then as the message recipient, by using the same public key credentials in each role. As the sender, it searches the AddressBook certificate store for the recipient's certificate, and uses that certificate to encrypt the message. As the recipient, it searches the My certificate store for the certificate, and uses the associated private key to decrypt the message.


This example is only for illustrative purposes. Production environments might use a different model in which the sender and the recipient of the message execute in different processes with their unique public key credentials.

Set up this example by using the Makecert.exe utility, one of several ways to do so. Certificate Creation Tool (Makecert.exe) is a convenient utility for generating test certificates. In a production environment, certificates are generated by a certification authority.

The following Makecert command generates the required public key certificates and private keys.

Makecert -n "CN=Recipient1" -ss My

This command places the appropriate public key certificate in the My certificate store and generates the private key. At this point, you need to get a copy of the public key certificate into the AddressBook certificate store. To do so, export the public key certificate, and then import it into the AddressBook certificate store by following the procedure in How to: Export and Import a Public Key Certificate.

// Copyright (c) Microsoft Corporation.  All rights reserved.
#region Using directives

using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;


namespace EnvelopAMessageForOneRecipient
    class EnvelopedCmsSingleRecipient
        const String recipientName = "Recipient1";

        static void Main(string[] args)
            Console.WriteLine("System.Security.Cryptography.Pkcs " +
            "Sample: Single-recipient encrypted and decrypted message");

            //  Original message.
            const String msg = "Here is your personal identification number:";

            Console.WriteLine("\nOriginal message (len {0}): {1}  ",
                              msg.Length, msg);

            //  Convert message to an array of Unicode bytes for signing.
            UnicodeEncoding unicode = new UnicodeEncoding();
            byte[] msgBytes = unicode.GetBytes(msg);

            Console.WriteLine("     SETUP OF CREDENTIALS     ");

            //  The recipient's certificate is necessary to encrypt
            //  the message for that recipient.
            X509Certificate2 recipientCert = GetRecipientCert();

            Console.WriteLine("     SENDER SIDE      ");

            byte[] encodedEnvelopedCms = EncryptMsg(msgBytes,

            Console.Write("\nMessage after encryption (len {0}):  ",
            foreach (byte b in encodedEnvelopedCms)
                Console.Write("{0:x}", b);

            Console.WriteLine("     RECIPIENT SIDE     ");

            Byte[] decryptedMsg = DecryptMsg(encodedEnvelopedCms);

            //  Convert Unicode bytes to the original message string.
            Console.WriteLine("\nDecrypted Message: {0}",

        //  Open the AddressBook (also known as Other in 
        //  Internet Explorer) certificate store and search for 
        //  a recipient certificate with which to encrypt the 
        //  message. The certificate must have a subject name 
        //  of "Recipient1".
        static public X509Certificate2 GetRecipientCert()
            //  Open the AddressBook local user X509 certificate store.
            X509Store storeAddressBook = new X509Store(StoreName.
                AddressBook, StoreLocation.CurrentUser);

            //  Display certificates to help troubleshoot 
            //  the example's setup.
                "Found certs with the following subject names in the " +
                "{0} store:", storeAddressBook.Name);
            foreach (X509Certificate2 cert in storeAddressBook.Certificates)
                Console.WriteLine("\t{0}", cert.SubjectName.Name);

            //  Get recipient certificate.
            //  For purposes of this sample, do not validate the
            //  certificate. Note that in a production environment,
            //  validating the certificate will probably be necessary.
            X509Certificate2Collection certColl = storeAddressBook.
                recipientName, false);
                "Found {0} certificates in the {1} store with name {2}",
                certColl.Count, storeAddressBook.Name, recipientName);

            //  Check to see if the certificate suggested by the example
            //  requirements is not present.
            if (certColl.Count == 0)
                    "A suggested certificate to use for this example " +
                    "is not in the certificate store. Select " +
                    "an alternate certificate to use for " +
                    "signing the message.");


            return certColl[0];

        //  Encrypt the message with the public key of
        //  the recipient. This is done by enveloping the message by
        //  using an EnvelopedCms object.
        static public byte[] EncryptMsg(
            Byte[] msg,
            X509Certificate2 recipientCert)
            //  Place the message in a ContentInfo object.
            //  This is required to build an EnvelopedCms object.
            ContentInfo contentInfo = new ContentInfo(msg);

            //  Instantiate an EnvelopedCms object with the ContentInfo
            //  above.
            //  Has default SubjectIdentifierType IssuerAndSerialNumber.
            //  Has default ContentEncryptionAlgorithm property value
            //  RSA_DES_EDE3_CBC.
            EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);

            //  Formulate a CmsRecipient object that
            //  represents information about the recipient 
            //  to encrypt the message for.
            CmsRecipient recip1 = new CmsRecipient(

                "Encrypting data for a single recipient of " +
                "subject name {0} ... ",
            //  Encrypt the message for the recipient.

            //  The encoded EnvelopedCms message contains the message
            //  ciphertext and the information about each recipient 
            //  that the message was enveloped for.
            return envelopedCms.Encode();

        //  Decrypt the encoded EnvelopedCms message.
        static public Byte[] DecryptMsg(byte[] encodedEnvelopedCms)
            //  Prepare object in which to decode and decrypt.
            EnvelopedCms envelopedCms = new EnvelopedCms();

            //  Decode the message.

            //  Display the number of recipients the message is
            //  enveloped for; it should be 1 for this example.
            DisplayEnvelopedCms(envelopedCms, false);

            //  Decrypt the message for the single recipient.
            Console.Write("Decrypting Data ... ");

            //  The decrypted message occupies the ContentInfo property
            //  after the Decrypt method is invoked.
            return envelopedCms.ContentInfo.Content;

        //  Display the ContentInfo property of an EnvelopedCms object.
        static private void DisplayEnvelopedCmsContent(String desc,
            EnvelopedCms envelopedCms)
            Console.WriteLine(desc + " (length {0}):  ",
            foreach (byte b in envelopedCms.ContentInfo.Content)
                Console.Write(b.ToString() + " ");

        //  Display some properties of an EnvelopedCms object.
        static private void DisplayEnvelopedCms(EnvelopedCms e,
            Boolean displayContent)
            Console.WriteLine("\nEnveloped CMS/PKCS #7 Message " +
                "\tThe number of recipients for the Enveloped CMS/PKCS " +
                "#7 is: {0}", e.RecipientInfos.Count);
            for (int i = 0; i < e.RecipientInfos.Count; i++)
                    "\tRecipient #{0} has type {1}.",
                    i + 1,
            if (displayContent)
                DisplayEnvelopedCmsContent("Enveloped CMS/PKCS " +
                    "#7 Content", e);