예제 #1
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);
        }
예제 #2
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);
                    }
        }
예제 #3
0
        public static void MultipleRecipientIdentifiers_RoundTrip()
        {
            ContentInfo            contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms           ecms        = new EnvelopedCms(contentInfo);
            CmsRecipientCollection recipients  = new CmsRecipientCollection();

            using (X509Certificate2 issuerSerialCert = Certificates.RSAKeyTransfer1.GetCertificate())
                using (X509Certificate2 explicitSkiCert = Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate())
                {
                    // CmsRecipients have different identifiers to test multiple identifier encryption.
                    recipients.Add(new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, issuerSerialCert));
                    recipients.Add(new CmsRecipient(SubjectIdentifierType.SubjectKeyIdentifier, explicitSkiCert));
                    ecms.Encrypt(recipients);
                }

            byte[] encodedMessage = ecms.Encode();

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

            // Try decoding it, doesn't really matter with which cert you want to do it as it's not what this
            // test aims for.

            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);
        }
예제 #4
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);
        }
예제 #5
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);
        }
        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);
        }
        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);
        }
예제 #8
0
        public static void SignEnveloped(SubjectIdentifierType signerType)
        {
            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(new byte[] { 3 }));
                envelopedCms.Encrypt(new CmsRecipient(signerType, cert));

                SignedCms signedCms = new SignedCms(
                    new ContentInfo(new Oid(Oids.Pkcs7Enveloped), envelopedCms.Encode()));

                signedCms.ComputeSignature(new CmsSigner(cert));
                signedCms.CheckSignature(true);

                SignerInfoCollection signers = signedCms.SignerInfos;
                Assert.Equal(1, signers.Count);

                CryptographicAttributeObjectCollection attrs = signers[0].SignedAttributes;
                Assert.Equal(2, attrs.Count);

                CryptographicAttributeObject firstAttrSet = attrs[0];
                Assert.Equal(Oids.ContentType, firstAttrSet.Oid.Value);
                Assert.Equal(1, firstAttrSet.Values.Count);
                Assert.Equal(Oids.ContentType, firstAttrSet.Values[0].Oid.Value);
                Assert.Equal("06092A864886F70D010703", firstAttrSet.Values[0].RawData.ByteArrayToHex());

                CryptographicAttributeObject secondAttrSet = attrs[1];
                Assert.Equal(Oids.MessageDigest, secondAttrSet.Oid.Value);
                Assert.Equal(1, secondAttrSet.Values.Count);
                Assert.Equal(Oids.MessageDigest, secondAttrSet.Values[0].Oid.Value);
            }
        }
예제 #9
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);
        }
예제 #10
0
        private string Encrypt(string password, X509Certificate2 cert)
        {
            byte[]       bytes        = Encoding.UTF8.GetBytes(password);
            EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(bytes));

            envelopedCms.Encrypt(new CmsRecipient(cert));
            return(Convert.ToBase64String(envelopedCms.Encode()));
        }
        /// <summary>
        /// Encrypts the data.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <returns>encrypted data</returns>
        protected byte[] EncryptData(byte[] source)
        {
            var contentInfo  = new ContentInfo(source);
            var envelopedCms = new EnvelopedCms(contentInfo);

            envelopedCms.Encrypt(new CmsRecipient(this.certificate));
            return(envelopedCms.Encode());
        }
예제 #12
0
        /// <summary>
        /// Encrypt payload string into a base 64-encoded string using the certificate.
        /// This is suitable for encrypting storage account keys for later use as a job argument.
        /// </summary>
        /// <param name="cert">
        /// Certificate used to encrypt the payload.
        /// </param>
        /// <param name="payload">
        /// Value to encrypt.
        /// </param>
        /// <returns>
        /// Encrypted payload.
        /// </returns>
        public static string EncryptAsBase64String(X509Certificate2 cert, string payload)
        {
            var ci  = new ContentInfo(Encoding.UTF8.GetBytes(payload));
            var env = new EnvelopedCms(ci);

            env.Encrypt(new CmsRecipient(cert));
            return(Convert.ToBase64String(env.Encode()));
        }
