private static KeyTransRecipientInfo EncodeKeyTransl_Rsa2048(RSAEncryptionPadding encryptionPadding, SubjectIdentifierType type = SubjectIdentifierType.IssuerAndSerialNumber)
        {
            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RSA2048Sha256KeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient;
                if (encryptionPadding is null)
                {
                    cmsRecipient = new CmsRecipient(type, cert);
                }
                else
                {
                    cmsRecipient = new CmsRecipient(type, cert, encryptionPadding);
                }

                ecms.Encrypt(cmsRecipient);
            }
            byte[] encodedMessage = ecms.Encode();

            EnvelopedCms ecms2 = new EnvelopedCms();

            ecms2.Decode(encodedMessage);

            RecipientInfoCollection recipients = ecms2.RecipientInfos;

            Assert.Equal(1, recipients.Count);
            RecipientInfo recipientInfo = recipients[0];

            Assert.IsType <KeyTransRecipientInfo>(recipientInfo);
            return((KeyTransRecipientInfo)recipientInfo);
        }
Example #2
0
        public static void ReuseEnvelopeCmsEncodeThenDecode()
        {
            // Test ability to encrypt, encode and decode all in one EnvelopedCms instance.

            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(cert);
                ecms.Encrypt(cmsRecipient);
            }

            byte[] encodedMessage = ecms.Encode();
            ecms.Decode(encodedMessage);

            RecipientInfoCollection recipients = ecms.RecipientInfos;

            Assert.Equal(1, recipients.Count);
            RecipientInfo         recipientInfo = recipients[0];
            KeyTransRecipientInfo recipient     = recipientInfo as KeyTransRecipientInfo;

            Assert.NotNull(recipientInfo);

            SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
            object            value             = subjectIdentifier.Value;

            Assert.True(value is X509IssuerSerial);
            X509IssuerSerial xis = (X509IssuerSerial)value;

            Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName);
            Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber);
        }
Example #3
0
        private static void TestSimpleDecrypt_RoundTrip(CertLoader certLoader, ContentInfo contentInfo, string algorithmOidValue, SubjectIdentifierType type, ContentInfo expectedContentInfo = null)
        {
            // Deep-copy the contentInfo since the real ContentInfo doesn't do this. This defends against a bad implementation changing
            // our "expectedContentInfo" to match what it produces.
            expectedContentInfo = expectedContentInfo ?? new ContentInfo(new Oid(contentInfo.ContentType), (byte[])(contentInfo.Content.Clone()));

            string certSubjectName;

            byte[] encodedMessage;
            byte[] originalCopy = (byte[])(contentInfo.Content.Clone());
            using (X509Certificate2 certificate = certLoader.GetCertificate())
            {
                certSubjectName = certificate.Subject;
                AlgorithmIdentifier alg          = new AlgorithmIdentifier(new Oid(algorithmOidValue));
                EnvelopedCms        ecms         = new EnvelopedCms(contentInfo, alg);
                CmsRecipient        cmsRecipient = new CmsRecipient(type, certificate);
                ecms.Encrypt(cmsRecipient);
                Assert.Equal(originalCopy.ByteArrayToHex(), ecms.ContentInfo.Content.ByteArrayToHex());
                encodedMessage = ecms.Encode();
            }

            // We don't pass "certificate" down because it's expected that the certificate used for encrypting doesn't have a private key (part of the purpose of this test is
            // to ensure that you don't need the recipient's private key to encrypt.) The decrypt phase will have to locate the matching cert with the private key.
            VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
        }
Example #4
0
        public static void CmsRecipientPassNullCertificate()
        {
            object ignore;

            Assert.Throws <ArgumentNullException>(() => ignore = new CmsRecipient(null));
            Assert.Throws <ArgumentNullException>(() => ignore = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, null));
        }
Example #5
0
        public static void RoundTrip_ExplicitSki()
        {
            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 explicitSkiCert = Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate())
            {
                CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, explicitSkiCert);
                ecms.Encrypt(recipient);
            }

            byte[] encodedMessage = ecms.Encode();

            ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);

            using (X509Certificate2 privateCert = Certificates.RSAKeyTransfer_ExplicitSki.TryGetCertificateWithPrivateKey())
            {
                if (privateCert == null)
                {
                    return; // CertLoader can't load the private certificate.
                }
                ecms.Decrypt(new X509Certificate2Collection(privateCert));
            }
            Assert.Equal(contentInfo.ContentType.Value, ecms.ContentInfo.ContentType.Value);
            Assert.Equal <byte>(contentInfo.Content, ecms.ContentInfo.Content);
        }
