Decrypt() public method

public Decrypt ( ) : void
return void
Ejemplo n.º 1
0
        public static void ImportEdgeCase()
        {
            //
            // Pfx's imported into a certificate collection propagate their "delete on Dispose" behavior to its cloned instances:
            // a subtle difference from Pfx's created using the X509Certificate2 constructor that can lead to premature or
            // double key deletion. Since EnvelopeCms.Decrypt() has no legitimate reason to clone the extraStore certs, this shouldn't
            // be a problem, but this test will verify that it isn't.
            //

            byte[] encodedMessage =
                ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
                + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
                + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
                + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
                + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
                + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();

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

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport())
            {
                X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
                ecms.Decrypt(extraStore);

                byte[] expectedContent = { 1, 2, 3 };
                ContentInfo contentInfo = ecms.ContentInfo;
                Assert.Equal<byte>(expectedContent, contentInfo.Content);
            }
        }
Ejemplo n.º 2
0
        public static void Rc4AndCngWrappersDontMixTest()
        {
            //
            // Combination of RC4 over a CAPI certificate.
            //
            //  This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG),
            //  the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG.
            //

            byte[] content = { 6, 3, 128, 33, 44 };
            AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4));

            EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4);
            CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate()));
            ecms.Encrypt(recipients);
            byte[] encodedMessage = ecms.Encode();

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

            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.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);
        }
 public static string DecryptEnvelop(string base64EncryptedString)
 {
     var encryptedBytes = Convert.FromBase64String(base64EncryptedString);
     var envelope = new EnvelopedCms();
     envelope.Decode(encryptedBytes);
     var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
     store.Open(OpenFlags.ReadOnly);
     envelope.Decrypt(store.Certificates);
     return Encoding.UTF8.GetString(envelope.ContentInfo.Content);
 }
Ejemplo n.º 4
0
        public static string Decrypt(string encryptedString)
        {
            // パスワードを復号
            var store = new X509Store(StoreLocation.LocalMachine); // (StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);

            var encPasswordBase64 = Convert.FromBase64String(encryptedString);

            var enveloped = new EnvelopedCms();
            enveloped.Decode(encPasswordBase64);
            enveloped.Decrypt(store.Certificates);

            return Encoding.UTF8.GetString(enveloped.ContentInfo.Content);
        }
        /// <summary>
        /// Decrypts enveloped mime content.
        /// </summary>
        /// <param name="cert">Decrypting certificate.</param>
        /// <returns>Returns decrypted enveloped mime content.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>cert</b> is null reference.</exception>
        /// <exception cref="InvalidOperationException">Is raised when <b>smime-type != enveloped-data</b>.</exception>
        public MIME_Message GetEnvelopedMime(X509Certificate2 cert)
        {
            if(cert == null){
                throw new ArgumentNullException("cert");
            }
            if(!string.Equals(this.Entity.ContentType.Parameters["smime-type"],"enveloped-data",StringComparison.InvariantCultureIgnoreCase)){
                throw new InvalidOperationException("The VerifySignature method is only valid if Content-Type parameter smime-type=enveloped-data.");
            }

            EnvelopedCms envelopedCms = new EnvelopedCms();
            envelopedCms.Decode(this.Data);

            X509Certificate2Collection certificates = new X509Certificate2Collection(cert);
            envelopedCms.Decrypt(certificates);

            return MIME_Message.ParseFromStream(new MemoryStream(envelopedCms.Encode()));
        }
        /// <summary>
        /// Decrypts the specified string.
        /// </summary>
        /// <param name="ciphertext">The ciphertext to be decrypted.</param>
        /// <param name="certificates">A set of certificates containing the one that was used to encrypt the ciphertext.</param>
        /// <returns>The decrypted text.</returns>
        public static string Decrypt(this string ciphertext, params X509Certificate2[] certificates)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);
            
            var certCollection = store.Certificates;

            if (certificates != null && certificates.Length > 0)
            {
                certCollection.AddRange(certificates);
            }

            var envelopedCms = new EnvelopedCms();
            envelopedCms.Decode(Convert.FromBase64String(ciphertext));
            envelopedCms.Decrypt(certCollection);
            return Encoding.UTF8.GetString(envelopedCms.ContentInfo.Content);
        }