예제 #13
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());
        }
예제 #14
0
        /// <summary>
        /// Шифрует сообщение
        /// </summary>
        /// <param name="msg">Сообщение</param>
        /// <param name="recipientCerts">Сертификат</param>
        /// <returns>Результат шифровки</returns>
        public static byte[] EncryptMsg(Byte[] msg, X509Certificate2Collection recipientCerts)
        {
            ContentInfo            contentInfo  = new ContentInfo(msg);
            EnvelopedCms           envelopedCms = new EnvelopedCms(contentInfo);
            CmsRecipientCollection recips       = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, recipientCerts);

            envelopedCms.Encrypt(recips);
            return(envelopedCms.Encode());
        }
예제 #15
0
        private static byte[] Encrypt(byte[] contentInfoPayload, X509Certificate2 certificate)
        {
            var envelopedCms = new EnvelopedCms(new ContentInfo(contentInfoPayload), new AlgorithmIdentifier(Oid.FromOidValue(Oids.Aes128Cbc, OidGroup.EncryptionAlgorithm)));

            envelopedCms.Encrypt(new CmsRecipient(certificate));
            var payload = envelopedCms.Encode();

            return(payload);
        }
예제 #16
0
        private static byte[] Encrypt(byte[] contentInfoPayload, SymmetricAlgorithm symmetricAlg, string keyId)
        {
            var envelopedCms = new EnvelopedCms(new ContentInfo(contentInfoPayload), new AlgorithmIdentifier(Oid.FromOidValue(Oids.Aes128Cbc, OidGroup.EncryptionAlgorithm)));

            envelopedCms.Encrypt(new CmsRecipient(keyId, symmetricAlg));
            var payload = envelopedCms.Encode();

            return(payload);
        }
        public static void DecryptMultipleRecipients()
        {
            // Force Decrypt() to try multiple recipients. Ensure that a failure to find a matching cert in one doesn't cause it to quit early.

            CertLoader[] certLoaders = new CertLoader[]
            {
                Certificates.RSAKeyTransfer1,
                Certificates.RSAKeyTransfer2,
                Certificates.RSAKeyTransfer3,
            };

            byte[]                 content    = { 6, 3, 128, 33, 44 };
            EnvelopedCms           ecms       = new EnvelopedCms(new ContentInfo(content), new AlgorithmIdentifier(new Oid(Oids.Aes256)));
            CmsRecipientCollection recipients = new CmsRecipientCollection();

            foreach (CertLoader certLoader in certLoaders)
            {
                recipients.Add(new CmsRecipient(certLoader.GetCertificate()));
            }
            ecms.Encrypt(recipients);
            byte[] encodedMessage = ecms.Encode();

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

            // How do we know that Decrypt() tries receipients in the order they appear in ecms.RecipientInfos? Because we wrote the implementation.
            // Not that some future implementation can't ever change it but it's the best guess we have.
            RecipientInfo me = ecms.RecipientInfos[2];

            CertLoader matchingCertLoader = null;

            for (int index = 0; index < recipients.Count; index++)
            {
                if (recipients[index].Certificate.Issuer == ((X509IssuerSerial)(me.RecipientIdentifier.Value)).IssuerName)
                {
                    matchingCertLoader = certLoaders[index];
                    break;
                }
            }
            Assert.NotNull(matchingCertLoader);

            using (X509Certificate2 cert = matchingCertLoader.TryGetCertificateWithPrivateKey())
            {
                if (cert == null)
                {
                    return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
                }
                X509Certificate2Collection extraStore = new X509Certificate2Collection();
                extraStore.Add(cert);
                ecms.Decrypt(extraStore);
            }

            ContentInfo contentInfo = ecms.ContentInfo;

            Assert.Equal <byte>(content, contentInfo.Content);
        }
