public void CopyTo(RecipientInfo[] array, int index)
 {
 }
        public unsafe sealed override ContentInfo?TryDecrypt(
            RecipientInfo recipientInfo,
            X509Certificate2?cert,
            AsymmetricAlgorithm?privateKey,
            X509Certificate2Collection originatorCerts,
            X509Certificate2Collection extraStore,
            out Exception?exception)
        {
            Debug.Assert((cert != null) ^ (privateKey != null));

            if (privateKey != null)
            {
                RSA?key = privateKey as RSA;

                if (key == null)
                {
                    exception = new CryptographicException(SR.Cryptography_Cms_Ktri_RSARequired);
                    return(null);
                }

                ContentInfo contentInfo = _hCryptMsg.GetContentInfo();
                byte[]? cek = AnyOS.ManagedPkcsPal.ManagedKeyTransPal.DecryptCekCore(
                    cert,
                    key,
                    recipientInfo.EncryptedKey,
                    recipientInfo.KeyEncryptionAlgorithm.Oid.Value,
                    recipientInfo.KeyEncryptionAlgorithm.Parameters,
                    out exception);

                // Pin CEK to prevent it from getting copied during heap compaction.
                fixed(byte *pinnedCek = cek)
                {
                    try
                    {
                        if (exception != null)
                        {
                            return(null);
                        }

                        return(AnyOS.ManagedPkcsPal.ManagedDecryptorPal.TryDecryptCore(
                                   cek !,
                                   contentInfo.ContentType.Value !,
                                   contentInfo.Content,
                                   _contentEncryptionAlgorithm,
                                   out exception));
                    }
                    finally
                    {
                        if (cek != null)
                        {
                            Array.Clear(cek, 0, cek.Length);
                        }
                    }
                }
            }

            Debug.Assert(recipientInfo != null);
            Debug.Assert(cert != null);
            Debug.Assert(originatorCerts != null);
            Debug.Assert(extraStore != null);

            CryptKeySpec keySpec;

            exception = TryGetKeySpecForCertificate(cert, out keySpec);
            if (exception != null)
            {
                return(null);
            }

            // .NET Framework compat: We pass false for "silent" here (thus allowing crypto providers to display UI.)
            const bool Silent = false;
            // Note: Using CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG rather than CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG
            // because wrapping an NCrypt wrapper over CAPI keys unconditionally causes some legacy features
            // (such as RC4 support) to break.
            const bool PreferNCrypt = false;

            using (SafeProvOrNCryptKeyHandle? hKey = PkcsPalWindows.GetCertificatePrivateKey(cert, Silent, PreferNCrypt, out _, out exception))
            {
                if (hKey == null)
                {
                    return(null);
                }

                RecipientInfoType type = recipientInfo.Type;
                switch (type)
                {
                case RecipientInfoType.KeyTransport:
                    exception = TryDecryptTrans((KeyTransRecipientInfo)recipientInfo, hKey, keySpec);
                    break;

                case RecipientInfoType.KeyAgreement:
                    exception = TryDecryptAgree((KeyAgreeRecipientInfo)recipientInfo, hKey, keySpec, originatorCerts, extraStore);
                    break;

                default:
                    // Since only the framework can construct RecipientInfo's, we're at fault if we get here. So it's okay to assert and throw rather than
                    // returning to the caller.
                    Debug.Fail($"Unexpected RecipientInfoType: {type}");
                    throw new NotSupportedException();
                }

                if (exception != null)
                {
                    return(null);
                }

                // If we got here, we successfully decrypted. Return the decrypted content.
                return(_hCryptMsg.GetContentInfo());
            }
        }
 public void Decrypt(RecipientInfo recipientInfo)
 {
 }
 public void Decrypt(RecipientInfo recipientInfo, System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraStore)
 {
 }