Ejemplo n.º 7
0
        public static void ImportEdgeCaseSki()
        {
            byte[] encodedMessage =
                ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158"
                + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83"
                + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46"
                + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba"
                + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray();

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

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport())
            {
                X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
                ecms.Decrypt(extraStore);

                byte[] expectedContent = { 1, 2, 3 };
                ContentInfo contentInfo = ecms.ContentInfo;
                Assert.Equal<byte>(new byte[] { 1, 2, 3 }, contentInfo.Content);
                Assert.Equal<byte>(expectedContent, contentInfo.Content);
            }
        }
Ejemplo n.º 8
0
        public static void PostDecrypt_Decrypt()
        {
            byte[] expectedContent = { 6, 3, 128, 33, 44 };

            byte[] encodedMessage =
                 ("308202b006092a864886f70d010703a08202a13082029d020100318202583081c5020100302e301a31183016060355040313"
                + "0f5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004"
                + "81801026d9fb60d1a55686b73cf859c8bd66b58defda5e23e3da5f535f1427e3c5f7a4a2a94373e8e3ba5488a7c6a1059bfb"
                + "57301156698e7fca62671426d388fb3fb4373c9cb53132fda067598256bbfe8491b14dadaaf04d5fdfb2463f358ad0d6a594"
                + "bf6a4fbab6b3d725f08032e601492265e6336d5a638096f9975025ccd6393081c5020100302e301a31183016060355040313"
                + "0f5253414b65795472616e736665723202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d010101050004"
                + "8180b6497a2b789728f200ca1f974a676c531a4769f03f3929bd7526e7333ea483b4abb530a49c8532db5d4a4df66f173e3e"
                + "a4ba9e4814b584dc987ac87c46bb131daab535140968aafad8808100a2515e9c6d0c1f382b024992ce36b70b841628e0eb43"
                + "4db89545d702a8fbd3403188e7de7cb4bc1dcc3bc325467570654aaf2ee83081c5020100302e301a31183016060355040313"
                + "0f5253414b65795472616e736665723302104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d010101050004"
                + "81807517e594c353d41abff334c6162988b78e05df7d79457c146fbc886d2d8057f594fa3a96cd8df5842c9758baac1fcdd5"
                + "d9672a9f8ef9426326cccaaf5954f2ae657f8c7b13aef2f811adb4954323aa8319a1e8f2ad4e5c96c1d3fbe413ae479e471b"
                + "b701cbdfa145c9b64f5e1f69f472804995d56c31351553f779cf8efec237303c06092a864886f70d010701301d0609608648"
                + "01650304012a041023a114c149d7d4017ce2f5ec7c5d53f980104e50ab3c15533743dd054ef3ff8b9d83").HexToByteArray();

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

            using (X509Certificate2 cert1 = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
            using (X509Certificate2 cert2 = Certificates.RSAKeyTransfer2.TryGetCertificateWithPrivateKey())
            using (X509Certificate2 cert3 = Certificates.RSAKeyTransfer3.TryGetCertificateWithPrivateKey())
            {
                if (cert1 == null || cert2 == null || cert3 == 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(cert1);
                extraStore.Add(cert2);
                extraStore.Add(cert3);
                RecipientInfoCollection r = ecms.RecipientInfos;
                ecms.Decrypt(r[0], extraStore);
                ContentInfo contentInfo = ecms.ContentInfo;
                Assert.Equal<byte>(expectedContent, contentInfo.Content);

                // Though this doesn't seem like a terribly unreasonable thing to attempt, attempting to call Decrypt() again
                // after a successful Decrypt() throws a CryptographicException saying "Already decrypted."
                Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(r[1], extraStore));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Decrypt the encrypted data.
        /// </summary>
        /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="encryptedData"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public override MimeEntity Decrypt(Stream encryptedData)
        {
            if (encryptedData == null)
                throw new ArgumentNullException ("encryptedData");

            var enveloped = new EnvelopedCms ();
            enveloped.Decode (ReadAllBytes (encryptedData));

            var store = new X509Store (StoreName.My, StoreLocation);
            store.Open (OpenFlags.ReadOnly);

            enveloped.Decrypt ();
            store.Close ();

            var decryptedData = enveloped.Encode ();

            using (var memory = new MemoryStream (decryptedData, false)) {
                return MimeEntity.Load (memory);
            }
        }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
/*		[Test]
		[ExpectedException (typeof (ArgumentNullException))]
		public void DecryptX509CertificateExCollectionNull () 
		{
			EnvelopedPkcs7 ep = new EnvelopedPkcs7 ();
			RecipientInfo ri = 
			ep.Decrypt (ri, null);
		}*/

		private void RoundTrip (byte[] encoded) 
		{
			X509Certificate2Collection xc = new X509Certificate2Collection ();
			xc.Add (GetCertificate (true));
			EnvelopedCms ep = new EnvelopedCms ();
			ep.Decode (encoded);
			ep.Decrypt (xc);
			Assert.AreEqual ("05-00", BitConverter.ToString (ep.ContentInfo.Content), "ContentInfo.Content");
		}
Ejemplo n.º 12
0
        public static void EnvelopedCmsDecryptWithoutMatchingCertSki()
        {
            // You don't have the private key? No message for you.

            // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger
            // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. 
            using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
            { }

            byte[] encodedMessage =
                ("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158"
                + "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83"
                + "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46"
                + "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba"
                + "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray();

            EnvelopedCms ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);
            RecipientInfo recipientInfo = ecms.RecipientInfos[0];
            X509Certificate2Collection extraStore = new X509Certificate2Collection();
            Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo));
            Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore));
            Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore));
        }
