コード例 #1
0
        public static void ZeroLengthContent_RoundTrip()
        {
            ContentInfo  contentInfo = new ContentInfo(Array.Empty <byte>());
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(cert);
                ecms.Encrypt(cmsRecipient);
            }
            byte[] encodedMessage = ecms.Encode();
            ValidateZeroLengthContent(encodedMessage);
        }
コード例 #2
0
        // Encrypts/decrypts messages via http://www.ietf.org/rfc/rfc3852.txt
        // CMS is used to digitally sign, digest, authenticate, or encrypt arbitrary message content.
        // CMS supports digital signatures & encryption. One encapsulation envelope can be nested
        // inside another. Likewise, one party can digitally sign some previously encapsulated data.
        // It also allows arbitrary attributes, such as signing time, to be signed along with the message content,
        // and provides for other attributes such as countersignatures to be associated with a signature.

        /// <summary>Encrypts a string using the Cryptographic Message Syntax.</summary>
        /// <param name="clearText">The string data to encrypt.</param>
        /// <param name="certificate">The certificate (must be marked for key exchange).</param>
        /// <returns>The encrypted string.</returns>
        public static String EncryptTextUsingCms(this String clearText, X509Certificate2 certificate)
        {
            // Good way to get a certificate: new X509Certificate2(pfxCertificatePathname, pfxPassword);

            // Create an envelope with the text as its contents
            var envelopedCms = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(clearText)));

            // Encrypt the envelope for the recipient & return the encoded value;
            // The recipient of the envelope is the owner of the certificate's private key
            // NOTE: the certificate info is embedded; no need to remember the thumbprint separately.
            envelopedCms.Encrypt(new CmsRecipient(certificate));
            return(Convert.ToBase64String(envelopedCms.Encode()));
        }
コード例 #3
0
        internal byte[] SignProject(ExcelVbaProject proj)
        {
            if (!Certificate.HasPrivateKey)
            {
                //throw (new InvalidOperationException("The certificate doesn't have a private key"));
                Certificate = null;
                return(null);
            }
            var hash = GetContentHash(proj);

            BinaryWriter bw = new BinaryWriter(new MemoryStream());

            bw.Write((byte)0x30);                                                                //Constructed Type
            bw.Write((byte)0x32);                                                                //Total length
            bw.Write((byte)0x30);                                                                //Constructed Type
            bw.Write((byte)0x0E);                                                                //Length SpcIndirectDataContent
            bw.Write((byte)0x06);                                                                //Oid Tag Indentifier
            bw.Write((byte)0x0A);                                                                //Lenght OId
            bw.Write(new byte[] { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x1D }); //Encoded Oid 1.3.6.1.4.1.311.2.1.29
            bw.Write((byte)0x04);                                                                //Octet String Tag Identifier
            bw.Write((byte)0x00);                                                                //Zero length

            bw.Write((byte)0x30);                                                                //Constructed Type (DigestInfo)
            bw.Write((byte)0x20);                                                                //Length DigestInfo
            bw.Write((byte)0x30);                                                                //Constructed Type (Algorithm)
            bw.Write((byte)0x0C);                                                                //length AlgorithmIdentifier
            bw.Write((byte)0x06);                                                                //Oid Tag Indentifier
            bw.Write((byte)0x08);                                                                //Lenght OId
            bw.Write(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05 });             //Encoded Oid for 1.2.840.113549.2.5 (AlgorithmIdentifier MD5)
            bw.Write((byte)0x05);                                                                //Null type identifier
            bw.Write((byte)0x00);                                                                //Null length
            bw.Write((byte)0x04);                                                                //Octet String Identifier
            bw.Write((byte)hash.Length);                                                         //Hash length
            bw.Write(hash);                                                                      //Content hash

            ContentInfo contentInfo = new ContentInfo(((MemoryStream)bw.BaseStream).ToArray());

            contentInfo.ContentType.Value = "1.3.6.1.4.1.311.2.1.4";
#if (Core)
            Verifier = new EnvelopedCms(contentInfo);
            var r = new CmsRecipient(Certificate);
            Verifier.Encrypt(r);
            return(Verifier.Encode());
#else
            Verifier = new SignedCms(contentInfo);
            var signer = new CmsSigner(Certificate);
            Verifier.ComputeSignature(signer, false);
            return(Verifier.Encode());
#endif
        }