예제 #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="message"></param>
        /// <param name="encryptionCertificates"></param>
        /// <returns></returns>
        internal static byte[] EncryptMessage(Byte[] message, X509Certificate2Collection encryptionCertificates)
        {
            EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(message));

            CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificates);

            envelopedCms.Encrypt(recipients);

            return(envelopedCms.Encode());
        }
예제 #19
0
파일: Helpers.cs 프로젝트: zverev-iv/AIM
        /// <summary>
        ///     CMS encryption of a data
        /// </summary>
        /// <param name="data">Data to encrypt</param>
        /// <param name="encryptionCertificates">A list of certificates to encrypt the data with</param>
        /// <returns>The encrypted data</returns>
        internal static byte[] Encrypt(string data, X509Certificate2Collection encryptionCertificates)
        {
            byte[] messageBytes = Encoding.ASCII.GetBytes(data);
            var    envelopedCms = new EnvelopedCms(new ContentInfo(messageBytes));
            var    recipients   = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber,
                                                             encryptionCertificates);

            envelopedCms.Encrypt(recipients);
            return(envelopedCms.Encode());
        }
예제 #20
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());
        }
예제 #21
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()));
        }
예제 #22
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());
        }
예제 #23
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));
            }
        }
예제 #25
0
파일: Cms.cs 프로젝트: waffle-iron/nequeo
        /// <summary>
        /// Encrypts the contents of the CMS/PKCS #7 message by using the specified recipient information.
        /// </summary>
        /// <param name="contentInfo">An instance of the ContentInfo class that represents the content and its type.</param>
        /// <param name="certificate">The certificate used to encrypt the content message.</param>
        /// <returns>If the method succeeds, the method returns an array of byte values that represent the encoded information.
        /// If the method fails, it throws an exception.</returns>
        public byte[] Encrypt(ContentInfo contentInfo, X509Certificate2 certificate)
        {
            // Create a new envolope, passing the
            // content info that is to be encrypted
            // and encoded.
            _cms = new EnvelopedCms(contentInfo);

            // Encode and encrypt
            _cms.Encrypt(new CmsRecipient(certificate));
            return(_cms.Encode());
        }
예제 #26
0
        public static void PostEncrypt_Decrypt()
        {
            ContentInfo  expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                ecms.Encrypt(new CmsRecipient(cert));
            }
            Assert.ThrowsAny <CryptographicException>(() => ecms.Decrypt());
        }
예제 #27
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));
            }
        }
예제 #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()));
        }
        private static EnvelopedCms GetDocWithRecipient(SubjectIdentifierType type, X509Certificate2 cert)
        {
            byte[]       content   = new byte[] { 1, 2, 3, 4 };
            EnvelopedCms cms       = new EnvelopedCms(new ContentInfo(content));
            CmsRecipient recipient = new CmsRecipient(type, cert);

            cms.Encrypt(recipient);
            byte[] encoded = cms.Encode();
            cms = new EnvelopedCms();
            cms.Decode(encoded);
            return(cms);
        }
예제 #30
0
        /// <summary>
        /// Used primarily to encrypt the password for the Remote Desktop using the pvk of the Service Certificate
        /// </summary>
        public string ExportBase64EncryptedString(string password)
        {
            byte[] byPassword   = Encoding.UTF8.GetBytes(password);
            var    info         = new ContentInfo(byPassword);
            var    envelopedCms = new EnvelopedCms(info);

            envelopedCms.Encrypt(new CmsRecipient(_certificate.Certificate));
            return(Convert.ToBase64String(envelopedCms.Encode()));
            //var provider = (RSACryptoServiceProvider)_certificate.Certificate.PublicKey.Key;
            //byte[] cipherText = provider.Encrypt(byPassword, false);
            //return Convert.ToBase64String(cipherText, Base64FormattingOptions.None);
        }