Example #6
0
        private static void Assert_Certificate_Roundtrip(CertLoader certificateLoader)
        {
            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = certificateLoader.GetCertificate())
            {
                CmsRecipient recipient = new CmsRecipient(cert);
                ecms.Encrypt(recipient);
            }

            byte[] encodedMessage = ecms.Encode();

            ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);

            using (X509Certificate2 privateCert = certificateLoader.TryGetCertificateWithPrivateKey())
            {
                if (privateCert == null)
                {
                    return; // CertLoader can't load the private certificate.
                }
                ecms.Decrypt(new X509Certificate2Collection(privateCert));
            }
            Assert.Equal(contentInfo.ContentType.Value, ecms.ContentInfo.ContentType.Value);
            Assert.Equal <byte>(contentInfo.Content, ecms.ContentInfo.Content);
        }
        public static void Oneary()
        {
            CmsRecipient           a0 = s_cr0;
            CmsRecipientCollection c  = new CmsRecipientCollection(a0);

            AssertEquals(c, new CmsRecipient[] { a0 });
        }
Example #8
0
        public static void DecryptUsingCertificateWithSameSubjectKeyIdentifierButDifferentKeyPair()
        {
            using (X509Certificate2 recipientCert = Certificates.RSAKeyTransfer4_ExplicitSki.GetCertificate())
                using (X509Certificate2 otherRecipientWithSameSki = Certificates.RSAKeyTransfer5_ExplicitSkiOfRSAKeyTransfer4.TryGetCertificateWithPrivateKey())
                    using (X509Certificate2 realRecipientCert = Certificates.RSAKeyTransfer4_ExplicitSki.TryGetCertificateWithPrivateKey())
                    {
                        Assert.Equal(recipientCert, realRecipientCert);
                        Assert.NotEqual(recipientCert, otherRecipientWithSameSki);
                        Assert.Equal(GetSubjectKeyIdentifier(recipientCert), GetSubjectKeyIdentifier(otherRecipientWithSameSki));

                        byte[] plainText = new byte[] { 1, 3, 7, 9 };

                        ContentInfo  content = new ContentInfo(plainText);
                        EnvelopedCms ecms    = new EnvelopedCms(content);

                        CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, recipientCert);
                        ecms.Encrypt(recipient);
                        byte[] encoded = ecms.Encode();

                        ecms = new EnvelopedCms();
                        ecms.Decode(encoded);

                        Assert.ThrowsAny <CryptographicException>(() => ecms.Decrypt(new X509Certificate2Collection(otherRecipientWithSameSki)));
                        ecms.Decrypt(new X509Certificate2Collection(realRecipientCert));

                        Assert.Equal(plainText, ecms.ContentInfo.Content);
                    }
        }
        public static void RemoveNonExistent()
        {
            CmsRecipientCollection c  = new CmsRecipientCollection();
            CmsRecipient           a0 = s_cr0;

            c.Remove(a0);  // You can "remove" items that aren't in the collection - this is defined as a NOP.
        }
        public static void CopyExceptions()
        {
            CmsRecipient a0 = s_cr0;
            CmsRecipient a1 = s_cr1;
            CmsRecipient a2 = s_cr2;

            CmsRecipientCollection c = new CmsRecipientCollection();

            c.Add(a0);
            c.Add(a1);
            c.Add(a2);

            CmsRecipient[] a = new CmsRecipient[3];
            Assert.Throws <ArgumentNullException>(() => c.CopyTo(null, 0));
            Assert.Throws <ArgumentOutOfRangeException>(() => c.CopyTo(a, -1));
            Assert.Throws <ArgumentOutOfRangeException>(() => c.CopyTo(a, 3));
            AssertExtensions.Throws <ArgumentException>(null, () => c.CopyTo(a, 1));

            ICollection ic = c;

            Assert.Throws <ArgumentNullException>(() => ic.CopyTo(null, 0));
            Assert.Throws <ArgumentOutOfRangeException>(() => ic.CopyTo(a, -1));
            Assert.Throws <ArgumentOutOfRangeException>(() => ic.CopyTo(a, 3));
            AssertExtensions.Throws <ArgumentException>(null, () => ic.CopyTo(a, 1));
            AssertExtensions.Throws <ArgumentException>(null, () => ic.CopyTo(new CmsRecipient[2, 2], 1));
            Assert.Throws <InvalidCastException>(() => ic.CopyTo(new int[10], 1));

            if (PlatformDetection.IsNonZeroLowerBoundArraySupported)
            {
                // Array has non-zero lower bound
                Array array = Array.CreateInstance(typeof(object), new int[] { 10 }, new int[] { 10 });
                Assert.Throws <IndexOutOfRangeException>(() => ic.CopyTo(array, 0));
            }
        }
        public static void TestKeyTransRecipientIdValue_ExplicitSki_RoundTrip()
        {
            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, cert);
                ecms.Encrypt(cmsRecipient);
            }
            byte[] encodedMessage = ecms.Encode();

            EnvelopedCms ecms2 = new EnvelopedCms();

            ecms2.Decode(encodedMessage);

            RecipientInfoCollection recipients = ecms2.RecipientInfos;

            Assert.Equal(1, recipients.Count);
            RecipientInfo recipientInfo = recipients[0];

            Assert.IsType <KeyTransRecipientInfo>(recipientInfo);
            KeyTransRecipientInfo recipient = (KeyTransRecipientInfo)recipientInfo;

            SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
            object            value             = subjectIdentifier.Value;

            Assert.IsType <string>(value);
            string ski = (string)value;

            Assert.Equal("01952851C55DB594B0C6167F5863C5B6B67AEFE6", ski);
        }
         static void Main (string[] args)
 		{
 			//  Select a binary file
 			var dialog = new OpenFileDialog {
 				Filter = "All files (*.*)|*.*",
 				InitialDirectory = "./",
 				Title = "Select a text file"
 			};
 			var filename = (dialog.ShowDialog () == DialogResult.OK) ? dialog.FileName : null;
             var certificate2 = new X509Certificate2 ("c:/temp1/cert.pfx", "password");
             MimeEntity body;
 
 			using (var content = new MemoryStream (File.ReadAllBytes (filename)))
 			    var part = new MimePart (MimeTypes.GetMimeType (filename)) {
 				    ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
 				    ContentTransferEncoding = ContentEncoding.Binary,
 				    FileName = Path.GetFileName (filename),
 				    Content = new MimeContent (content)
 			    };
 
 			    var recipient = new CmsRecipient (certificate2) {
                     EncryptionAlgorithms = new EncryptionAlgorithm[] { EncryptionAlgorithm.TripleDes }
                 };
                 var recipients = new CmsRecipientCollection ();
 			    recipients.Add (recipient);
 
 			    using (var ctx = new TemporarySecureMimeContext ())
 				    body = ApplicationPkcs7Mime.Encrypt (ctx, recipients, part);
 			}