Exemple #5
0
        private static void CollectEventsAndRecipients(RecipientsType type, ArrayList recipients, Hashtable events, Hashtable users, string param1, DateTime param2)
        {
            EventInfo eInfo;
            UserInfo uInfo;

            // Load recipients info
            using (IDataReader reader = GetRecipientsReader(type, param1, param2))
            {
                RecipientInfo rInfo;
                while (reader.Read())
                {
                    rInfo = new RecipientInfo();
                    rInfo.Load(reader);
                    recipients.Add(rInfo);
                }
            }

            foreach (RecipientInfo rInfo in recipients)
            {
                eInfo = (EventInfo)events[rInfo.SystemEventId];
                if (eInfo == null)
                {
                    // Load events info
                    using (IDataReader reader = DBSystemEvents.GetEvent(rInfo.SystemEventId))
                    {
                        while (reader.Read())
                        {
                            eInfo = new EventInfo();
                            eInfo.Load(reader);
                            events[rInfo.SystemEventId] = eInfo;
                        }
                    }
                }

                if (rInfo.UserId > 0)
                {
                    eInfo.AddRecipient(rInfo.RecipientId);
                    eInfo.AddUser(rInfo.UserId);

                    uInfo = (UserInfo)users[rInfo.UserId];
                    if (uInfo == null)
                    {
                        uInfo = new UserInfo();
                        uInfo.Load(rInfo.UserId);
                        users[rInfo.UserId] = uInfo;
                    }
                    uInfo.AddEvent(eInfo);
                    uInfo.AddRecipient(rInfo);
                }
            }
        }
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.RecipientInfoCollection.CopyTo(System.Security.Cryptography.Pkcs.RecipientInfo[],System.Int32)"/> method copies the <see cref="T:System.Security.Cryptography.Pkcs.RecipientInfoCollection"/> collection to a <see cref="T:System.Security.Cryptography.Pkcs.RecipientInfo"/> array.
 /// </summary>
 /// <param name="array">An array of <see cref="T:System.Security.Cryptography.Pkcs.RecipientInfo"/> objects where the <see cref="T:System.Security.Cryptography.Pkcs.RecipientInfoCollection"/> collection is to be copied.</param><param name="index">The zero-based index in <paramref name="array"/> where the <see cref="T:System.Security.Cryptography.Pkcs.RecipientInfoCollection"/> collection is copied.</param><exception cref="T:System.ArgumentException">One of the arguments provided to a method was not valid.</exception><exception cref="T:System.ArgumentNullException">A null reference was passed to a method that does not accept it as a valid argument. </exception><exception cref="T:System.ArgumentOutOfRangeException">The value of an argument was outside the allowable range of values as defined by the called method.</exception>
 public void CopyTo(RecipientInfo[] array, int index)
 {
     this.CopyTo((Array)array, index);
 }
        private async Task <Campaign> AddAnnouncementToDB(Activity activity, CreateNewAnnouncementData data, string tenantId)
        {
            Campaign announcement = new Campaign()
            {
                IsAcknowledgementRequested = bool.Parse(data.Acknowledge),
                IsContactAllowed           = bool.Parse(data.AllowContactIns),
                ShowAllDetailsButton       = true,
                Title       = data.Title,
                SubTitle    = data.SubTitle,
                CreatedTime = DateTime.Now,
                Author      = new Author()
                {
                    EmailId = data.AuthorAlias
                },
                Preview     = data.Preview,
                Body        = data.Body,
                ImageUrl    = data.Image,
                Sensitivity = (MessageSensitivity)Enum.Parse(typeof(MessageSensitivity), data.MessageType),
                OwnerId     = await GetUserEmailId(activity)
            };

            announcement.Id       = string.IsNullOrEmpty(data.Id) ? Guid.NewGuid().ToString() : data.Id; // Assing the Existing Announcement Id
            announcement.TenantId = tenantId;

            if (!string.IsNullOrEmpty(data.Id))
            {
                var dbAnnouncement = await Cache.Announcements.GetItemAsync(data.Id);

                if (dbAnnouncement.Status == Status.Scheduled)
                {
                    announcement.Schedule = dbAnnouncement.Schedule;
                    Scheduler.RemoveSchedule(announcement.Schedule.ScheduleId);// Clear the schedule
                    // Remove schedule
                }
            }
            var recipients = new RecipientInfo
            {
                ServiceUrl = activity.ServiceUrl,
                TenantId   = tenantId
            };

            if (data.Channels != null)
            {
                var channels = data.Channels.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var channelInfo in channels)
                {
                    var info      = channelInfo.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    var teamId    = info[0];
                    var channelId = info[1];
                    var team      = await Cache.Teams.GetItemAsync(teamId);

                    recipients.Channels.Add(new ChannelRecipient()
                    {
                        TeamId  = teamId,
                        Channel = new RecipientDetails()
                        {
                            Id = channelId,
                        },
                        Members = team?.Members
                    });
                }
            }

            if (data.Groups != null)
            {
                var groups = data.Groups.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var groupId in groups)
                {
                    var groupDetailsFromDB = await Cache.Groups.GetItemAsync(groupId);

                    var recipientGroup = new GroupRecipient()
                    {
                        GroupId = groupId
                    };
                    foreach (var userEmailId in groupDetailsFromDB.Users)
                    {
                        recipientGroup.Users.Add(new RecipientDetails()
                        {
                            Id = userEmailId,
                        });
                    }
                    recipients.Groups.Add(recipientGroup);
                }
            }
            announcement.Recipients = recipients;
            announcement.Status     = Status.Draft;

            var tenantDetails = await Cache.Tenants.GetItemAsync(tenantId);

            // Fetch author Email ID
            if (tenantDetails.IsAdminConsented)
            {
                var token = await GraphHelper.GetAccessToken(tenantId, ApplicationSettings.AppId, ApplicationSettings.AppSecret);

                GraphHelper helper      = new GraphHelper(token);
                var         userDetails = await helper.GetUser(announcement.Author.EmailId);

                if (userDetails != null)
                {
                    announcement.Author.Name         = userDetails.DisplayName;
                    announcement.Author.Role         = userDetails.JobTitle ?? userDetails.UserPrincipalName;
                    announcement.Author.ProfilePhoto = await helper.GetUserProfilePhoto(tenantId, userDetails.Id);
                }
                else
                {
                    announcement.Author.Name         = announcement.Author.EmailId;
                    announcement.Author.ProfilePhoto = ApplicationSettings.BaseUrl + "/Resources/Person.png";
                }
            }

            if (string.IsNullOrEmpty(data.Id))
            {
                await Cache.Announcements.AddOrUpdateItemAsync(announcement.Id, announcement);// Push to DB

                tenantDetails.Announcements.Add(announcement.Id);
                await Cache.Tenants.AddOrUpdateItemAsync(tenantDetails.Id, tenantDetails); // Update tenat catalog
            }
            else
            {
                await Cache.Announcements.AddOrUpdateItemAsync(data.Id, announcement);// Push updated data DB
            }
            return(announcement);
        }
	public void Decrypt(RecipientInfo recipientInfo, System.Security.Cryptography.X509Certificates.X509Certificate2Collection extraStore) {}
