Ejemplo n.º 1
0
        public PrivatePublicKey(string applicationName)
        {
            ApplicationName = applicationName;

            using (var encryption = new KeyEncryption(ApplicationName))
            {
                PublicKey  = encryption.PublicKey;
                PrivateKey = encryption.PrivateKey;
            }
        }
Ejemplo n.º 2
0
        protected override void encryptKey(ref EncryptedMessage em, Guid remoteId)
        {
            if (KeyEncryption is NoKey)
            {
                return;
            }

            em.Key     = KeyEncryption.EncryptData(em.Key, HubPublicKey?.Key);
            em.KeyType = KeyEncryption.Type;
        }
Ejemplo n.º 3
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                return(KeyEncryption.DecryptAsInt((string)reader.Value));
            }

            if (reader.ValueType == typeof(long))
            {
                return(Convert.ToInt32(reader.Value));
            }

            return(reader.Value);
        }
Ejemplo n.º 4
0
        protected override void encryptKey(ref EncryptedMessage em, Guid remoteId)
        {
            if (KeyEncryption is NoKey)
            {
                return;
            }

            if (!NodesPublicKeys.ContainsKey(remoteId))
            {
                throw new Exception(String.Format("No RSA public key for node \"{0}\" found!", remoteId.ToString()));
            }

            em.Key     = KeyEncryption.EncryptData(em.Key, NodesPublicKeys[remoteId].Key);
            em.KeyType = KeyEncryption.Type;
        }
        public void MaxKey_Win32_WithEmptyContainerName_ShouldGive_384_AsMaxKeySize()
        {
            // arrange
            var configurationMock = new Mock <ISecurityConfiguration>();

            configurationMock.Setup(x => x.OSVersionPlatform).Returns(PlatformID.Win32Windows);

            using var keyEncryption = new KeyEncryption(string.Empty, configurationMock.Object);

            // act
            var maxKeySize = keyEncryption.KeySize;

            // assert
            maxKeySize.Should().Be(384);
        }