Example #13
0
            //
            // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
            //
            private static CMSG_RECIPIENT_ENCODE_INFO EncodeRecipientInfo(CmsRecipient recipient, AlgorithmIdentifier contentEncryptionAlgorithm, HeapBlockRetainer hb)
            {
                CMSG_RECIPIENT_ENCODE_INFO recipientEncodeInfo;

                unsafe
                {
                    switch (recipient.Certificate.GetKeyAlgorithm())
                    {
                    case Oids.Rsa:
                    case Oids.RsaOaep:
                        recipientEncodeInfo.dwRecipientChoice       = CMsgCmsRecipientChoice.CMSG_KEY_TRANS_RECIPIENT;
                        recipientEncodeInfo.pCmsRecipientEncodeInfo = (IntPtr)EncodeKeyTransRecipientInfo(recipient, hb);
                        break;

                    case Oids.Esdh:
                    case Oids.DiffieHellman:
                    case Oids.DiffieHellmanPkcs3:
                        recipientEncodeInfo.dwRecipientChoice       = CMsgCmsRecipientChoice.CMSG_KEY_AGREE_RECIPIENT;
                        recipientEncodeInfo.pCmsRecipientEncodeInfo = (IntPtr)EncodeKeyAgreeRecipientInfo(recipient, contentEncryptionAlgorithm, hb);
                        break;

                    default:
                        throw ErrorCode.CRYPT_E_UNKNOWN_ALGO.ToCryptographicException();
                    }
                }
                return(recipientEncodeInfo);
            }