Exemple #9
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.EnvelopedCms.Decrypt(System.Security.Cryptography.Pkcs.RecipientInfo,System.Security.Cryptography.X509Certificates.X509Certificate2Collection)"/> method decrypts the contents of the decoded enveloped CMS/PKCS #7 message by using the private key associated with the certificate identified by the specified recipient information and by using the specified certificate collection.  The <see cref="M:System.Security.Cryptography.Pkcs.EnvelopedCms.Decrypt(System.Security.Cryptography.Pkcs.RecipientInfo,System.Security.Cryptography.X509Certificates.X509Certificate2Collection)"/> method searches the specified certificate collection and the My certificate store for the proper certificate to use for the decryption.
 /// </summary>
 /// <param name="recipientInfo">A <see cref="T:System.Security.Cryptography.Pkcs.RecipientInfo"/> object that represents the recipient information to use for the decryption.</param><param name="extraStore">An <see cref="T:System.Security.Cryptography.X509Certificates.X509Certificate2Collection"/> collection that represents additional certificates to use for the decryption. The <see cref="M:System.Security.Cryptography.Pkcs.EnvelopedCms.Decrypt(System.Security.Cryptography.Pkcs.RecipientInfo,System.Security.Cryptography.X509Certificates.X509Certificate2Collection)"/> method searches this certificate collection and the My certificate store for the proper certificate to use for the decryption.</param><exception cref="T:System.ArgumentNullException">A null reference was passed to a method that does not accept it as a valid argument.</exception><exception cref="T:System.Security.Cryptography.CryptographicException">A cryptographic operation could not be completed.</exception><exception cref="T:System.InvalidOperationException">A method call was invalid for the object's current state.</exception>
 public void Decrypt(RecipientInfo recipientInfo, X509Certificate2Collection extraStore)
 {
     if (recipientInfo == null)
         throw new ArgumentNullException("recipientInfo");
     if (extraStore == null)
         throw new ArgumentNullException("extraStore");
     this.DecryptContent(new RecipientInfoCollection(recipientInfo), extraStore);
 }