コード例 #4
0
        private static byte[] EncryptMessage(X509Certificate2 certificate, byte[] message)
        {
            // Создание объекта для шифрования сообщения
            var envelopedCms = new EnvelopedCms(new ContentInfo(message));

            // Создание объектс с информацией о получателе
            var recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, certificate);

            // Шифрование сообщения CMS/PKCS#7
            envelopedCms.Encrypt(recipient);

            // Создание сообщения CMS/PKCS#7
            return(envelopedCms.Encode());
        }
コード例 #5
0
        public static byte[] Encrypt(byte[] data, X509Certificate2 encryptingCert)
        {
            var plainContent = new ContentInfo(data);

            var encryptedData = new EnvelopedCms(plainContent);

            var recipient = new CmsRecipient(encryptingCert);

            encryptedData.Encrypt(recipient);

            byte[] encryptedBytes = encryptedData.Encode();

            return(encryptedBytes);
        }
コード例 #6
0
        public static byte[] Encrypt(byte[] message, string recipientCert, EncryptionAlgorithm encryptionAlgorithm)
        {
            var cert         = new X509Certificate2(recipientCert);
            var contentInfo  = new ContentInfo(message);
            var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(new Oid(encryptionAlgorithm.ToString())));

            var recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);

            envelopedCms.Encrypt(recipient);

            var encoded = envelopedCms.Encode();

            return(encoded);
        }
コード例 #7
0
        public static void DecodeAlgorithmAes256_RoundTrip()
        {
            AlgorithmIdentifier algorithm   = new AlgorithmIdentifier(new Oid(Oids.Aes256));
            ContentInfo         contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms        ecms        = new EnvelopedCms(contentInfo, algorithm);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(cert);
                ecms.Encrypt(cmsRecipient);
            }
            byte[] encodedMessage = ecms.Encode();
            VerifyAlgorithmAes256(encodedMessage);
        }
コード例 #8
0
ファイル: CertificateTests.cs プロジェクト: rsumner31/corefx2
        public static void DecodeCertificates0_RoundTrip()
        {
            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();

            VerifyCertificates0(encodedMessage);
        }
コード例 #9
0
        public static byte[] Decrypt(byte[] encodedEncryptedMessage, out string encryptionAlgorithmName)
        {
            var envelopedCms = new EnvelopedCms();

            // NB. the message will have been encrypted with your public key.
            // The corresponding private key must be installed in the Personal Certificates folder of the user
            // this process is running as.
            envelopedCms.Decode(encodedEncryptedMessage);

            envelopedCms.Decrypt();
            encryptionAlgorithmName = envelopedCms.ContentEncryptionAlgorithm.Oid.FriendlyName;

            return(envelopedCms.Encode());
        }
コード例 #10
0
        public static void DecodeRecipients3_RoundTrip()
        {
            ContentInfo            contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms           ecms        = new EnvelopedCms(contentInfo, KeyAgreeRecipientInfoTests.TripleDesAlgId);
            CmsRecipientCollection recipients  = new CmsRecipientCollection();

            foreach (X509Certificate2 cert in s_certs)
            {
                recipients.Add(new CmsRecipient(cert));
            }
            ecms.Encrypt(recipients);
            byte[] encodedMessage = ecms.Encode();

            VerifyRecipients3(encodedMessage);
        }
コード例 #11
0
ファイル: Secret.cs プロジェクト: stahir80/Azure
        public static string Encrypt(string thumbprint, string value)
        {
            X509Certificate2 cert = GetCertificate(thumbprint);

            if (null != cert)
            {
                byte[]       data        = Encoding.UTF8.GetBytes(value);
                ContentInfo  contentInfo = new ContentInfo(data);
                EnvelopedCms cms         = new EnvelopedCms(contentInfo);
                CmsRecipient recipient   = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
                cms.Encrypt(recipient);
                return(Convert.ToBase64String(cms.Encode()));
            }
            return(string.Empty);
        }
コード例 #12
0
 public byte[] encryptMessage(byte[] msg, X509Certificate2 publicCert)
 {
     byte[] bytes;
     try
     {
         EnvelopedCms envelopedCm = new EnvelopedCms(new ContentInfo(msg));
         envelopedCm.Encrypt(new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, publicCert));
         bytes = envelopedCm.Encode();
     }
     catch (Exception exception)
     {
         bytes = null;
     }
     return(bytes);
 }
コード例 #13
0
        private byte[] Protect(byte[] data, X509Certificate2 encryptionCertificate)
        {
            // first we sign the message
            SignedCms signedCms = new SignedCms(new ContentInfo(data));

            signedCms.ComputeSignature(new CmsSigner(SigningCertificate));
            byte[] signedData = signedCms.Encode();

            // then we encrypt it
            CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificate);
            EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(signedData));

            envelopedCms.Encrypt(cmsRecipient);

            return(envelopedCms.Encode());
        }