Example #14
0
            //
            // This returns an allocated native memory block. Its lifetime (and that of any allocated subblocks it may point to) is that of "hb".
            //
            private static unsafe CERT_ID EncodeRecipientId(CmsRecipient recipient, SafeCertContextHandle hCertContext, CERT_CONTEXT *pCertContext, CERT_INFO *pCertInfo, HeapBlockRetainer hb)
            {
                CERT_ID recipientId        = default(CERT_ID);
                SubjectIdentifierType type = recipient.RecipientIdentifierType;

                switch (type)
                {
                case SubjectIdentifierType.IssuerAndSerialNumber:
                {
                    recipientId.dwIdChoice = CertIdChoice.CERT_ID_ISSUER_SERIAL_NUMBER;
                    recipientId.u.IssuerSerialNumber.Issuer       = pCertInfo->Issuer;
                    recipientId.u.IssuerSerialNumber.SerialNumber = pCertInfo->SerialNumber;
                    break;
                }

                case SubjectIdentifierType.SubjectKeyIdentifier:
                {
                    byte[] ski  = hCertContext.GetSubjectKeyIdentifer();
                    IntPtr pSki = hb.AllocBytes(ski);

                    recipientId.dwIdChoice     = CertIdChoice.CERT_ID_KEY_IDENTIFIER;
                    recipientId.u.KeyId.cbData = (uint)(ski.Length);
                    recipientId.u.KeyId.pbData = pSki;
                    break;
                }

                default:
                    // The public contract for CmsRecipient guarantees that SubjectKeyIdentifier and IssuerAndSerialNumber are the only two possibilities.
                    Debug.Fail($"Unexpected SubjectIdentifierType: {type}");
                    throw new NotSupportedException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, type));
                }

                return(recipientId);
            }
Example #15
0
 static void AssertDefaultValues(CmsRecipient recipient, X509Certificate certificate)
 {
     Assert.AreEqual(certificate, recipient.Certificate);
     Assert.AreEqual(1, recipient.EncryptionAlgorithms.Length);
     Assert.AreEqual(EncryptionAlgorithm.TripleDes, recipient.EncryptionAlgorithms[0]);
     Assert.AreEqual(SubjectIdentifierType.IssuerAndSerialNumber, recipient.RecipientIdentifierType);
 }
Example #16
0
        public void SubjectKeyIdentifier()
        {
            X509Certificate2 x509 = GetCertificate(true);
            CmsRecipient     p7r  = new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, x509);

            Assert.AreEqual(SubjectIdentifierType.SubjectKeyIdentifier, p7r.RecipientIdentifierType, "RecipientIdentifierType");
            Assert.AreEqual(x509.Thumbprint, p7r.Certificate.Thumbprint, "Certificate");
        }
Example #17
0
        public void Unknown()
        {
            X509Certificate2 x509 = GetCertificate(true);
            CmsRecipient     p7r  = new CmsRecipient(SubjectIdentifierType.Unknown, x509);

            Assert.AreEqual(SubjectIdentifierType.IssuerAndSerialNumber, p7r.RecipientIdentifierType, "RecipientIdentifierType");
            Assert.AreEqual(x509.Thumbprint, p7r.Certificate.Thumbprint, "Certificate");
        }
Example #18
0
 static void AssertDefaultValues(CmsRecipient recipient, X509Certificate certificate)
 {
     Assert.AreEqual(certificate, recipient.Certificate, "Certificate");
     Assert.AreEqual(1, recipient.EncryptionAlgorithms.Length, "EncryptionAlgorithms");
     Assert.AreEqual(EncryptionAlgorithm.TripleDes, recipient.EncryptionAlgorithms[0], "EncryptionAlgorithm");
     Assert.AreEqual(SubjectIdentifierType.IssuerAndSerialNumber, recipient.RecipientIdentifierType, "RecipientIdentifierType");
     Assert.IsNull(recipient.RsaEncryptionPadding, "RsaEncryptionPadding");
 }
Example #19
0
 public static void CmsRecipientPassUnknown()
 {
     using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
     {
         CmsRecipient r = new CmsRecipient(SubjectIdentifierType.Unknown, cert);
         Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType);
         Assert.Same(cert, r.Certificate);
     }
 }
Example #20
0
        private byte[] envelope(byte[] message)
        {
            var content          = new ContentInfo(message);
            var envelopedContent = new EnvelopedCms(content);
            var recipient        = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, _recipientCert);

            envelopedContent.Encrypt(recipient);
            return(envelopedContent.Encode());
        }