Ejemplo n.º 13
0
        private static void ValidateZeroLengthContent(byte[] encodedMessage)
        {
            EnvelopedCms ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);
            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
            {
                if (cert == null)
                    return;
                X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
                ecms.Decrypt(extraStore);
                ContentInfo contentInfo = ecms.ContentInfo;
                byte[] content = contentInfo.Content;
                if (content.Length == 6)
                    throw new Exception("ContentInfo expected to be 0 but was actually 6. If you're running on the desktop CLR, this is actually a known bug.");

                Assert.Equal(0, content.Length);
            }
        }
Ejemplo n.º 14
0
        private static void VerifySimpleDecrypt(byte[] encodedMessage, CertLoader certLoader, ContentInfo expectedContent)
        {
            EnvelopedCms ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);

            using (X509Certificate2 cert = certLoader.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(cert);
                ecms.Decrypt(extraStore);
                ContentInfo contentInfo = ecms.ContentInfo;
                Assert.Equal(expectedContent.ContentType.Value, contentInfo.ContentType.Value);
                Assert.Equal<byte>(expectedContent.Content, contentInfo.Content);
            }
        }
Ejemplo n.º 15
0
        public static void EnvelopedCmsDecryptNullExtraStore()
        {
            byte[] encodedMessage =
                ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
                + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
                + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
                + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
                + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
                + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();

            EnvelopedCms ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);
            RecipientInfo recipientInfo = ecms.RecipientInfos[0];
            X509Certificate2Collection extraStore = null;
            Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(extraStore));
            Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore));
        }
Ejemplo n.º 16
0
        private string Decrypt(string actualContent)
        {
            // Extract out the bytes and Base64 decode them
            int startIndex, endIndex;
            byte[] messageBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex);
            if ((messageBytes == null) && (!IncludeContext))
            {
                ErrorRecord error = new ErrorRecord(
                    new ArgumentException(
                        String.Format(CultureInfo.InvariantCulture,
                            CmsCommands.InputContainedNoEncryptedContentIncludeContext, "-IncludeContext")),
                    "InputContainedNoEncryptedContentIncludeContext", ErrorCategory.ObjectNotFound, null);
                ThrowTerminatingError(error);
            }

            // Capture the pre and post context, if there was any
            string preContext = null;
            string postContext = null;
            if (IncludeContext)
            {
                if (startIndex > -1)
                {
                    preContext = actualContent.Substring(0, startIndex);
                }
                if (endIndex > -1)
                {
                    postContext = actualContent.Substring(endIndex);
                }
            }

            EnvelopedCms cms = new EnvelopedCms();
            X509Certificate2Collection certificates = new X509Certificate2Collection();

            if ((To != null) && (To.Length > 0))
            {
                ErrorRecord error = null;

                foreach (CmsMessageRecipient recipient in To)
                {
                    recipient.Resolve(this.SessionState, ResolutionPurpose.Decryption, out error);
                    if (error != null)
                    {
                        ThrowTerminatingError(error);
                        return null;
                    }

                    foreach (X509Certificate2 certificate in recipient.Certificates)
                    {
                        certificates.Add(certificate);
                    }
                }
            }

            string resultString = actualContent;
            if (messageBytes != null)
            {
                cms.Decode(messageBytes);
                cms.Decrypt(certificates);

                resultString = System.Text.Encoding.UTF8.GetString(cms.ContentInfo.Content);
            }

            if (IncludeContext)
            {
                if (preContext != null)
                {
                    resultString = preContext + resultString;
                }
                if (postContext != null)
                {
                    resultString = resultString + postContext;
                }
            }

            return resultString;
        }