コード例 #14
0
		/// <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);
		}
コード例 #15
0
        private void ButtonEncryptWithCER_Click(object sender, EventArgs e)
        {
            byte[]      data        = Encoding.UTF8.GetBytes(textBoxInfo.Text);
            ContentInfo contentInfo = new ContentInfo(data);

            X509Certificate2 cert = new X509Certificate2(fileCertCER);

            CmsRecipient cmsRecipient = new CmsRecipient(cert);

            EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);

            envelopedCms.Encrypt(cmsRecipient);
            this.tempEnvelope = envelopedCms.Encode();

            MessageBox.Show(Convert.ToBase64String(this.tempEnvelope));
        }
コード例 #16
0
        public ActionResult SignAndEncrypt(SignedAsymmetricModel model)
        {
            if (model.Action == "encrypt")
            {
                var plainTextAsBytes     = Encoding.Unicode.GetBytes(model.PlainText);
                var recipientCertificate = LoadCertificate(model.RecipientThumbprint);
                var signingCertificate   = LoadCertificate(model.SenderThumbprint);

                // Sign message
                var signatureContentInfo = new ContentInfo(plainTextAsBytes);
                var signedCms            = new SignedCms(signatureContentInfo);
                var cmsSigner            = new CmsSigner(signingCertificate);
                signedCms.ComputeSignature(cmsSigner);
                var signedMessageAsBytes = signedCms.Encode();

                // Encrypt
                var encryptedContentInfo = new ContentInfo(signedMessageAsBytes);
                var envelopedCms         = new EnvelopedCms(encryptedContentInfo);
                var cmsRecipient         = new CmsRecipient(recipientCertificate);
                envelopedCms.Encrypt(cmsRecipient);
                var envelopeAsBytes = envelopedCms.Encode();

                model.Envelope  = Convert.ToBase64String(envelopeAsBytes);
                model.PlainText = string.Empty;
            }
            else if (model.Action == "decrypt")
            {
                // Decrypt
                var cipherTextAsBytes = Convert.FromBase64String(model.Envelope);
                var envelopedCms      = new EnvelopedCms();
                envelopedCms.Decode(cipherTextAsBytes);
                envelopedCms.Decrypt();
                var encodedSignedCMS = envelopedCms.Encode();
                var signedCms        = new SignedCms();
                signedCms.Decode(encodedSignedCMS);
                signedCms.CheckSignature(true);

                var plainTextAsBytes = signedCms.ContentInfo.Content;
                model.PlainText     = UnicodeEncoding.Unicode.GetString(plainTextAsBytes);
                model.SenderSubject = signedCms.SignerInfos[0].Certificate.Subject;
                model.Envelope      = string.Empty;
            }
            model.RecipientThumbprint = RecipientThumbprint;
            model.SenderThumbprint    = SenderThumbprint;
            ModelState.Clear();
            return(View(model));
        }
コード例 #17
0
        public void EncryptCmsRecipientUnknown()
        {
            ContentInfo  ci = new ContentInfo(asnNull);
            EnvelopedCms ep = new EnvelopedCms(SubjectIdentifierType.IssuerAndSerialNumber, ci);

            X509Certificate2 x509 = GetCertificate(false);
            CmsRecipient     p7r  = new CmsRecipient(SubjectIdentifierType.Unknown, x509);

            ep.Encrypt(p7r);
            byte[] encoded = ep.Encode();
#if DEBUG
            FileStream fs = File.OpenWrite("EncryptCmsRecipientUnknown.der");
            fs.Write(encoded, 0, encoded.Length);
            fs.Close();
#endif
            RoundTrip(encoded);
        }
コード例 #18
0
        //Не производит обработку ошибок, выкидывает криптографические исключения
        public MimeReader Decrypt(X509Certificate2Collection certificates)
        {
            //необязательный параметр
            if (certificates == null)
            {
                certificates = new X509Certificate2Collection();
            }
            var encodedEncryptedMessage = this.GetContent();
            var envelopedCms            = new EnvelopedCms();

            envelopedCms.Decode(encodedEncryptedMessage);
            envelopedCms.Decrypt(certificates);
            var decryptedData = envelopedCms.Encode();

            verifyValidCertificate(envelopedCms, certificates);
            return(createMimeReader(decryptedData));
        }
コード例 #19
0
        private static byte[] CreateEcmsWithAttributes(params AsnEncodedData[] attributes)
        {
            ContentInfo  contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            foreach (AsnEncodedData attribute in attributes)
            {
                ecms.UnprotectedAttributes.Add(attribute);
            }

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(cert);
                ecms.Encrypt(cmsRecipient);
            }
            byte[] encodedMessage = ecms.Encode();
            return(encodedMessage);
        }