Exemple #10
0
 private static unsafe int GetCspParams(RecipientInfo recipientInfo, X509Certificate2Collection extraStore, ref EnvelopedCms.CMSG_DECRYPT_PARAM cmsgDecryptParam)
 {
     int num = -2146889717;
     System.Security.Cryptography.SafeCertContextHandle certContextHandle = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle;
     System.Security.Cryptography.SafeCertStoreHandle hCertStore = EnvelopedCms.BuildDecryptorStore(extraStore);
     switch (recipientInfo.Type)
     {
         case RecipientInfoType.KeyTransport:
             if (recipientInfo.SubType == RecipientSubType.Pkcs7KeyTransport)
             {
                 certContextHandle = CAPI.CertFindCertificateInStore(hCertStore, 65537U, 0U, 720896U, recipientInfo.pCmsgRecipientInfo.DangerousGetHandle(), System.Security.Cryptography.SafeCertContextHandle.InvalidHandle);
                 break;
             }
             else
             {
                 CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO transRecipientInfo = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO)recipientInfo.CmsgRecipientInfo;
                 certContextHandle = CAPI.CertFindCertificateInStore(hCertStore, 65537U, 0U, 1048576U, new IntPtr((void*)&transRecipientInfo.RecipientId), System.Security.Cryptography.SafeCertContextHandle.InvalidHandle);
                 break;
             }
         case RecipientInfoType.KeyAgreement:
             CAPI.CERT_ID recipientId = ((KeyAgreeRecipientInfo)recipientInfo).RecipientId;
             certContextHandle = CAPI.CertFindCertificateInStore(hCertStore, 65537U, 0U, 1048576U, new IntPtr((void*)&recipientId), System.Security.Cryptography.SafeCertContextHandle.InvalidHandle);
             break;
         default:
             num = -2147483647;
             break;
     }
     if (certContextHandle != null && !certContextHandle.IsInvalid)
     {
         SafeCryptProvHandle invalidHandle = SafeCryptProvHandle.InvalidHandle;
         uint pdwKeySpec = 0U;
         bool pfCallerFreeProv = false;
         CspParameters parameters = new CspParameters();
         if (!X509Utils.GetPrivateKeyInfo(certContextHandle, ref parameters))
             throw new CryptographicException(Marshal.GetLastWin32Error());
         if (string.Compare(parameters.ProviderName, "Microsoft Base Cryptographic Provider v1.0", StringComparison.OrdinalIgnoreCase) == 0 && (CAPI.CryptAcquireContext(out invalidHandle, parameters.KeyContainerName, "Microsoft Enhanced Cryptographic Provider v1.0", 1U, 0U) || CAPI.CryptAcquireContext(out invalidHandle, parameters.KeyContainerName, "Microsoft Strong Cryptographic Provider", 1U, 0U)))
             cmsgDecryptParam.safeCryptProvHandle = invalidHandle;
         cmsgDecryptParam.safeCertContextHandle = certContextHandle;
         cmsgDecryptParam.keySpec = (uint)parameters.KeyNumber;
         num = 0;
         if (invalidHandle == null || invalidHandle.IsInvalid)
         {
             if (CAPI.CAPISafe.CryptAcquireCertificatePrivateKey(certContextHandle, 6U, IntPtr.Zero, out invalidHandle, out pdwKeySpec, out pfCallerFreeProv))
             {
                 if (!pfCallerFreeProv)
                     GC.SuppressFinalize((object)invalidHandle);
                 cmsgDecryptParam.safeCryptProvHandle = invalidHandle;
             }
             else
                 num = Marshal.GetHRForLastWin32Error();
         }
     }
     return num;
 }
