예제 #1
0
        /// <summary>
        /// Encrypts the data in a specified byte array and returns a byte array that contains the encrypted data.
        /// This method uses the local machine account.
        /// </summary>
        /// <param name="data">The data to protect.</param>
        /// <returns>The stream containing the protected data.</returns>
        public MemoryStream MachineProtect(byte[] data)
        {
            DataProtection protect = new DataProtection();

            byte[] protectedData = protect.Protect(data, DataProtectionScope.LocalMachine);
            return(new MemoryStream(protectedData));
        }
예제 #2
0
        public static bool CheckUserCookie(UserProfile profile)
        {
            if (HttpContext.Current.Request.Cookies["UserProfileCookie"] != null)
            {
                string strId = DataProtection.Decrypt(HttpContext.Current.Request.Cookies["UserProfileCookie"]["Id"]);
                if (string.IsNullOrWhiteSpace(strId))
                {
                    return(false);
                }
                UserModel employee = new CU_AccountService().ValidateLoginData(DataProtection.Decrypt(HttpContext.Current.Request.Cookies["UserProfileCookie"]["LoginName"])
                                                                               , DataProtection.Decrypt(HttpContext.Current.Request.Cookies["UserProfileCookie"]["Password"]));
                if (employee != null)
                {
                    CreateUserSession(profile, employee);
                    return(true);
                }
                else
                {
                    return(false);
                }



                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #3
0
        /// <summary>
        /// Decrypts the data in a specified byte array and returns a byte array that contains the decrypted data.
        /// This method uses the current user account.
        /// </summary>
        /// <param name="data">The data to unprotect.</param>
        /// <returns>The stream containing the unprotected data.</returns>
        public MemoryStream UserUnprotect(byte[] data)
        {
            DataProtection unprotect = new DataProtection();

            byte[] unprotectedData = unprotect.Unprotect(data, DataProtectionScope.CurrentUser);
            return(new MemoryStream(unprotectedData));
        }
예제 #4
0
        public async Task ExecuteAsync()
        {
            try
            {
                var content = new StringContent(JsonConvert.SerializeObject(_infoModel), Encoding.UTF8, "application/json");
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri("Agent/Report/", UriKind.Relative),
                    Method     = HttpMethod.Post,
                    Content    = content
                };
                CertHandler      _certHandler      = new CertHandler();
                X509Certificate2 clientCertificate = _certHandler.FindCertificate("YaraCA", StoreName.My, StoreLocation.LocalMachine);
                request.Headers.Add("X-ARR-ClientCert", clientCertificate.GetRawCertDataString());

                var response = await HttpClientSingleton.HttpClientInstance.SendAsync(request);

                response.EnsureSuccessStatusCode();
            }
            catch (HttpRequestException)
            {
                string timestamp       = Guid.NewGuid().ToString();
                string infoModelString = JsonConvert.SerializeObject(_infoModel);
                byte[] infoModelEnc    = DataProtection.Protect(Encoding.UTF8.GetBytes(infoModelString));
                FileHandler.WriteBytesToFile(FileHandler.REPORT_ARCHIVE + timestamp, infoModelEnc);
            }
        }
예제 #5
0
        internal static DatabaseInfo PromptForInfo(EFCorePowerToolsPackage package)
        {
            // Show dialog with SqlClient selected by default
            var dialogFactory = package.GetService <IVsDataConnectionDialogFactory>();
            var dialog        = dialogFactory.CreateConnectionDialog();

            dialog.AddAllSources();
            dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528");
            var dialogResult = dialog.ShowDialog(connect: true);

            if (dialogResult == null)
            {
                return new DatabaseInfo {
                           DatabaseType = DatabaseType.Undefined
                }
            }
            ;

            var info = GetDatabaseInfo(package, dialogResult.Provider, DataProtection.DecryptString(dialog.EncryptedConnectionString));

            if (info.Size == Guid.Empty.ToString())
            {
                return new DatabaseInfo {
                           DatabaseType = DatabaseType.Undefined
                }
            }
            ;

            SaveDataConnection(package, dialog.EncryptedConnectionString, info.DatabaseType, new Guid(info.Size));
            return(info);
        }
        internal static void RemoveDataConnection(SqlCeToolboxPackage package, string connectionString, Guid provider)
        {
            var removals = new List <IVsDataExplorerConnection>();
            var dataExplorerConnectionManager = package.GetServiceHelper(typeof(IVsDataExplorerConnectionManager)) as IVsDataExplorerConnectionManager;

            if (dataExplorerConnectionManager != null)
            {
                foreach (var connection in dataExplorerConnectionManager.Connections.Values)
                {
                    var objProviderGuid = connection.Provider;
                    if ((objProviderGuid == new Guid(Resources.SqlCompact35Provider)) || (objProviderGuid == new Guid(Resources.SqlCompact40Provider)))
                    {
                        if (DataProtection.DecryptString(connection.EncryptedConnectionString) == connectionString)
                        {
                            removals.Add(connection);
                        }
                    }
                }

                for (int i = removals.Count - 1; i >= 0; i--)
                {
                    try
                    {
                        dataExplorerConnectionManager.RemoveConnection(removals[i]);
                    }
                    catch (ArgumentException)
                    {
                    }
                    catch (IndexOutOfRangeException)
                    {
                    }
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Creates and returns a fully configured <see cref="ILogProvider"/> instance.
        /// </summary>
        /// <returns>A fully configured <see cref="ILogProvider"/> instance.</returns>
        public ILogProvider GetConfiguredInstance()
        {
            if (!string.IsNullOrEmpty(txtUrl.Text))
            {
                if (ModifierKeys != Keys.Shift)
                {
                    // Save the current settings as new default values.
                    Settings.Default.PnlCustomHttpSettingsUrl            = txtUrl.Text;
                    Settings.Default.PnlCustomHttpSettingsAuthentication = chkAuthentication.Checked;
                    Settings.Default.PnlCustomHttpSettingsUsername       = DataProtection.EncryptString(txtUsername.Text);
                    Settings.Default.PnlCustomHttpSettingsPassword       = DataProtection.EncryptString(txtPassword.Text);
                    Settings.Default.PnlCustomHttpSettingsPollTime       = (int)nudPollingTime.Value;
                    Settings.Default.PnlCustomTcpSettingsEncoding        = ((EncodingWrapper)cmbEncoding.SelectedItem).Codepage;

                    if (cmbColumnizer.SelectedItem != null)
                    {
                        Settings.Default.PnlCustomHttpSettingsColumnizer = cmbColumnizer.SelectedItem.ToString();
                    }

                    Settings.Default.SaveSettings();
                }

                return(new CustomHttpReceiver(
                           txtUrl.Text
                           , chkAuthentication.Checked ? new BasicHttpAuthentication(txtUsername.Text, txtPassword.Text) : null
                           , (int)nudPollingTime.Value
                           , cmbColumnizer.SelectedItem as Columnizer
                           , Settings.Default.PnlCustomHttpSettingsEncoding));
            }

            return(null);
        }
        public void ObtainFromDB()
        {
            using (SQLiteConnection myconnection = new SQLiteConnection(SystemParameters.ConnectionString))
            {
                myconnection.Open();

                using (SQLiteCommand mycommand = new SQLiteCommand(myconnection))
                {
                    mycommand.CommandText = String.Format("SELECT * FROM {0}", tableName);
                    SQLiteDataReader dataReader = mycommand.ExecuteReader();
                    if (dataReader.Read())
                    {
                        if (dataReader["syncable"].ToString().Equals("1"))
                        {
                            this.syncable = 1;
                        }
                        else
                        {
                            this.syncable = 0;
                        }

                        this.account        = dataReader["account"].ToString();
                        this.password       = DataProtection.Decrypt(dataReader["password"].ToString());
                        this.url            = dataReader["url"].ToString();
                        this.apiKey         = DataProtection.Decrypt(dataReader["api_key"].ToString());
                        this.rootFolderPath = dataReader["root_folder_path"].ToString();
                        this.displayName    = dataReader["display_name"].ToString();
                        this.defaultOrganizationResourceID = dataReader["default_organization_resource_id"].ToString();
                        this.defaultLicenseResourceID      = dataReader["default_license_resource_id"].ToString();
                    }
                }
                myconnection.Close();
            }
        }
예제 #9
0
파일: XmlService.cs 프로젝트: veserine/Neo
        public List <string> ReadConnection(string id)
        {
            var connectionList = new List <string>();
            var data           = new DataProtection();

            try
            {
                var root       = XElement.Load(@".\Config\Connections.xml");
                var connection =
                    from el in root.Elements("Connection")
                    where (string)el.Attribute("ID") == id
                    select el;
                foreach (var el in connection)
                {
                    connectionList.Add(data.Decrpyt(el.Element("Address").Value));
                    connectionList.Add(data.Decrpyt(el.Element("Username").Value));
                    connectionList.Add(data.Decrpyt(el.Element("Password").Value));
                    connectionList.Add(data.Decrpyt(el.Element("Database").Value));
                }
                return(connectionList);
            }
            catch (Exception e)
            {
                Log.Error("Unable to read connection. " + e.Message);
            }
            return(null);
        }
예제 #10
0
파일: XmlService.cs 프로젝트: veserine/Neo
        public void SaveConnection(List <string> value)
        {
            var data = new DataProtection();

            try
            {
                var fileDir = XDocument.Load(@".\Config\Connections.xml");

                var newConnection = new XElement("Connection",
                                                 new XElement("Address", data.Encrpyt(value[0])),
                                                 new XElement("Username", data.Encrpyt(value[1])),
                                                 new XElement("Password", data.Encrpyt(value[2])),
                                                 new XElement("Database", data.Encrpyt(value[3]))
                                                 );

                newConnection.SetAttributeValue("ID", value[4]);
                newConnection.SetAttributeValue("Default", value[5]);

                var xElement = fileDir.Element("Connections");
                if (xElement != null)
                {
                    xElement.Add(newConnection);
                }

                fileDir.Save(@".\Config\Connections.xml");
            }
            catch (Exception e)
            {
                Log.Error("Unable to save connection. " + e.Message);
            }
        }
예제 #11
0
        // Scanner Listener
        public void OnFileScanned(InfoModel report)
        {
            // Check not send reports
            List <NetScanJob> netScanJobs = new List <NetScanJob>();

            foreach (string file in Directory.EnumerateFiles(FileHandler.REPORT_ARCHIVE))
            {
                try
                {
                    byte[]     encReport  = FileHandler.ReadTextFromFile(file);
                    byte[]     decReport  = DataProtection.Unprotect(encReport);
                    string     content    = Encoding.UTF8.GetString(decReport);
                    InfoModel  infoModel  = JsonConvert.DeserializeObject <InfoModel>(content);
                    NetScanJob netScanJob = new NetScanJob(report);
                    netScanJobs.Add(netScanJob);
                    FileHandler.DeleteFile(file);
                }
                catch (Exception ex)
                {
                }
            }

            netScanJobs.Add(new NetScanJob(report));
            foreach (NetScanJob job in netScanJobs)
            {
                mNetworking.ExecuteAsync(job);
            }
        }
예제 #12
0
        public void GenerateServerDgmlFiles()
        {
            try
            {
                if (_package.Dte2.Mode == vsIDEMode.vsIDEModeDebug)
                {
                    EnvDteHelper.ShowError("Cannot generate code while debugging");
                    return;
                }

                // Show dialog with SqlClient selected by default
                var dialogFactory = _package.GetService <IVsDataConnectionDialogFactory>();
                var dialog        = dialogFactory.CreateConnectionDialog();
                dialog.AddAllSources();
                dialog.SelectedSource = new Guid("067ea0d9-ba62-43f7-9106-34930c60c528");
                var dialogResult = dialog.ShowDialog(connect: true);

                if (dialogResult == null)
                {
                    return;
                }

                _package.Dte2.StatusBar.Text = "Loading schema information...";

                var dbInfo = GetDatabaseInfo(dialogResult, DataProtection.DecryptString(dialog.EncryptedConnectionString));

                if (dbInfo.DatabaseType == DatabaseType.SQLCE35)
                {
                    EnvDteHelper.ShowError($"Unsupported provider: {dbInfo.ServerVersion}");
                    return;
                }

                var ptd = new PickTablesDialog();
                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    ptd.Tables = repository.GetAllTableNamesForExclusion();
                }

                var res = ptd.ShowModal();
                if (!res.HasValue || !res.Value)
                {
                    return;
                }

                var path = Path.GetTempFileName() + ".dgml";

                using (var repository = RepositoryHelper.CreateRepository(dbInfo))
                {
                    var generator = RepositoryHelper.CreateGenerator(repository, path, dbInfo.DatabaseType);
                    generator.GenerateSchemaGraph(dbInfo.ConnectionString, ptd.Tables);
                    _package.Dte2.ItemOperations.OpenFile(path);
                    _package.Dte2.ActiveDocument.Activate();
                }
            }
            catch (Exception ex)
            {
                _package.LogError(new List <string>(), ex);
            }
        }
예제 #13
0
        internal static void SaveDataConnection(EFCorePowerToolsPackage package, string encryptedConnectionString,
                                                DatabaseType dbType, Guid provider)
        {
            var dataExplorerConnectionManager = package.GetService <IVsDataExplorerConnectionManager>();
            var savedName = GetFileName(DataProtection.DecryptString(encryptedConnectionString), dbType);

            dataExplorerConnectionManager.AddConnection(savedName, provider, encryptedConnectionString, true);
        }
    public static Tuple <string, string> setNewAgentPassword(SecureString new_password)
    {
        /* With the given password return the corresponding hash with a new salt (which will have to be saved into the database)*/
        string salt            = DataProtection.getSaltForHashes();
        string hashed_password = DataProtection.getSaltHashedString(new_password, salt);

        return(Tuple.Create(hashed_password, salt));
    }
        public async Task <bool> RunAsync(string emailAddress)
        {
            HashSet emailAddressHash = await DataProtection.StaticHashAsync(emailAddress, DataKeys.EmailAddressSalt);

            return(await _authenticationDbContext.Identities
                   .AnyAsync(i => i.AuthenticationIdentities.OfType <PasswordIdentity>()
                             .Any(a => a.EmailAddressHash == emailAddressHash.Hash)
                             ));
        }
 internal static void SaveDataConnection(SqlCeToolboxPackage package, string encryptedConnectionString,
                                         DatabaseType dbType, Guid provider)
 {
     if (package.GetServiceHelper(typeof(IVsDataExplorerConnectionManager)) is IVsDataExplorerConnectionManager dataExplorerConnectionManager)
     {
         var savedName = GetFileName(DataProtection.DecryptString(encryptedConnectionString), dbType);
         dataExplorerConnectionManager.AddConnection(savedName, provider, encryptedConnectionString, true);
     }
 }
        private void save_button_Click(object sender, EventArgs e)
        {
            if (mail_adress_textBox.Text == "" || password_textBox.Text == "" || smtp_port_textBox.Text == "" || smtp_port_textBox.Text == "")
            {
                MessageBox.Show("ERREUR : tous les champs doivent être renseignés !");
                return;
            }

            Parms parms = new Parms();

            parms.toDefault();

            parms.adress    = mail_adress_textBox.Text;
            parms.smtpSever = smtp_server_textBox.Text;
            try
            {
                parms.smtpPort = Int32.Parse(smtp_port_textBox.Text);
            }
            catch
            {
                MessageBox.Show("ERREUR : format du port SMTP non reconnu");
                return;
            }

            if (password_textBox.Text != DISPLAY_PASSWORD) //new password, so have to change it
            {
                SecureString password = new SecureString();
                foreach (char c in password_textBox.Text)
                {
                    password.AppendChar(c);
                }
                password.MakeReadOnly();

                try
                {
                    parms.password = DataProtection.protect(password);
                }
                catch
                {
                    MessageBox.Show("ERREUR : Impossible de sécuriser le mot de passe avant de l'enregistrer");
                    return;
                }finally
                {
                    password.Dispose();
                }
            }//else password reamin the same (already saved in the sruct ParmsMailsSender)
            parms.beforeMessage = removeAllVoidAtTheExtremaOfString(before_message_textBox.Text).Replace(Environment.NewLine, "<br>");
            parms.afterMessage  = removeAllVoidAtTheExtremaOfString(after_message_textBox.Text).Replace(Environment.NewLine, "<br>");


            ToolsClass.Settings.MailsSenderParameters = parms;

            this.Close();
        }
예제 #18
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.UserControl.Load"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data. </param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            cmbColumnizer.Items.AddRange(LoadColumnizer());

            if (cmbColumnizer.Items.Count > 0)
            {
                if (ModifierKeys != Keys.Shift)
                {
                    foreach (var columnizer in cmbColumnizer.Items)
                    {
                        if (Equals(columnizer.ToString(), Settings.Default.PnlCustomHttpSettingsColumnizer))
                        {
                            cmbColumnizer.SelectedItem = columnizer;
                            break;
                        }
                    }
                }

                if (cmbColumnizer.SelectedItem == null)
                {
                    cmbColumnizer.SelectedIndex = 0;
                }
            }

            if (ModifierKeys != Keys.Shift)
            {
                txtUrl.Text               = Settings.Default.PnlCustomHttpSettingsUrl;
                txtUsername.Text          = DataProtection.DecryptString(Settings.Default.PnlCustomHttpSettingsUsername);
                txtPassword.Text          = DataProtection.DecryptString(Settings.Default.PnlCustomHttpSettingsPassword);
                chkAuthentication.Checked = Settings.Default.PnlCustomHttpSettingsAuthentication;
                nudPollingTime.Value      = Settings.Default.PnlCustomHttpSettingsPollTime;
            }

            foreach (EncodingInfo encoding in Encoding.GetEncodings())
            {
                EncodingWrapper encWrapper = new EncodingWrapper(encoding);

                cmbEncoding.Items.Add(encWrapper);

                if (encoding.CodePage == (ModifierKeys != Keys.Shift ? Settings.Default.PnlCustomTcpSettingsEncoding : Encoding.Default.CodePage))
                {
                    cmbEncoding.SelectedItem = encWrapper;
                }
            }

            if (cmbEncoding.SelectedItem == null)
            {
                cmbEncoding.SelectedIndex = 0;
            }

            UpdateEditButtons();
        }
예제 #19
0
        private async Task <List <TableModel> > GetTablesAsync(DatabaseConnectionModel dbInfo, CodeGenerationMode codeGenerationMode, SchemaInfo[] schemas)
        {
            if (dbInfo.DataConnection != null)
            {
                dbInfo.DataConnection.Open();
                dbInfo.ConnectionString = DataProtection.DecryptString(dbInfo.DataConnection.EncryptedConnectionString);
            }

            var builder = new TableListBuilder(dbInfo.ConnectionString, dbInfo.DatabaseType, schemas);

            return(await builder.GetTableDefinitionsAsync(codeGenerationMode));
        }
예제 #20
0
        public async Task <Identity> RunAsync(
            AuthenticationGrantTypeClientCredential authenticationGrantTypeClientCredential,
            string identifier)
        {
            HashSet identifierHash = await DataProtection.StaticHashAsync(identifier, DataKeys.IdentifierSalt);

            return(await _authenticationDbContext.Identities
                   .SingleOrDefaultAsync(i =>
                                         i.AuthenticationIdentities.OfType <ClientCredentialIdentity>().Any(a =>
                                                                                                            a.IdentifierHash == identifierHash.Hash &&
                                                                                                            a.AuthenticationGrantTypeClientCredential == authenticationGrantTypeClientCredential)));
        }
        public List <TableInformationModel> GetTables(DatabaseInfo dbInfo, bool useEFCore5, SchemaInfo[] schemas)
        {
            if (dbInfo.DataConnection != null)
            {
                dbInfo.DataConnection.Open();
                dbInfo.ConnectionString = DataProtection.DecryptString(dbInfo.DataConnection.EncryptedConnectionString);
            }

            var builder = new TableListBuilder(dbInfo.ConnectionString, dbInfo.DatabaseType, schemas);

            return(builder.GetTableDefinitions(useEFCore5));
        }
예제 #22
0
        public static List <TableInformationModel> GetTablesFromRepository(DatabaseInfo dbInfo, bool includeViews = false)
        {
            if (dbInfo.DataConnection != null)
            {
                dbInfo.DataConnection.Open();
                dbInfo.ConnectionString = DataProtection.DecryptString(dbInfo.DataConnection.EncryptedConnectionString);
            }

            if (dbInfo.DatabaseType == DatabaseType.Npgsql)
            {
                return(EnvDteHelper.GetNpgsqlTableNames(dbInfo.ConnectionString, includeViews));
            }

            if (dbInfo.DatabaseType == DatabaseType.Mysql)
            {
                return(EnvDteHelper.GetMysqlTableNames(dbInfo.ConnectionString, includeViews));
            }

            if (dbInfo.DatabaseType == DatabaseType.Oracle)
            {
                return(EnvDteHelper.GetOracleTableNames(dbInfo.ConnectionString, includeViews));
            }

            using (var repository = RepositoryHelper.CreateRepository(dbInfo))
            {
                var allPks    = repository.GetAllPrimaryKeys();
                var tableList = repository.GetTableNamesForExclusion();
                var tables    = new List <TableInformationModel>();

                foreach (var table in tableList)
                {
                    var hasPrimaryKey = allPks.Any(m => m.TableName == table.TableName);
                    var name          = string.IsNullOrEmpty(table.Schema)
                        ? table.TableName
                        : $"[{table.Schema}].[{table.Name}]";

                    var info = new TableInformationModel(name, includeViews ? true : hasPrimaryKey, includeViews ? !hasPrimaryKey : false);
                    tables.Add(info);
                }

                if (includeViews)
                {
                    var views = repository.GetAllViews();
                    foreach (var view in views)
                    {
                        var info = new TableInformationModel(view.ViewName, true, true);
                        tables.Add(info);
                    }
                }

                return(tables.OrderBy(l => l.Name).ToList());
            }
        }
        private async Task <List <TableModel> > GetTablesAsync(DatabaseInfo dbInfo, bool useEFCore5, SchemaInfo[] schemas)
        {
            if (dbInfo.DataConnection != null)
            {
                dbInfo.DataConnection.Open();
                dbInfo.ConnectionString = DataProtection.DecryptString(dbInfo.DataConnection.EncryptedConnectionString);
            }

            var builder = new TableListBuilder(dbInfo.ConnectionString, dbInfo.DatabaseType, schemas);

            return(await System.Threading.Tasks.Task.Run(() => builder.GetTableDefinitions(useEFCore5)));
        }
        public async Task StoreAsync <T>(string key, T value)
        {
            StorageFile file = await LocalFolder.CreateFileAsync(GenerateStoredKey(key, typeof(T)),
                                                                 CreationCollisionOption.ReplaceExisting);

            var content = NewtonsoftJsonSerializer.Instance.Serialize(value);

            byte[] protectedContent = DataProtection.Protect(content);
            using (var stream = await file.OpenStreamForWriteAsync().ConfigureAwait(false))
            {
                await stream.WriteAsync(protectedContent, 0, protectedContent.Length).ConfigureAwait(false);
            }
        }
예제 #25
0
        private static Guid GetVsDataSource(IVsDataProviderManager dataProviderManager, IVsDataConnection dataConnection)
        {
            if (dataConnection == null)
            {
                throw new ArgumentNullException("dataConnection");
            }

            var guid     = Guid.Empty;
            var provider = GetVsProvider(dataProviderManager, dataConnection);

            guid = provider.DeriveSource(DataProtection.DecryptString(dataConnection.EncryptedConnectionString));

            return(guid);
        }
        internal static void SaveDataConnection(string connectionString, DatabaseType dbType,
            SqlCeToolboxPackage package)
        {
            var storeDbType = GetPreferredDatabaseType();
            var helper = CreateEngineHelper(storeDbType);
            string path = CreateEngineHelper(dbType).PathFromConnectionString(connectionString);
            helper.SaveDataConnection(CreateStore(storeDbType), connectionString, path, dbType.GetHashCode());

            if (package.VsSupportsSimpleDdex4Provider() && dbType == DatabaseType.SQLCE40)
            {
                SaveDataConnection(package, DataProtection.EncryptString(connectionString), dbType,
                    new Guid(Resources.SqlCompact40PrivateProvider));
            }
        }
예제 #27
0
        public string UnsecureDecrypt(byte[] value)
        {
            if (value == null || value.Length == 0)
            {
                return(string.Empty);
            }

            byte[] pw    = DataProtection.Unprotect(value);
            char[] chars = new char[pw.Length / sizeof(char)];

            Buffer.BlockCopy(pw, 0, chars, 0, pw.Length);

            return(new string(chars));
        }
예제 #28
0
        public static void CreateUserCookie(UserProfile profile, UserModel employee, string password = null)
        {
            var cookie = new HttpCookie("UserProfileCookie");

            cookie["Id"]            = DataProtection.Encrypt(profile.Id.ToString());
            cookie["Name"]          = DataProtection.Encrypt(profile.Name);
            cookie["LoginName"]     = DataProtection.Encrypt(profile.LoginName);
            cookie["Password"]      = DataProtection.Encrypt(password);
            cookie["Email"]         = DataProtection.Encrypt(profile.Email);
            cookie["LastVisitTime"] = DataProtection.Encrypt(profile.LastVisitTime);
            cookie["BranchID"]      = DataProtection.Encrypt(profile.BranchID.ToString());
            cookie.Expires          = DateTime.Now.AddDays(7);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        public async Task <T> GetAsync <T>(string key)
        {
            byte[] content = await ReadFileContentAsync(GenerateStoredKey(key, typeof(T))).ConfigureAwait(false);

            TaskCompletionSource <T> tcs = new TaskCompletionSource <T>();

            if (content.Length == 0)
            {
                return(default(T));
            }

            var data = DataProtection.Unprotect(content);

            return(NewtonsoftJsonSerializer.Instance.Deserialize <T>(data));
        }
예제 #30
0
        public RdpConfig(string address, string username, string password)
        {
            if (string.IsNullOrEmpty(address))
            {
                throw new ArgumentNullException(nameof(address));
            }

            FullAddress = address;
            Username    = username;

            if ((password ?? "") != "")
            {
                Password = BitConverter.ToString(DataProtection.ProtectData(Encoding.Unicode.GetBytes(password), "")).Replace("-", "");
            }
        }