Example #21
0
        private KeyTransRecipientInfoAsn MakeKtri(
            byte[] cek,
            CmsRecipient recipient,
            out bool v0Recipient)
        {
            KeyTransRecipientInfoAsn ktri = new KeyTransRecipientInfoAsn();

            if (recipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier)
            {
                ktri.Version = 2;
                ktri.Rid.SubjectKeyIdentifier = GetSubjectKeyIdentifier(recipient.Certificate);
            }
            else if (recipient.RecipientIdentifierType == SubjectIdentifierType.IssuerAndSerialNumber)
            {
                byte[] serial = recipient.Certificate.GetSerialNumber();
                Array.Reverse(serial);

                IssuerAndSerialNumberAsn iasn = new IssuerAndSerialNumberAsn
                {
                    Issuer       = recipient.Certificate.IssuerName.RawData,
                    SerialNumber = serial,
                };

                ktri.Rid.IssuerAndSerialNumber = iasn;
            }
            else
            {
                throw new CryptographicException(
                          SR.Cryptography_Cms_Invalid_Subject_Identifier_Type,
                          recipient.RecipientIdentifierType.ToString());
            }

            RSAEncryptionPadding padding;

            switch (recipient.Certificate.GetKeyAlgorithm())
            {
            case Oids.RsaOaep:
                padding = RSAEncryptionPadding.OaepSHA1;
                ktri.KeyEncryptionAlgorithm.Algorithm  = new Oid(Oids.RsaOaep, Oids.RsaOaep);
                ktri.KeyEncryptionAlgorithm.Parameters = s_rsaOaepSha1Parameters;
                break;

            default:
                padding = RSAEncryptionPadding.Pkcs1;
                ktri.KeyEncryptionAlgorithm.Algorithm  = new Oid(Oids.Rsa, Oids.Rsa);
                ktri.KeyEncryptionAlgorithm.Parameters = s_rsaPkcsParameters;
                break;
            }

            using (RSA rsa = recipient.Certificate.GetRSAPublicKey())
            {
                ktri.EncryptedKey = rsa.Encrypt(cek, padding);
            }

            v0Recipient = (ktri.Version == 0);
            return(ktri);
        }
Example #22
0
        public static string EncryptText(string plainText, X509Certificate2 certificate)
        {
            const string OID_NIST_AES256_CBC = "2.16.840.1.101.3.4.1.42";
            var          content             = new ContentInfo(Encoding.Unicode.GetBytes(plainText));
            var          envelope            = new EnvelopedCms(content, new AlgorithmIdentifier(new Oid(OID_NIST_AES256_CBC)));
            var          recepient           = new CmsRecipient(certificate);

            envelope.Encrypt(recepient);
            return(Convert.ToBase64String(envelope.Encode()));
        }
Example #23
0
        private byte[] EncryptedBytes(byte[] bytes)
        {
            var contentInfo    = new ContentInfo(bytes);
            var encryptAlgoOid = new Oid("2.16.840.1.101.3.4.1.42"); // AES-256-CBC
            var envelopedCms   = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(encryptAlgoOid));
            var recipient      = new CmsRecipient(CryptographicCertificate);

            envelopedCms.Encrypt(recipient);
            return(envelopedCms.Encode());
        }
Example #24
0
        private void BtnEnvolver_Click(object sender, RoutedEventArgs e)
        {
            X509Certificate2 cert = LeerCertificado(txtCertificado.Text);
            var content           = new ContentInfo(Encoding.UTF8.GetBytes(txtClaro.Text));
            var envelopedCms      = new EnvelopedCms(content);
            var recipient         = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);

            envelopedCms.Encrypt(recipient);
            txtSalida.Text = Convert.ToBase64String(envelopedCms.Encode());
        }
 private static void ValidateEnumerator(IEnumerator enumerator, IList <CmsRecipient> expected)
 {
     foreach (CmsRecipient e in expected)
     {
         Assert.True(enumerator.MoveNext());
         CmsRecipient actual = (CmsRecipient)(enumerator.Current);
         Assert.Equal(e, actual);
     }
     Assert.False(enumerator.MoveNext());
 }