Exemple #11
0
 /// <summary>
 /// The <see cref="M:System.Security.Cryptography.Pkcs.EnvelopedCms.Decrypt(System.Security.Cryptography.Pkcs.RecipientInfo)"/> method decrypts the contents of the decoded enveloped CMS/PKCS #7 message by using the private key associated with the certificate identified by the specified recipient information.
 /// </summary>
 /// <param name="recipientInfo">A <see cref="T:System.Security.Cryptography.Pkcs.RecipientInfo"/> object that represents the recipient information that identifies the certificate associated with the private key to use for the decryption.</param><exception cref="T:System.ArgumentNullException">A null reference was passed to a method that does not accept it as a valid argument. </exception><exception cref="T:System.Security.Cryptography.CryptographicException">A cryptographic operation could not be completed.</exception><exception cref="T:System.InvalidOperationException">A method call was invalid for the object's current state.</exception>
 public void Decrypt(RecipientInfo recipientInfo)
 {
     if (recipientInfo == null)
         throw new ArgumentNullException("recipientInfo");
     this.DecryptContent(new RecipientInfoCollection(recipientInfo), (X509Certificate2Collection)null);
 }
Exemple #12
0
 /// <summary>
 /// Converts the recipient.
 /// </summary>
 /// <param name="recipient">The recipient.</param>
 /// <returns></returns>
 private EchoSignRecipientInfo ConvertRecipient(RecipientInfo recipient)
 {
     return(new EchoSignRecipientInfo {
         email = recipient.email
     });
 }
 internal RecipientInfoCollection(RecipientInfo recipientInfo)
 {
     this.m_safeCryptMsgHandle = SafeCryptMsgHandle.InvalidHandle;
     this.m_recipientInfos = new ArrayList(1);
     this.m_recipientInfos.Add((object)recipientInfo);
 }
Exemple #14
0
        private ITestResult EnvelopedTest()
        {
            try
            {
                // Key trans
                ContentInfo info = ContentInfo.GetInstance(
                    Asn1Object.FromByteArray(envDataKeyTrns));
                EnvelopedData envData = EnvelopedData.GetInstance(info.Content);
                Asn1Set       s       = envData.RecipientInfos;

                if (s.Count != 1)
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong number of recipients"));
                }

                RecipientInfo recip = RecipientInfo.GetInstance(s[0]);

                if (recip.Info is KeyTransRecipientInfo)
                {
                    KeyTransRecipientInfo inf = KeyTransRecipientInfo.GetInstance(recip.Info);

                    inf = new KeyTransRecipientInfo(inf.RecipientIdentifier, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

                    s = new DerSet(new RecipientInfo(inf));
                }
                else
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong recipient type"));
                }

                envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
                info    = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

                if (!Arrays.AreEqual(info.GetEncoded(), envDataKeyTrns))
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped failed to re-encode"));
                }


                // KEK
                info = ContentInfo.GetInstance(
                    Asn1Object.FromByteArray(envDataKEK));
                envData = EnvelopedData.GetInstance(info.Content);
                s       = envData.RecipientInfos;

                if (s.Count != 1)
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong number of recipients"));
                }

                recip = RecipientInfo.GetInstance(s[0]);

                if (recip.Info is KekRecipientInfo)
                {
                    KekRecipientInfo inf = KekRecipientInfo.GetInstance(recip.Info);

                    inf = new KekRecipientInfo(inf.KekID, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

                    s = new DerSet(new RecipientInfo(inf));
                }
                else
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong recipient type"));
                }

                envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
                info    = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

                if (!Arrays.AreEqual(info.GetEncoded(), envDataKEK))
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped failed to re-encode"));
                }

                // Nested NDEF problem
                Asn1StreamParser    asn1In = new Asn1StreamParser(new MemoryStream(envDataNestedNDEF, false));
                ContentInfoParser   ci     = new ContentInfoParser((Asn1SequenceParser)asn1In.ReadObject());
                EnvelopedDataParser ed     = new EnvelopedDataParser((Asn1SequenceParser)ci
                                                                     .GetContent(Asn1Tags.Sequence));
                Touch(ed.Version);
                ed.GetOriginatorInfo();
                ed.GetRecipientInfos().ToAsn1Object();
                EncryptedContentInfoParser eci = ed.GetEncryptedContentInfo();
                Touch(eci.ContentType);
                Touch(eci.ContentEncryptionAlgorithm);

                Stream dataIn = ((Asn1OctetStringParser)eci.GetEncryptedContent(Asn1Tags.OctetString))
                                .GetOctetStream();
                Streams.Drain(dataIn);
                dataIn.Close();

                // Test data doesn't have unprotected attrs, bug was being thrown by this call
                Asn1SetParser upa = ed.GetUnprotectedAttrs();
                if (upa != null)
                {
                    upa.ToAsn1Object();
                }

                return(new SimpleTestResult(true, Name + ": Okay"));
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": CMS enveloped failed - " + e.ToString(), e));
            }
        }