コード例 #20
0
        public void EncryptAnswer(byte[] answerData)
        {
            X509Certificate2 certificate = GetAnswerCertificate();

            ContentInfo  contentInfo  = new ContentInfo(answerData);
            EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);
            CmsRecipient recipient    = new CmsRecipient(
                SubjectIdentifierType.IssuerAndSerialNumber,
                certificate);

            envelopedCms.Encrypt(recipient);
            byte[] answer = envelopedCms.Encode();

            dataEncrypted        = Convert.ToBase64String(answer);
            sessionKeyIV         = String.Empty;
            sessionKeyDiversData = String.Empty;
            encryptedSessionKey  = String.Empty;
        }
コード例 #21
0
        /// <summary>
        /// Encrypts the string supplied as -content on cmd-line, and encodes in base64
        /// </summary>
        private static string Encrypt()
        {
            X509Certificate2 cert = new X509Certificate2(certFileName);

            string      content      = GetString(contentToEncrypt);
            var         contentBytes = Encoding.UTF8.GetBytes(content);
            ContentInfo contentInfo  = new ContentInfo(contentBytes);

            content      = null;
            contentBytes = null;

            EnvelopedCms envelope = new EnvelopedCms(contentInfo);

            envelope.Encrypt(new CmsRecipient(cert));
            string encryptedContent = Convert.ToBase64String(envelope.Encode());

            return(encryptedContent);
        }
コード例 #22
0
ファイル: Secret.cs プロジェクト: stahir80/Azure
        public static string Decrypt(string value)
        {
            try
            {
                byte[]       data = Convert.FromBase64String(value);
                EnvelopedCms cms  = new EnvelopedCms();
                cms.Decode(data);

                var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                cms.Decrypt(store.Certificates);
                return(Encoding.UTF8.GetString(cms.Encode()));
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
            }
            return(string.Empty);
        }
コード例 #23
0
        public static void PostDecrypt_Encode(bool useExplicitPrivateKey)
        {
            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.
                }
                RecipientInfoCollection r = ecms.RecipientInfos;

                if (useExplicitPrivateKey)
                {
#if NETCOREAPP
                    ecms.Decrypt(r[0], cer.GetRSAPrivateKey());
#else
                    Assert.True(false, "Should not run on this platform");
#endif
                }
                else
                {
                    X509Certificate2Collection extraStore = new X509Certificate2Collection(cer);
                    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);
            }
        }
コード例 #24
0
        /// <summary>
        /// Decrypt the encoded EnvelopedCms message.
        /// </summary>
        /// <param name="encodedEnvelopedCms">Array of bytes containing the encrypted message</param>
        /// <returns>Array of bytes containing the decrypted message</returns>
        protected Byte[] DecryptMsg(byte[] encodedEnvelopedCms)
        {
            //  Prepare object in which to decode and decrypt.
            EnvelopedCms envelopedCms = new EnvelopedCms();

            //  Decode the message.
            envelopedCms.Decode(encodedEnvelopedCms);

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

            //  Decrypt the message for the single recipient. Note that the following call to the Decrypt method
            //  accomplishes the same result: envelopedCms.Decrypt();
            //Console.Write("Decrypting Data ... ");
            envelopedCms.Decrypt(envelopedCms.RecipientInfos[0]);
            //Console.WriteLine("Done.");

            return(envelopedCms.Encode());
        }
コード例 #25
0
        public static void EncryptionAlgorithmAes128_IgnoresKeyLength()
        {
            // For .NET Framework compat, static key length ciphers ignore the key lengths supplied
            AlgorithmIdentifier algorithm   = new AlgorithmIdentifier(new Oid(Oids.Aes128), 3);
            ContentInfo         contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
            EnvelopedCms        ecms        = new EnvelopedCms(contentInfo, algorithm);

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

            ecms.Decode(encodedMessage);

            Assert.Equal(Oids.Aes128, ecms.ContentEncryptionAlgorithm.Oid.Value);
            Assert.Equal(0, ecms.ContentEncryptionAlgorithm.KeyLength);
        }