Ejemplo n.º 17
0
        public static void PostDecrypt_RecipientInfos()
        {
            byte[] expectedContent = { 6, 3, 128, 33, 44 };

            EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent));
            ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate()));
            byte[] encodedMessage =
                 ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
                + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067"
                + "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380"
                + "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac"
                + "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d"
                + "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray();
            ecms.Decode(encodedMessage);

            using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
            {
                if (cer == 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(cer);
                RecipientInfoCollection col1 = ecms.RecipientInfos;
                ecms.Decrypt(col1[0], extraStore);

                // Make sure we can still RecipientInfos after a Decrypt()
                RecipientInfoCollection col2 = ecms.RecipientInfos;
                Assert.Equal(col1.Count, col2.Count);

                RecipientInfo r1 = col1[0];
                RecipientInfo r2 = col2[0];

                X509IssuerSerial is1 = (X509IssuerSerial)(r1.RecipientIdentifier.Value);
                X509IssuerSerial is2 = (X509IssuerSerial)(r2.RecipientIdentifier.Value);
                Assert.Equal(is1.IssuerName, is2.IssuerName);
                Assert.Equal(is1.SerialNumber, is2.SerialNumber);
            }
        }
Ejemplo n.º 18
0
        public static void PostDecrypt_Encode()
        {
            byte[] expectedContent = { 6, 3, 128, 33, 44 };

            EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent));
            ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate()));
            byte[] encodedMessage =
                 ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
                + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067"
                + "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380"
                + "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac"
                + "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d"
                + "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray();
            ecms.Decode(encodedMessage);

            using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
            {
                if (cer == 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(cer);
                RecipientInfoCollection r = ecms.RecipientInfos;
                ecms.Decrypt(r[0], extraStore);

                // Desktop compat: Calling Encode() at this point should have thrown an InvalidOperationException. Instead, it returns
                // the decrypted inner content (same as ecms.ContentInfo.Content). This is easy for someone to take a reliance on
                // so for compat sake, we'd better keep it. 
                byte[] encoded = ecms.Encode();
                Assert.Equal<byte>(expectedContent, encoded);
            }
        }
Ejemplo n.º 19
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());
 }
Ejemplo n.º 20
0
 public static void PostCtor_Decrypt()
 {
     EnvelopedCms ecms = new EnvelopedCms();
     Assert.Throws<InvalidOperationException>(() => ecms.Decrypt());
 }
 public static byte[] Decrypt(byte[] kryptertData)
 {
     var envelopedCms = new EnvelopedCms();
     envelopedCms.Decode(kryptertData);
     envelopedCms.Decrypt(envelopedCms.RecipientInfos[0]);
     return envelopedCms.ContentInfo.Content;
 }