Exemple #15
0
 /// <summary>
 /// Attempt to decrypt the CMS using the specified "cert". If successful, return the ContentInfo that contains the decrypted content. If unsuccessful, return null and set "exception"
 /// to a valid Exception object. Do not throw the exception as EnvelopedCms will want to continue decryption attempts against other recipients. Only if all the recipients fail to
 /// decrypt will then EnvelopedCms throw the exception from the last failed attempt.
 /// </summary>
 public abstract ContentInfo TryDecrypt(RecipientInfo recipientInfo, X509Certificate2 cert, X509Certificate2Collection originatorCerts, X509Certificate2Collection extraStore, out Exception exception);
	public void Decrypt(RecipientInfo recipientInfo) {}
            public override unsafe ContentInfo TryDecrypt(
                RecipientInfo recipientInfo,
                X509Certificate2 cert,
                X509Certificate2Collection originatorCerts,
                X509Certificate2Collection extraStore,
                out Exception exception)
            {
                // When encryptedContent is null Windows seems to decrypt the CEK first,
                // then return a 0 byte answer.

                byte[] cek;

                if (recipientInfo.Pal is ManagedKeyTransPal ktri)
                {
                    cek = ktri.DecryptCek(cert, out exception);
                }
                else
                {
                    exception = new CryptographicException(
                        SR.Cryptography_Cms_RecipientType_NotSupported,
                        recipientInfo.Type.ToString());

                    return(null);
                }

                byte[] decrypted;

                // Pin CEK to prevent it from getting copied during heap compaction.
                fixed(byte *pinnedCek = cek)
                {
                    try
                    {
                        if (exception != null)
                        {
                            return(null);
                        }

                        ReadOnlyMemory <byte>?encryptedContent = _envelopedData.EncryptedContentInfo.EncryptedContent;

                        if (encryptedContent == null)
                        {
                            exception = null;

                            return(new ContentInfo(
                                       new Oid(_envelopedData.EncryptedContentInfo.ContentType),
                                       Array.Empty <byte>()));
                        }

                        decrypted = DecryptContent(encryptedContent.Value, cek, out exception);
                    }
                    finally
                    {
                        Array.Clear(cek, 0, cek.Length);
                    }
                }

                if (exception != null)
                {
                    return(null);
                }

                if (_envelopedData.EncryptedContentInfo.ContentType == Oids.Pkcs7Data)
                {
                    byte[] tmp = null;

                    try
                    {
                        AsnReader reader = new AsnReader(decrypted, AsnEncodingRules.BER);

                        if (reader.TryGetPrimitiveOctetStringBytes(out ReadOnlyMemory <byte> contents))
                        {
                            decrypted = contents.ToArray();
                        }
                        else
                        {
                            tmp = ArrayPool <byte> .Shared.Rent(decrypted.Length);

                            if (reader.TryCopyOctetStringBytes(tmp, out int written))
                            {
                                Span <byte> innerContents = new Span <byte>(tmp, 0, written);
                                decrypted = innerContents.ToArray();
                                innerContents.Clear();
                            }
                            else
                            {
                                Debug.Fail("Octet string grew during copy");
                                // If this happens (which requires decrypted was overwritten, which
                                // shouldn't be possible), just leave decrypted alone.
                            }
                        }
                    }
                    catch (CryptographicException)
                    {
                    }
                    finally
                    {
                        if (tmp != null)
                        {
                            // Already cleared
                            ArrayPool <byte> .Shared.Return(tmp);
                        }
                    }
                }

                exception = null;
                return(new ContentInfo(
                           new Oid(_envelopedData.EncryptedContentInfo.ContentType),
                           decrypted));
            }