Example #26
0
        // Зашифровываем сообщение, используя открытый ключ
        // получателя, при помощи класса EnvelopedCms.
        static byte[] EncryptMsg(
            Byte[] msg,
            X509Certificate2 recipientCert,
            bool useDataContextType)
        {
            // Помещаем сообщение в объект ContentInfo
            // Это требуется для создания объекта EnvelopedCms.

            ContentInfo contentInfo;

            if (useDataContextType)
            {
                contentInfo = new ContentInfo(
                    new Oid("1.2.840.113549.1.7.1"),
                    msg);
            }
            else
            {
                contentInfo = new ContentInfo(
                    ContentInfo.GetContentType(msg),
                    msg);
            }
            //contentInfo = new ContentInfo(msg);

            // Создаем объект EnvelopedCms, передавая ему
            // только что созданный объект ContentInfo.
            // Используем идентификацию получателя (SubjectIdentifierType)
            // по умолчанию (IssuerAndSerialNumber).
            // Не устанавливаем алгоритм зашифрования тела сообщения:
            // ContentEncryptionAlgorithm устанавливается в
            // RSA_DES_EDE3_CBC, несмотря на это, при зашифровании
            // сообщения в адрес получателя с ГОСТ сертификатом,
            // будет использован алгоритм GOST 28147-89.
            //EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(new Oid("1.2.840.113549.3.7")));
            EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);

            // Создаем объект CmsRecipient, который
            // идентифицирует получателя зашифрованного сообщения.
            CmsRecipient recip1 = new CmsRecipient(
                SubjectIdentifierType.IssuerAndSerialNumber,
                recipientCert);

            Console.Write(
                "Зашифровываем данные для одного получателя " +
                "с именем {0} ...",
                recip1.Certificate.SubjectName.Name);
            // Зашифровываем сообщение.
            envelopedCms.Encrypt(recip1);
            Console.WriteLine("Выполнено.");

            // Закодированное EnvelopedCms сообщение содержит
            // зашифрованный текст сообщения и информацию
            // о каждом получателе данного сообщения.
            return(envelopedCms.Encode());
        }
        public static void TestKeyTransEncryptKey_RsaOaepCertificate_NoPlatformSupport_Throws()
        {
            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RsaOaep2048_NoParameters.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(cert);
                Assert.Throws <CryptographicException>(() => ecms.Encrypt(cmsRecipient));
            }
        }
Example #28
0
        /// <summary>
        /// Encrypts the specified string.
        /// </summary>
        /// <param name="plaintext">The plaintext to be encrypted.</param>
        /// <param name="certificate">The certificate to be used for encryption.</param>
        /// <returns>The encrypted text.</returns>
        public static string Encrypt(this string plaintext, X509Certificate2 certificate)
        {
            var contentInfo  = new ContentInfo(Encoding.UTF8.GetBytes(plaintext));
            var envelopedCms = new EnvelopedCms(contentInfo);

            var cmsRecipient = new CmsRecipient(certificate);

            envelopedCms.Encrypt(cmsRecipient);

            return(Convert.ToBase64String(envelopedCms.Encode()));
        }
        public static void Twoary_Ski()
        {
            CmsRecipient           a0 = s_cr0;
            CmsRecipientCollection c  = new CmsRecipientCollection(SubjectIdentifierType.SubjectKeyIdentifier, new X509Certificate2Collection(a0.Certificate));

            Assert.Equal(1, c.Count);
            CmsRecipient actual = c[0];

            Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, actual.RecipientIdentifierType);
            Assert.Equal(a0.Certificate, actual.Certificate);
        }
Example #30
0
        public static void RsaOaepCertificate_NullParameters_Throws()
        {
            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RsaOaep2048_NullParameters.GetCertificate())
            {
                CmsRecipient recipient = new CmsRecipient(cert);
                Assert.ThrowsAny <CryptographicException>(() => ecms.Encrypt(recipient));
            }
        }
	public CmsRecipientCollection(CmsRecipient recipient) {}