Ejemplo n.º 22
0
		public void Decrypt () 
		{
			byte[] encoded = { 0x30, 0x82, 0x01, 0x1C, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x03, 0xA0, 0x82, 0x01, 0x0D, 0x30, 0x82, 0x01, 0x09, 0x02, 0x01, 0x00, 0x31, 0x81, 0xD6, 0x30, 0x81, 0xD3, 0x02, 0x01, 0x00, 0x30, 0x3C, 0x30, 0x28, 0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x1D, 0x4D, 0x6F, 0x74, 0x75, 0x73, 0x20, 0x54, 0x65, 0x63, 0x68, 0x6E, 0x6F, 0x6C, 0x6F, 0x67, 0x69, 0x65, 0x73, 0x20, 0x69, 0x6E, 0x63, 0x2E, 0x28, 0x74, 0x65, 0x73, 0x74, 0x29, 0x02, 0x10, 0x91, 0xC4, 0x4B, 0x0D, 0xB7, 0xD8, 0x10, 0x84, 0x42, 0x26, 0x71, 0xB3, 0x97, 0xB5, 0x00, 0x97, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x81, 0x80, 0xCA, 0x4B, 0x97, 0x9C, 0xAB, 0x79, 0xC6, 0xDF, 0x6A, 0x27, 0xC7, 0x24, 0xC4, 0x5E, 0x3B, 0x31, 0xAD, 0xBC, 0x25, 0xE6, 0x38, 0x5E, 0x79, 0x26, 0x0E, 0x68, 0x46, 0x1D, 0x21, 0x81, 0x38, 0x92, 0xEC, 0xCB, 0x7C, 0x91, 0xD6, 0x09, 0x38, 0x91, 0xCE, 0x50, 0x5B, 0x70, 0x31, 0xB0, 0x9F, 0xFC, 0xE2, 0xEE, 0x45, 0xBC, 0x4B, 0xF8, 0x9A, 0xD9, 0xEE, 0xE7, 0x4A, 0x3D, 0xCD, 0x8D, 0xFF, 0x10, 0xAB, 0xC8, 0x19, 0x05, 0x54, 0x5E, 0x40, 0x7A, 0xBE, 0x2B, 0xD7, 0x22, 0x97, 0xF3, 0x23, 0xAF, 0x50, 0xF5, 0xEB, 0x43, 0x06, 0xC3, 0xFB, 0x17, 0xCA, 0xBD, 0xAD, 0x28, 0xD8, 0x10, 0x0F, 0x61, 0xCE, 0xF8, 0x25, 0x70, 0xF6, 0xC8, 0x1E, 0x7F, 0x82, 0xE5, 0x94, 0xEB, 0x11, 0xBF, 0xB8, 0x6F, 0xEE, 0x79, 0xCD, 0x63, 0xDD, 0x59, 0x8D, 0x25, 0x0E, 0x78, 0x55, 0xCE, 0x21, 0xBA, 0x13, 0x6B, 0x30, 0x2B, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0x30, 0x14, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03, 0x07, 0x04, 0x08, 0x8C, 0x5D, 0xC9, 0x87, 0x88, 0x9C, 0x05, 0x72, 0x80, 0x08, 0x2C, 0xAF, 0x82, 0x91, 0xEC, 0xAD, 0xC5, 0xB5 };
			EnvelopedCms ep = new EnvelopedCms ();
			ep.Decode (encoded);

			X509Certificate2 x509 = GetCertificate (true);
			X509Certificate2Collection xc = new X509Certificate2Collection ();
			xc.Add (x509);
			ep.Decrypt (xc);
			// properties
			Assert.AreEqual (0, ep.Certificates.Count, "Certificates");
			Assert.AreEqual (192, ep.ContentEncryptionAlgorithm.KeyLength, "ContentEncryptionAlgorithm.KeyLength");
			Assert.AreEqual (tdesName, ep.ContentEncryptionAlgorithm.Oid.FriendlyName, "ContentEncryptionAlgorithm.Oid.FriendlyName");
			Assert.AreEqual (tdesOid, ep.ContentEncryptionAlgorithm.Oid.Value, "ContentEncryptionAlgorithm.Oid.Value");
			Assert.AreEqual (16, ep.ContentEncryptionAlgorithm.Parameters.Length, "ContentEncryptionAlgorithm.Parameters");
			Assert.AreEqual (p7DataName, ep.ContentInfo.ContentType.FriendlyName, "ContentInfo.ContentType.FriendlyName");
			Assert.AreEqual (p7DataOid, ep.ContentInfo.ContentType.Value, "ContentInfo.ContentType.Value");
			Assert.AreEqual ("05-00", BitConverter.ToString (ep.ContentInfo.Content), "ContentInfo.Content");
			Assert.AreEqual (1, ep.RecipientInfos.Count, "RecipientInfos");
			Assert.AreEqual (0, ep.UnprotectedAttributes.Count, "UnprotectedAttributes");
			Assert.AreEqual (0, ep.Version, "Version");
		}
		/// <summary>
		/// Decrypt the encrypted data.
		/// </summary>
		/// <remarks>
		/// Decrypt the encrypted data.
		/// </remarks>
		/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
		/// <param name="encryptedData">The encrypted data.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="encryptedData"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.Security.Cryptography.CryptographicException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public override MimeEntity Decrypt (Stream encryptedData)
		{
			if (encryptedData == null)
				throw new ArgumentNullException ("encryptedData");

			var enveloped = new EnvelopedCms ();

			enveloped.Decode (ReadAllBytes (encryptedData));
			enveloped.Decrypt ();

			var decryptedData = enveloped.Encode ();

			var memory = new MemoryStream (decryptedData, false);

			return MimeEntity.Load (memory, true);
		}