Exemple #18
0
 internal void AddRecipient(RecipientInfo ri)
 {
     if (!Recipients.Contains(ri))
         Recipients.Add(ri);
 }
        private static void ReadRecipientInfo(global::System.Collections.IList infos, RecipientInfo info, CmsSecureReadable secureReadable)
        {
            Asn1Encodable info2 = info.Info;

            if (info2 is KeyTransRecipientInfo)
            {
                infos.Add((object)new KeyTransRecipientInformation((KeyTransRecipientInfo)info2, secureReadable));
            }
            else if (info2 is KekRecipientInfo)
            {
                infos.Add((object)new KekRecipientInformation((KekRecipientInfo)info2, secureReadable));
            }
            else if (info2 is KeyAgreeRecipientInfo)
            {
                KeyAgreeRecipientInformation.ReadRecipientInfo(infos, (KeyAgreeRecipientInfo)info2, secureReadable);
            }
            else if (info2 is PasswordRecipientInfo)
            {
                infos.Add((object)new PasswordRecipientInformation((PasswordRecipientInfo)info2, secureReadable));
            }
        }
Exemple #20
0
        private static Message GetMessage(
			Hashtable messages,
			AlertTemplate tmpl,
			RecipientInfo rInfo,
			EventInfo eInfo,
			UserInfo uInfo)
        {
            Message ret = null;

            string key = string.Format("{0}|{1}|{2}", tmpl.Key, eInfo.EventId, uInfo.TimeZoneId);
            ret = (Message)messages[key];
            if (ret == null || uInfo.IsExternal)
            {
                ArrayList variables = eInfo.GetVariablesArrayList(uInfo.LanguageId);

                ret = GetMessage(tmpl.Subject, tmpl.Body, uInfo, variables, eInfo.ObjectTypeId, eInfo.ObjectId, eInfo.ObjectUid);
                if (!uInfo.IsExternal)
                    messages[key] = ret;
            }

            return ret;
        }
        public CmsEnvelopedDataParser(
            Stream envelopedData)
            : base(envelopedData)
        {
            this._attrNotRead  = true;
            this.envelopedData = new EnvelopedDataParser(
                (Asn1SequenceParser)this.contentInfo.GetContent(Asn1Tags.Sequence));

            // TODO Validate version?
            //			DerInteger version = this.envelopedData.Version;

            //
            // load the RecipientInfoStore
            //
            Asn1SetParser s         = this.envelopedData.GetRecipientInfos();
            IList         baseInfos = new ArrayList();

            IAsn1Convertible entry;

            while ((entry = s.ReadObject()) != null)
            {
                baseInfos.Add(RecipientInfo.GetInstance(entry.ToAsn1Object()));
            }

            //
            // read the encrypted content info
            //
            EncryptedContentInfoParser encInfo = this.envelopedData.GetEncryptedContentInfo();

            this._encAlg = encInfo.ContentEncryptionAlgorithm;

            //
            // prime the recipients
            //
            IList  infos      = new ArrayList();
            Stream dataStream = ((Asn1OctetStringParser)encInfo.GetEncryptedContent(Asn1Tags.OctetString)).GetOctetStream();

            foreach (Asn1.Cms.RecipientInfo info in baseInfos)
            {
                Asn1Encodable recipInfo = info.Info;
                if (recipInfo is Asn1.Cms.KeyTransRecipientInfo)
                {
                    infos.Add(new KeyTransRecipientInformation(
                                  (KeyTransRecipientInfo)recipInfo, _encAlg, dataStream));
                }
                else if (recipInfo is Asn1.Cms.KekRecipientInfo)
                {
                    infos.Add(new KekRecipientInformation(
                                  (KekRecipientInfo)recipInfo, _encAlg, dataStream));
                }
                else if (recipInfo is KeyAgreeRecipientInfo)
                {
                    infos.Add(new KeyAgreeRecipientInformation(
                                  (KeyAgreeRecipientInfo)recipInfo, _encAlg, dataStream));
                }
                else if (recipInfo is PasswordRecipientInfo)
                {
                    infos.Add(new PasswordRecipientInformation(
                                  (PasswordRecipientInfo)recipInfo, _encAlg, dataStream));
                }
            }

            this.recipientInfoStore = new RecipientInformationStore(infos);
        }