Example #32
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.CmsRecipientCollection.Add(System.Security.Cryptography.Pkcs.CmsRecipient)"/> method adds a recipient to the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipientCollection"/> collection.
 /// </summary>
 /// 
 /// <returns>
 /// If the method succeeds, the method returns an <see cref="T:System.Int32"/> value that represents the zero-based position where the recipient is to be inserted.If the method fails, it throws an exception.
 /// </returns>
 /// <param name="recipient">A <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipient"/> object that represents the recipient to add to the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipientCollection"/> collection.</param><exception cref="T:System.ArgumentNullException"><paramref name="recipient"/> is null.</exception>
 public int Add(CmsRecipient recipient)
 {
     if (recipient == null)
         throw new ArgumentNullException("recipient");
     else
         return this.m_recipients.Add((object)recipient);
 }
		/// <summary>
		/// Gets the X.509 certificate associated with the <see cref="MimeKit.MailboxAddress"/>.
		/// </summary>
		/// <remarks>
		/// Gets the X.509 certificate associated with the <see cref="MimeKit.MailboxAddress"/>.
		/// </remarks>
		/// <returns>The certificate.</returns>
		/// <param name="mailbox">The mailbox.</param>
		/// <exception cref="CertificateNotFoundException">
		/// A certificate for the specified <paramref name="mailbox"/> could not be found.
		/// </exception>
		protected override CmsRecipient GetCmsRecipient (MailboxAddress mailbox)
		{
			var certificate = GetCmsRecipientCertificate (mailbox);
			var cert = DotNetUtilities.FromX509Certificate (certificate);
			var recipient = new CmsRecipient (cert);

			foreach (var extension in certificate.Extensions) {
				if (extension.Oid.Value == "1.2.840.113549.1.9.15") {
					var algorithms = DecodeEncryptionAlgorithms (extension.RawData);

					if (algorithms != null)
						recipient.EncryptionAlgorithms = algorithms;

					break;
				}
			}

			return recipient;
		}
Example #34
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.CmsRecipientCollection.CopyTo(System.Security.Cryptography.Pkcs.CmsRecipient[],System.Int32)"/> method copies the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipientCollection"/> collection to a <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipient"/> array.
 /// </summary>
 /// <param name="array">An array of <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipient"/> objects where the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipientCollection"/> collection is to be copied.</param><param name="index">The zero-based index for the array of <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipient"/> objects in <paramref name="array"/> to which the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipientCollection"/> collection is copied.</param><exception cref="T:System.ArgumentException"><paramref name="array"/> is not large enough to hold the specified elements.-or-<paramref name="array"/> does not contain the proper number of dimensions.</exception><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is outside the range of elements in <paramref name="array"/>.</exception>
 public void CopyTo(CmsRecipient[] array, int index)
 {
     this.CopyTo((Array)array, index);
 }
Example #35
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.CmsRecipientCollection.Remove(System.Security.Cryptography.Pkcs.CmsRecipient)"/> method removes a recipient from the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipientCollection"/> collection.
 /// </summary>
 /// <param name="recipient">A <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipient"/> object that represents the recipient to remove from the collection.</param><exception cref="T:System.ArgumentNullException"><paramref name="recipient"/> is null.</exception>
 public void Remove(CmsRecipient recipient)
 {
     if (recipient == null)
         throw new ArgumentNullException("recipient");
     this.m_recipients.Remove((object)recipient);
 }
Example #36
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.CmsRecipientCollection.#ctor(System.Security.Cryptography.Pkcs.CmsRecipient)"/> constructor creates an instance of the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipientCollection"/> class and adds the specified recipient.
 /// </summary>
 /// <param name="recipient">An instance of the <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipient"/> class that represents the specified CMS/PKCS #7 recipient.</param>
 public CmsRecipientCollection(CmsRecipient recipient)
 {
     this.m_recipients = new ArrayList(1);
     this.m_recipients.Add((object)recipient);
 }
	// Methods
	public int Add(CmsRecipient recipient) {}
Example #38
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.EnvelopedCms.Encrypt(System.Security.Cryptography.Pkcs.CmsRecipient)"/> method encrypts the contents of the CMS/PKCS #7 message by using the specified recipient information.
 /// </summary>
 /// <param name="recipient">A <see cref="T:System.Security.Cryptography.Pkcs.CmsRecipient"/> object that represents the recipient information.</param><exception cref="T:System.ArgumentNullException">A null reference was passed to a method that does not accept it as a valid argument. </exception><exception cref="T:System.Security.Cryptography.CryptographicException">A cryptographic operation could not be completed.</exception>
 public void Encrypt(CmsRecipient recipient)
 {
     if (recipient == null)
         throw new ArgumentNullException("recipient");
     this.Encrypt(new CmsRecipientCollection(recipient));
 }
	public void CopyTo(CmsRecipient[] array, int index) {}
	public void Remove(CmsRecipient recipient) {}
	public void Encrypt(CmsRecipient recipient) {}