Ejemplo n.º 24
0
		public void DecryptEmpty () 
		{
			EnvelopedCms ep = new EnvelopedCms ();
			ep.Decrypt ();
		}
Ejemplo n.º 25
0
        public static void EnvelopedCmsDecryptWithoutMatchingCert()
        {
            // You don't have the private key? No message for you.

            // This is the private key that "we don't have." We want to force it to load anyway, though, to trigger
            // the "fail the test due to bad machine config" exception if someone left this cert in the MY store check. 
            using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
            { }

            byte[] encodedMessage =
                ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
                + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
                + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
                + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
                + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
                + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();

            EnvelopedCms ecms = new EnvelopedCms();
            ecms.Decode(encodedMessage);
            RecipientInfo recipientInfo = ecms.RecipientInfos[0];
            X509Certificate2Collection extraStore = new X509Certificate2Collection();
            Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo));
            Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore));
            Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore));
        }
Ejemplo n.º 26
0
		public void DecryptRecipientInfoNull () 
		{
			EnvelopedCms ep = new EnvelopedCms ();
			RecipientInfo ri = null; // do not confuse compiler
			ep.Decrypt (ri);
		}
Ejemplo n.º 27
0
		public void DecryptX509CertificateExCollectionNull () 
		{
			EnvelopedCms ep = new EnvelopedCms ();
			X509Certificate2Collection xec = null; // do not confuse compiler
			ep.Decrypt (xec);
		}
Ejemplo n.º 28
0
		public void DecryptRecipientInfoX509CertificateExCollectionNull () 
		{
			EnvelopedCms ep = new EnvelopedCms ();
			X509Certificate2Collection xec = new X509Certificate2Collection ();
			ep.Decrypt (null, xec);
		}
Ejemplo n.º 29
0
        /// <summary>
        /// Extracts the original message from the S/MIME envelope and decrypts it.
        /// </summary>
        /// <param name="extraStore">Certificates with private keys to be used in addition to those found in the current user's personal store.</param>
        /// <returns>A Message object representing the message as it was before encryption.</returns>
        /// <example>
        /// <code>
        /// [C#]
        /// 
        /// // Load a certificate (with private key) and add it to the collection.
        /// X509Certificate2 cert = new X509Certificate2("C:\\mycertificate.pfx");
        /// 
        /// // We retrieved a Message object by some means and have a reference to it in variable message.
        /// Message originalMessage = message.SmimeDevelopeAndDecrypt(new X509Certificate2Collection(cert));
        /// 
        /// //originalMessage contains all information about the encrypted message.
        /// 
        /// </code>
        /// </example>
#if !PocketPC
        public Message SmimeDevelopeAndDecrypt(X509Certificate2Collection extraStore)
        {
            if (!this.IsSmimeEncrypted) throw new InvalidOperationException("This message doesn't seem to be encrypted, or the encryption method is unknown.");
            else
            {
                EnvelopedCms cms = new EnvelopedCms();
                cms.Decode(this.PartTreeRoot.BinaryContent);
                cms.Decrypt(extraStore);

                Message sub = Parser.ParseMessage(cms.ContentInfo.Content);

                return sub;
            }
        }
Ejemplo n.º 30
-1
 public byte[] decrypt(byte[] data)
 {
     var envelopedCms = new EnvelopedCms();
     envelopedCms.Decode(data);
     envelopedCms.Decrypt(envelopedCms.RecipientInfos[0]);
     return envelopedCms.ContentInfo.Content;
 }