Ejemplo n.º 6
0
        public bool DeleteEncryptionStore()
        {
            try
            {
                using (var clientKeyEncryption = new KeyEncryption(ApplicationName))
                {
                    clientKeyEncryption.Delete();
                }
            }
            catch
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 7
0
            public void ThenCreateAS4EncryptedKeySucceeds(string algorithm, string digest, string mgf)
            {
                byte[] encryptionKey = GenerateEncryptionKey();

                var keyEncryption = new KeyEncryption
                {
                    TransportAlgorithm = algorithm,
                    DigestAlgorithm    = digest,
                    MgfAlgorithm       = mgf
                };

                var keyEncryptionConfiguration = new KeyEncryptionConfiguration(GetCertificate(), keyEncryption);

                AS4EncryptedKey key =
                    AS4EncryptedKey.CreateEncryptedKeyBuilderForKey(encryptionKey, keyEncryptionConfiguration)
                    .Build();

                Assert.Equal(algorithm, key.GetEncryptionAlgorithm());
                Assert.Equal(digest, key.GetDigestAlgorithm());
                Assert.Equal(mgf, key.GetMaskGenerationFunction());
            }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyEncryptionConfiguration"/> class.
        /// </summary>
        /// <param name="encryptionCertificate">The certificate that must be used to encrypt the symmetric key.</param>
        /// <param name="keyEncryption">An instance of the <see cref="KeyEncryption"/> class that defines the algorithms that must be used for encryption</param>
        public KeyEncryptionConfiguration(X509Certificate2 encryptionCertificate,
                                          KeyEncryption keyEncryption)
        {
            if (encryptionCertificate == null)
            {
                throw new ArgumentNullException(nameof(encryptionCertificate));
            }

            if (keyEncryption == null)
            {
                throw new ArgumentNullException(nameof(keyEncryption));
            }

            EncryptionCertificate = encryptionCertificate;

            // TODO: this is now hardcoded but should be configurable via the
            //       (Sending) PMode.
            _securityTokenReferenceType = X509ReferenceType.BSTReference;

            EncryptionMethod = keyEncryption.TransportAlgorithm;
            DigestMethod     = keyEncryption.DigestAlgorithm;
            Mgf = keyEncryption.MgfAlgorithm;
        }
 /// <summary>
 /// Provides a new OpenIDConsumer object with default settings.
 /// </summary>
 public OpenIDConsumer()
 {
     // Set Defaults
     Init();
     this.DumbMode = false;
     this.authmode = AuthorizationMode.Stateful;
     this.keyenc = KeyEncryption.DHSHA256;
     CleanupAssociations();
 }
Ejemplo n.º 10
0
        public async Task <bool> CheckFirstTimeAndDownload()
        {
            UserDialogs.Instance.ShowLoading("Loading...");
            var username = Convert.ToString(Application.Current.Properties["UserName"]);
            var password = Convert.ToString(Application.Current.Properties["PassID"]);

            try
            {
                var response = await services.LoginUser(new { username = username.Trim(), password = password.Trim() });

                if (response != null)
                {
                    if (!string.IsNullOrEmpty(response.StatusCode))
                    {
                        UserDialogs.Instance.HideLoading();
                        await UserDialogs.Instance.AlertAsync("Download Failed!");

                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                UserDialogs.Instance.HideLoading();
                if (!string.IsNullOrEmpty(ex.Message) && ex.Message == "User Don't have BDI product")
                {
                    await UserDialogs.Instance.AlertAsync("You Don't have BDI product access. Please contact Admin");
                }
                else
                {
                    await UserDialogs.Instance.AlertAsync("Download Failed!");
                }
                return(false);
            }
            ICommonDataService commonDataService = DependencyService.Get <ICommonDataService>();
            var lstlocalLocations     = default(List <Location>);
            var needtoDeleteLocations = default(List <Location>);

            UserDialogs.Instance.HideLoading();
            await PopupNavigation.Instance.PushAsync(new SyncingPopupView()
            {
                BindingContext = this
            });

            double totalTaskCount      = 11;
            var    percentageCompleted = 100;

            DownloadProgressMessage = "0%";

            var userResponse = _tokenService.GetTokenResposne();
            int uID, organizationID;

            int.TryParse(userResponse.UserID, out uID);
            int.TryParse(userResponse.OrganizationID, out organizationID);

            var contentSyncData      = userSyncService.GetContentSyncData(ContentTypes.Content.ToString());
            var contentImageSyncData = userSyncService.GetContentSyncData(ContentTypes.Images.ToString());
            var userLastSync         = userSyncService.GetUserSyncTable(uID);
            var childRecords         = await services.GetChildRecords(modifiedSince : userLastSync.LastSyncDatetime);

            DownloadProgressMessage = Convert.ToInt32(percentageCompleted / totalTaskCount) + "%";
            totalTaskCount         -= 1;
            if (childRecords != null && childRecords.StatusCode != 0)
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            var exisingRecords = _studentService.GetStudentsByDownloaded(uID);

            if (exisingRecords != null && exisingRecords.Any())
            {
                if (childRecords != null && childRecords.Childrens != null && childRecords.Childrens.Any())
                {
                    var newlyAddedRecords = childRecords.Childrens.Where(p => !exisingRecords.Select(q => q.UserId).Contains(p.ChildUserID)).ToList();
                    if (newlyAddedRecords != null && newlyAddedRecords.Any())
                    {
                        try
                        {
                            var needtoInsert = new List <Students>();
                            GenerateStudentList(newlyAddedRecords, needtoInsert, uID);
                            _studentService.InsertAll(needtoInsert);
                            var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                            foreach (var item in childRecords.Childrens)
                            {
                                if (item.ResearchCodes != null && item.ResearchCodes.Any())
                                {
                                    foreach (var innerItem in item.ResearchCodes)
                                    {
                                        var ProductResearchCodeValues = new ProductResearchCodeValues();
                                        ProductResearchCodeValues.OrganizationId      = organizationID;
                                        ProductResearchCodeValues.value               = innerItem.value;
                                        ProductResearchCodeValues.ResearchCodeValueId = innerItem.ResearchCodeValueId;
                                        ProductResearchCodeValues.ResearchCodeId      = innerItem.ResearchCodeId;
                                        ProductResearchCodeValues.OfflineStudentID    = needtoInsert.FirstOrDefault(p => p.UserId == item.ChildUserID.ToString()).OfflineStudentID;
                                        lstResearchCodeValues.Add(ProductResearchCodeValues);
                                    }
                                }
                            }
                            if (lstResearchCodeValues != null && lstResearchCodeValues.Any())
                            {
                                _productResearchCodeValuesService.InsertAll(lstResearchCodeValues);
                            }
                        }
                        catch (Exception ex)
                        {
                            Microsoft.AppCenter.Crashes.Crashes.TrackError(ex);
                        }
                    }

                    var needtoUpdateRecords = exisingRecords.Where(p => childRecords.Childrens.Select(q => q.ChildUserID).Contains(p.UserId)).ToList();
                    if (needtoUpdateRecords != null && needtoUpdateRecords.Any())
                    {
                        foreach (var item in needtoUpdateRecords)
                        {
                            var serverRecord = childRecords.Childrens.FirstOrDefault(p => p.ChildUserID.ToString() == item.UserId);
                            if (serverRecord.isDeleteStatus == 1)
                            {
                                var needtoInsert = new List <Students>();
                                GenerateStudentList(new List <Child>()
                                {
                                    serverRecord
                                }, needtoInsert, uID);
                                needtoInsert.FirstOrDefault().OfflineStudentID = item.OfflineStudentID;
                                _studentService.Update(needtoInsert.FirstOrDefault());
                            }
                            else
                            {
                                DateTime dateTime;
                                DateTime.TryParse(serverRecord.updatedOnUTC, out dateTime);

                                DateTime itemdateTime;
                                DateTime.TryParse(item.updatedOn, out itemdateTime);

                                if (serverRecord != null && dateTime > itemdateTime)
                                {
                                    var needtoInsert = new List <Students>();
                                    GenerateStudentList(new List <Child>()
                                    {
                                        serverRecord
                                    }, needtoInsert, uID);
                                    needtoInsert.FirstOrDefault().OfflineStudentID = item.OfflineStudentID;
                                    _studentService.Update(needtoInsert.FirstOrDefault());
                                    _productResearchCodeValuesService.DeleteByStudentId(item.OfflineStudentID);
                                    var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                                    foreach (var innerItem in serverRecord.ResearchCodes)
                                    {
                                        var ProductResearchCodeValues = new ProductResearchCodeValues();
                                        ProductResearchCodeValues.OrganizationId      = organizationID;
                                        ProductResearchCodeValues.value               = innerItem.value;
                                        ProductResearchCodeValues.ResearchCodeValueId = innerItem.ResearchCodeValueId;
                                        ProductResearchCodeValues.ResearchCodeId      = innerItem.ResearchCodeId;
                                        ProductResearchCodeValues.OfflineStudentID    = needtoInsert.FirstOrDefault(p => p.UserId == serverRecord.ChildUserID.ToString()).OfflineStudentID;
                                        lstResearchCodeValues.Add(ProductResearchCodeValues);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                }
            }
            else
            {
                var studentsToInsert = new List <Students>();
                if (childRecords != null)
                {
                    GenerateStudentList(childRecords.Childrens, studentsToInsert, uID);
                }
                if (studentsToInsert != null && studentsToInsert.Any())
                {
                    try
                    {
                        _studentService.InsertAll(studentsToInsert);
                        var lstResearchCodeValues = new List <ProductResearchCodeValues>();
                        foreach (var childItem in childRecords.Childrens)
                        {
                            if (childItem.ResearchCodes != null && childItem.ResearchCodes.Any())
                            {
                                foreach (var innerItem in childItem.ResearchCodes)
                                {
                                    var ProductResearchCodeValues = new ProductResearchCodeValues();
                                    ProductResearchCodeValues.OrganizationId      = organizationID;
                                    ProductResearchCodeValues.value               = innerItem.value;
                                    ProductResearchCodeValues.ResearchCodeValueId = innerItem.ResearchCodeValueId;
                                    ProductResearchCodeValues.ResearchCodeId      = innerItem.ResearchCodeId;
                                    ProductResearchCodeValues.OfflineStudentID    = studentsToInsert.FirstOrDefault(p => p.UserId == childItem.ChildUserID.ToString()).OfflineStudentID;
                                    lstResearchCodeValues.Add(ProductResearchCodeValues);
                                }
                            }
                        }
                        if (lstResearchCodeValues != null && lstResearchCodeValues.Any())
                        {
                            _productResearchCodeValuesService.InsertAll(lstResearchCodeValues);
                        }
                    }
                    catch (Exception ex)
                    {
                        Microsoft.AppCenter.Crashes.Crashes.TrackError(ex);
                    }
                }
            }

            if (childRecords != null && childRecords.ResearchCodes != null && childRecords.ResearchCodes.Any())
            {
                _productResearchCodesService.DeleteAll(organizationID);
                if (childRecords.ResearchCodes != null && childRecords.ResearchCodes.Any())
                {
                    _productResearchCodesService.InsertAll(childRecords.ResearchCodes);
                }
            }
            var locations = await new BDIWebServices().GetLocationRequestModel(uID);

            DownloadProgressMessage = Convert.ToInt32(percentageCompleted / totalTaskCount) + "%";
            totalTaskCount         -= 2;
            if (locations == null || !locations.Any())
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            else
            {
                if (locations != null && locations.Any())
                {
                    var totalLocations = new List <Models.DBModels.Location>();
                    foreach (var item in locations)
                    {
                        var location = new Models.DBModels.Location();
                        location.LocationId       = item.value;
                        location.LocationName     = item.text;
                        location.IsEnabled        = item.enabled;
                        location.DownloadedBy     = uID;
                        location.isDeleted        = item.isDeleted;
                        location.updatedOn        = item.updatedOn;
                        location.ParentLocationId = item.parentLocationID;
                        location.UserId           = uID;
                        totalLocations.Add(location);
                        GenerateSubLocations(item.subItems, totalLocations, 0, uID);
                    }
                    lstlocalLocations = _locationService.GetAllByDownloadedByLocations(uID);
                    _locationService.DeleteByDownloadedBy(uID);
                    needtoDeleteLocations = lstlocalLocations.Where(p => !totalLocations.Select(q => q.LocationId).Contains(p.LocationId)).ToList();
                    _locationService.InsertAll(totalLocations);
                }
            }
            percentageCompleted     = 50;
            totalTaskCount          = 1.5;
            DownloadProgressMessage = (Convert.ToInt32(percentageCompleted / totalTaskCount) + percentageCompleted) + "%";
            totalTaskCount         -= 1;
            var examiners = await new BDIWebServices().GetExaminer(new Models.Requests.StaffRequestModel());

            DownloadProgressMessage = Convert.ToInt32(percentageCompleted / totalTaskCount) + "%";
            totalTaskCount         -= 1;
            if (examiners == null || !examiners.Any())
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            else
            {
                _examinerService.DeleteByDownloadedBy(uID);
                if (examiners != null && examiners.Any())
                {
                    var orgId = Convert.ToInt32(Application.Current.Properties["OrgnazationID"].ToString());
                    foreach (var item in examiners)
                    {
                        item.DownloadedBy   = uID;
                        item.UserID         = KeyEncryption.Decrypt(item.UserID);
                        item.OrganizationId = orgId;
                    }
                    _examinerService.InsertAll(examiners);
                }
                commonDataService.SearchStaffResponseModel = _examinerService.GetExamainer() ?? new List <SearchStaffResponse>();
            }
            var programNotes = await new BDIWebServices().GetProgramNote(organizationID);

            if (programNotes == null)
            {
                await PopupNavigation.Instance.PopAllAsync();

                await UserDialogs.Instance.AlertAsync("Download Failed!");

                return(false);
            }
            else
            {
                DownloadProgressMessage = "100%";
                _programNoteService.DeleteByDownloadedBy(uID);
                if (programNotes != null && programNotes.Any())
                {
                    var totalProgram = new List <ProgramNoteModel>();
                    foreach (var item in programNotes)
                    {
                        var programNote = new ProgramNoteModel();
                        programNote.LabelId        = item.LabelId;
                        programNote.LabelName      = item.LabelName;
                        programNote.DeleteType     = item.DeleteType;
                        programNote.DownLoadedBy   = uID;
                        programNote.updatedOn      = item.updatedOn;
                        programNote.OrganizationId = item.OrganizationId;
                        totalProgram.Add(programNote);
                    }
                    _programNoteService.InsertAll(totalProgram);
                }
                commonDataService.ProgramNoteModels = _programNoteService.GetProgramNote() ?? new List <ProgramNoteModel>();
            }
            try
            {
                var organizationRecordForms = await services.GetOrgRecordForms();

                _orgRecordFormService.DeleteAll();
                if (organizationRecordForms != null && organizationRecordForms.Any())
                {
                    organizationRecordForms.ForEach((item) =>
                    {
                        item.DownloadedBy   = uID;
                        item.OrganizationId = organizationID;
                    });
                    _orgRecordFormService.Insert(organizationRecordForms);
                }
                commonDataService.OrgRecordFormList = _orgRecordFormService.GetRecordForms() ?? new List <OrganizationRecordForms>();
            }
            catch (Exception ex)
            {
            }
            var localLocations = _locationService.GetLocations();

            if (needtoDeleteLocations != null && needtoDeleteLocations.Any())
            {
                foreach (var item in needtoDeleteLocations)
                {
                    var deletedLocation = lstlocalLocations.FirstOrDefault(p => p.LocationId == item.LocationId);
                    if (deletedLocation != null)
                    {
                        deletedLocation.isDeleted = true;
                    }
                }
                var locationIDs             = needtoDeleteLocations.Select(p => p.LocationId).ToList();
                var locaDownlodedBtStudents = _studentService.GetStudentsByDownloaded(uID);
                if (locaDownlodedBtStudents != null && locaDownlodedBtStudents.Any())
                {
                    foreach (var item in locaDownlodedBtStudents)
                    {
                        if (item.SelectedLocationId.HasValue && locationIDs.Contains(item.SelectedLocationId.Value))
                        {
                            var locationID = CheckRecursiveLOcationsUpdate(item.SelectedLocationId.Value, lstlocalLocations);
                            item.SelectedLocationId = locationID;
                            _studentService.Update(item);
                        }
                    }
                }
            }
            var userpermissions = default(List <string>);

            if (JObject.Parse(_tokenService.GetTokenResposne().Perms).ToObject <Dictionary <int, string> >().ContainsKey(10))
            {
                userpermissions = JObject.Parse(_tokenService.GetTokenResposne().Perms).ToObject <Dictionary <int, string> >().Where(p => p.Key == 10).Select(p => p.Value).ToList();
                foreach (var item in userpermissions)
                {
                    await _userPermissionService.DeleteAllAsync();

                    var allUserPermissionList = new List <Models.DBModels.UserPermissions>();
                    var splitids = item.Split(',').ToList();
                    foreach (var perId in splitids)
                    {
                        var userPermissions = new Models.DBModels.UserPermissions()
                        {
                            UserId       = uID,
                            PermissionId = Convert.ToInt32(perId)
                        };
                        allUserPermissionList.Add(userPermissions);
                    }
                    await _userPermissionService.InsertAllAsync(allUserPermissionList);
                }
            }
            await PopupNavigation.Instance.PopAllAsync();

            var date = DateTime.Now.ToUniversalTime().ToString("s") + "Z";

            userLastSync.LastSyncDatetime = date;
            userSyncService.UpdateUserSync(userLastSync);
            return(true);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Perform an association request with an OpenID Provider.
        /// </summary>
        /// <param name="server">URL to the OpenID Provider.</param>
        /// <param name="associationManager">The IAssociationPersistence object to use for persistence.</param>
        /// <param name="version">The ProtocolVersion to use.</param>
        /// <param name="encryption">The key encryption type to use.</param>
        /// <returns>Populated Association object, or null.</returns>
        internal static Association CreateAssociation(Uri server, IAssociationPersistence associationManager,
                                                      ProtocolVersion version, KeyEncryption encryption)
        {
            if (server == null) { throw new ArgumentNullException("server"); }
            if (associationManager == null) { throw new ArgumentNullException("associationManager"); }

            NameValueCollection sd = new NameValueCollection();
            DiffieHellmanManaged dhm = new DiffieHellmanManaged();
            sd["openid.mode"] = "associate";

            switch (version)
            {
                case ProtocolVersion.V2Dot0:
                    sd["openid.ns"] = ProtocolUri.OpenId2Dot0.AbsoluteUri;
                    break;
                case ProtocolVersion.V1Dot1:
                    if (encryption == KeyEncryption.DHSHA256)
                    {
                        encryption = KeyEncryption.DHSHA1;
                    }
                    break;
            }

            byte[] pubkey = null;
            DHParameters dp;

            switch (encryption)
            {
                case KeyEncryption.None:
                    sd["openid.assoc_type"] = "HMAC-SHA1";
                    switch (version)
                    {
                        case ProtocolVersion.V2Dot0:
                            sd["openid.session_type"] = "no-encryption";
                            break;
                        case ProtocolVersion.V1Dot1:
                            sd["openid.session_type"] = "";
                            break;
                    }
                    break;
                case KeyEncryption.DHSHA1:
                    pubkey = dhm.CreateKeyExchange();
                    dp = dhm.ExportParameters(true);

                    sd["openid.assoc_type"] = "HMAC-SHA1";
                    sd["openid.session_type"] = "DH-SHA1";
                    sd["openid.dh_modulus"] = Utility.UnsignedToBase64(dp.P);
                    sd["openid.dh_gen"] = Utility.UnsignedToBase64(dp.G);
                    sd["openid.dh_consumer_public"] = Utility.UnsignedToBase64(pubkey);
                    break;
                case KeyEncryption.DHSHA256:
                    pubkey = dhm.CreateKeyExchange();
                    dp = dhm.ExportParameters(true);

                    sd["openid.assoc_type"] = "HMAC-SHA256";
                    sd["openid.session_type"] = "DH-SHA256";
                    sd["openid.dh_modulus"] = Utility.UnsignedToBase64(dp.P);
                    sd["openid.dh_gen"] = Utility.UnsignedToBase64(dp.G);
                    sd["openid.dh_consumer_public"] = Utility.UnsignedToBase64(pubkey);
                    break;
            }

            Tracer.Write("Opening connection to OpenID Provider.");
            string response = "";
            string actualLocation = null;
            response = Utility.MakeRequest(server, "POST", sd, out actualLocation);

            NameValueCollection association = null;
            Association retassoc = null;
            if (response != null)
            {
                Tracer.Write("Association response received.");
                association = Utility.SplitResponse(response);
            }
            else
            {
                Tracer.Write("No association response received.");
                switch (encryption)
                {
                    case KeyEncryption.DHSHA256:
                        Tracer.Write("Falling back to DHSHA1");
                        encryption = KeyEncryption.DHSHA1;
                        retassoc = CreateAssociation(server, associationManager, version, encryption);
                        if (retassoc != null) { return retassoc; }
                        break;
                    case KeyEncryption.DHSHA1:
                        Tracer.Write("Falling back to No-encryption");
                        encryption = KeyEncryption.None;
                        retassoc = CreateAssociation(server, associationManager, version, encryption);
                        if (retassoc != null) { return retassoc; }
                        break;
                }
                return null;
            }

            if (association["error"] != null)
            {
                Tracer.Write("Association response contains error. - " + association["error"]);
                return null;
            }

            if (encryption == KeyEncryption.DHSHA1 || encryption == KeyEncryption.DHSHA256)
            {
                Tracer.Write("Expecting DHSHA1 or DHSHA256.");
                StringBuilder vals = new StringBuilder();
                foreach (string key in association.Keys)
                {
                    vals.AppendLine(key + ": " + association[key]);
                }
                if (association["enc_mac_key"] == null) { Tracer.Write("No encoded MAC key returned! Received " + vals.ToString()); }
                if (association["enc_mac_key"] != null)
                {
                    Tracer.Write("Encrypted association key is present.");
                    byte[] serverpublickey = Convert.FromBase64String(association["dh_server_public"]);
                    byte[] mackey = Convert.FromBase64String(association["enc_mac_key"]);

                    byte[] dhShared = dhm.DecryptKeyExchange(serverpublickey);
                    byte[] shaShared = new byte[0];

                    if (encryption == KeyEncryption.DHSHA1)
                    {
                        Tracer.Write("Decoding DHSHA1 Association.");
                        SHA1 sha1 = new SHA1CryptoServiceProvider();
                        shaShared = sha1.ComputeHash(Utility.EnsurePositive(dhShared));
                    }
                    else if (encryption == KeyEncryption.DHSHA256)
                    {
                        Tracer.Write("Decoding DHSHA256 Association.");
                        SHA256 sha256 = new SHA256Managed();
                        shaShared = sha256.ComputeHash(Utility.EnsurePositive(dhShared));
                    }

                    byte[] secret = new byte[mackey.Length];
                    for (int i = 0; i < mackey.Length; i++)
                    {
                        secret[i] = (byte)(mackey[i] ^ shaShared[i]);
                    }
                    association["mac_key"] = Convert.ToBase64String(secret);
                }
                else
                {
                    Tracer.Write("Error: Received plaintext association when expecting encrypted.");
                    return null;
                }
            }

            Tracer.Write("Building association");
            retassoc = new Association();
            retassoc.AssociationType = association["assoc_type"];
            retassoc.Expiration = DateTime.UtcNow.AddSeconds(Convert.ToDouble(association["expires_in"], CultureInfo.InvariantCulture));
            retassoc.Handle = association["assoc_handle"];
            retassoc.ProtocolVersion = version;
            retassoc.Server = server.AbsoluteUri;
            retassoc.SessionType = association["session_type"];
            retassoc.Secret = Convert.FromBase64String(association["mac_key"]);
            return retassoc;
        }