コード例 #26
0
        public void EncryptToNegativeSerialNumber()
        {
            CertLoader negativeSerial = Certificates.NegativeSerialNumber;

            const string expectedSerial = "FD319CB1514B06AF49E00522277E43C8";

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

            using (X509Certificate2 cert = negativeSerial.GetCertificate())
            {
                Assert.Equal(expectedSerial, cert.SerialNumber);

                CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
                cms.Encrypt(recipient);
            }

            EnvelopedCms cms2 = new EnvelopedCms();

            cms2.Decode(cms.Encode());

            RecipientInfoCollection recipients = cms2.RecipientInfos;

            Assert.Equal(1, recipients.Count);

            RecipientInfo recipientInfo = recipients[0];

            Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, recipientInfo.RecipientIdentifier.Type);

            X509IssuerSerial issuerSerial = (X509IssuerSerial)recipientInfo.RecipientIdentifier.Value;

            Assert.Equal(expectedSerial, issuerSerial.SerialNumber);

            using (X509Certificate2 cert = negativeSerial.TryGetCertificateWithPrivateKey())
            {
                Assert.Equal(expectedSerial, cert.SerialNumber);

                cms2.Decrypt(new X509Certificate2Collection(cert));
            }

            Assert.Equal(content, cms2.ContentInfo.Content);
        }
コード例 #27
0
        public static void ZeroLengthContent_RoundTrip()
        {
            ContentInfo  contentInfo = new ContentInfo(Array.Empty <byte>());
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(cert);
                try
                {
                    ecms.Encrypt(cmsRecipient);
                }
                catch (CryptographicException) when(PlatformDetection.IsFullFramework)  // Expected on full FX
                {
                }
            }
            byte[] encodedMessage = ecms.Encode();
            ValidateZeroLengthContent(encodedMessage);
        }
コード例 #28
0
        public static void PostDecode_Encode()
        {
            byte[] encodedMessage =
                ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
                 + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
                 + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
                 + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
                 + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
                 + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();

            EnvelopedCms ecms = new EnvelopedCms();

            ecms.Decode(encodedMessage);

            // This should really have thrown an InvalidOperationException. Instead, you get... something back.
            byte[] expectedGarbage = "35edc437e31d0b70".HexToByteArray();
            byte[] garbage         = ecms.Encode();
            AssertEncryptedContentEqual(expectedGarbage, garbage);
        }
コード例 #29
0
        Stream Envelope(RealCmsRecipientCollection recipients, Stream content, EncryptionAlgorithm encryptionAlgorithm)
        {
            var contentInfo = new ContentInfo(ReadAllBytes(content));
            RealAlgorithmIdentifier algorithm;

            switch (encryptionAlgorithm)
            {
            case EncryptionAlgorithm.Aes256:
                algorithm = new RealAlgorithmIdentifier(new Oid(CmsEnvelopedGenerator.Aes256Cbc));
                break;

            case EncryptionAlgorithm.Aes192:
                algorithm = new RealAlgorithmIdentifier(new Oid(CmsEnvelopedGenerator.Aes192Cbc));
                break;

            case EncryptionAlgorithm.Aes128:
                algorithm = new RealAlgorithmIdentifier(new Oid(CmsEnvelopedGenerator.Aes128Cbc));
                break;

            case EncryptionAlgorithm.RC2128:
                algorithm = new RealAlgorithmIdentifier(new Oid(CmsEnvelopedGenerator.RC2Cbc), 128);
                break;

            case EncryptionAlgorithm.RC264:
                algorithm = new RealAlgorithmIdentifier(new Oid(CmsEnvelopedGenerator.RC2Cbc), 64);
                break;

            case EncryptionAlgorithm.RC240:
                algorithm = new RealAlgorithmIdentifier(new Oid(CmsEnvelopedGenerator.RC2Cbc), 40);
                break;

            default:
                algorithm = new RealAlgorithmIdentifier(new Oid(CmsEnvelopedGenerator.DesEde3Cbc));
                break;
            }

            var envelopedData = new EnvelopedCms(contentInfo, algorithm);

            envelopedData.Encrypt(recipients);

            return(new MemoryStream(envelopedData.Encode(), false));
        }
コード例 #30
0
ファイル: EdgeCasesTests.cs プロジェクト: mauriciolsrj/corefx
        public static void ZeroLengthContent_RoundTrip()
        {
            ContentInfo  contentInfo = new ContentInfo(Array.Empty <byte>());
            EnvelopedCms ecms        = new EnvelopedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                CmsRecipient cmsRecipient = new CmsRecipient(cert);
                try
                {
                    ecms.Encrypt(cmsRecipient);
                }
                catch (CryptographicException e)
                {
                    throw new Exception("ecms.Encrypt() threw " + e.Message + ".\nIf you're running on the desktop CLR, this is actually an expected result.");
                }
            }
            byte[] encodedMessage = ecms.Encode();
            ValidateZeroLengthContent(encodedMessage);
        }