/// <summary>
        /// TODO: Comment
        /// </summary>
        public void SaveDataExcecute()
        {
            //TODO: Save path in configuration
            string configurationPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                                    "SecureVault",
                                                    "settings",
                                                    "configuration.dat");

            ConfigurationHelper configHelper       = new ConfigurationHelper(configurationPath);
            SecureStringHelper  secureStringHelper = new SecureStringHelper();
            KeyHelper           keyHelper          = new KeyHelper();
            SaltGenerator       saltGenerator      = new SaltGenerator();

            //Generate random salt
            byte[] salt = saltGenerator.GenerateSalt();

            byte[] key = keyHelper.DeriveKey(secureStringHelper.SecureStringToString(this.Password), configHelper.GetSalt());

            CryptoHelper cryptoHelper = new CryptoHelper(key, salt);

            var plainTextBytes      = Encoding.UTF8.GetBytes(secureStringHelper.SecureStringToString(this.SecureData));
            var plainPasswordBase64 = Convert.ToBase64String(plainTextBytes);

            string encryptedValue = cryptoHelper.EncryptValue(plainPasswordBase64);

            configHelper.AddData(this.Name, encryptedValue, Convert.ToBase64String(salt));

            //Close the NewData window
            Application.Current.Windows.OfType <Window>().SingleOrDefault(x => x.IsActive).Close();
        }
示例#2
0
        private void CreateWallet()
        {
            if (null == Password || null == ConfirmPassword)
            {
                return;
            }

            var pwd        = SecureStringHelper.SecureStringToString(Password);
            var confimrPwd = SecureStringHelper.SecureStringToString(ConfirmPassword);

            if (pwd != confimrPwd)
            {
                MessageBoxService.Show("两次输入的密码不匹配");
                return;
            }

            this.IsCreating = true;

            var result = WalletManager.CreateWallet(pwd);

            this.MnemonicWords = string.Join(" ", result.MnemonicWords);

            this.IsCreating  = false;
            this.IsCompleted = true;
        }
示例#3
0
        internal void ExecuteCommand()
        {
            var extensionRefs = GetPredicateExtensionList();

            WriteObject(
                extensionRefs == null ? null : extensionRefs.Select(
                    r =>
            {
                GetExtensionValues(r);
                var pubSettings = string.IsNullOrEmpty(PublicConfiguration) ? null
                                    : JsonConvert.DeserializeObject <PublicSettings>(PublicConfiguration);

                return(new VirtualMachineCustomScriptExtensionContext
                {
                    ExtensionName = r.Name,
                    Publisher = r.Publisher,
                    ReferenceName = r.ReferenceName,
                    Version = r.Version,
                    State = r.State,
                    PublicConfiguration = PublicConfiguration,
                    PrivateConfiguration = SecureStringHelper.GetSecureString(PrivateConfiguration),
                    CommandToExecute = pubSettings == null ? string.Empty : pubSettings.commandToExecute,
                    Uri = pubSettings == null ? null : pubSettings.fileUris,
                    RoleName = VM.GetInstance().RoleName
                });
            }), true);
        }
示例#4
0
 /// <summary>
 /// Adds a sink that sends log events to YouTrack.
 /// </summary>
 /// <param name="sinkConfiguration">The logger configuration.</param>
 /// <param name="youTrackEndpoint">YouTrack base address.</param>
 /// <param name="user">Username that is used to authenticate to YouTrack.</param>
 /// <param name="password">Password that is used to authenticate to YouTrack.</param>
 /// <param name="reportingConfiguration">Configure reporting parameters such as YouTrack project, issue types and templates. Project needs to always be configured.</param>
 /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>///
 /// <returns>Logger configuration, allowing configuration to continue.</returns>
 public static LoggerConfiguration YouTrack(this LoggerSinkConfiguration sinkConfiguration, Uri youTrackEndpoint,
                                            string user, string password,
                                            Action <IYouTrackReportingConfigurationExpressions> reportingConfiguration, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum)
 {
     return(YouTrack(sinkConfiguration, youTrackEndpoint, user, SecureStringHelper.ToSecureString(password),
                     reportingConfiguration, restrictedToMinimumLevel));
 }
示例#5
0
        public ShellApplication(object password, UserSessionService userSessionService, EventWaitHandle loadedEvent, string securityTokenXml)
        {
            if (password != null)
            {
                _password = SecureStringHelper.GetSecureString(Marshal.PtrToStringBSTR((IntPtr)password));
                SecureStringHelper.FreeString((IntPtr)password);
            }

            _userSessionService = userSessionService;
            _loadedEvent        = loadedEvent;

            if (securityTokenXml != null)
            {
                _tokenCache = Imi.Framework.UX.Identity.SecurityTokenCache.Deserialize(securityTokenXml);
            }
            else
            {
                _tokenCache = new Imi.Framework.UX.Identity.SecurityTokenCache();
            }

            _settingsLoadedEvent = new EventWaitHandle(false, EventResetMode.AutoReset);

            Thread.CurrentThread.CurrentUICulture = userSessionService.UICulture;

            Run();
        }
        /// <summary>
        /// Creates and returns <see cref="AutoBackupSettings"/> object.
        /// </summary>
        protected override void ProcessRecord()
        {
            AutoBackupSettings autoBackupSettings = new AutoBackupSettings();

            autoBackupSettings.Enable           = (Enable.IsPresent) ? Enable.ToBool() : false;
            autoBackupSettings.EnableEncryption = (EnableEncryption.IsPresent) ? EnableEncryption.ToBool() : false;
            autoBackupSettings.RetentionPeriod  = RetentionPeriodInDays;

            switch (ParameterSetName)
            {
            case StorageContextParamSetName:
                autoBackupSettings.StorageUrl       = StorageContext.BlobEndPoint;
                autoBackupSettings.StorageAccessKey = this.GetStorageKey();
                break;

            case StorageUriParamSetName:
                autoBackupSettings.StorageUrl       = (StorageUri == null)? null: StorageUri.ToString();
                autoBackupSettings.StorageAccessKey = (StorageKey == null)? null: SecureStringHelper.ConvertToUnsecureString(StorageKey);
                break;
            }

            // Check if certificate password was set
            autoBackupSettings.Password = (CertificatePassword == null) ? null : SecureStringHelper.ConvertToUnsecureString(CertificatePassword);

            WriteObject(autoBackupSettings);
        }
示例#7
0
        public void CreateAuthorizationRequest_should_have_expected_result()
        {
            var date                        = new DateTime(2020, 03, 12, 14, 23, 46);
            var accessKeyId                 = "permanentuser";
            var secretAccessKey             = "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake";
            var salt                        = new byte[] { 64, 230, 20, 164, 223, 96, 92, 144, 3, 240, 27, 110, 97, 65, 200, 11, 157, 162, 141, 4, 149, 86, 91, 108, 189, 194, 100, 90, 249, 219, 155, 235, };
            var host                        = "sts.amazonaws.com";
            var expectedAuthorizationHeader = "AWS4-HMAC-SHA256 " +
                                              "Credential=permanentuser/20200312/us-east-1/sts/aws4_request, " +
                                              "SignedHeaders=content-length;content-type;host;x-amz-date;x-mongodb-gs2-cb-flag;x-mongodb-server-nonce, " +
                                              "Signature=6872b9199b47dc983a95f9113a096c9b4e63bb6ddf39030161b1f092ab616df2";
            var expectedTimestamp = "20200312T142346Z";

            AwsSignatureVersion4.CreateAuthorizationRequest(
                date,
                accessKeyId,
                SecureStringHelper.ToSecureString(secretAccessKey),
                sessionToken: null,
                salt,
                host,
                out var actualAuthorizationHeader,
                out var actualTimestamp);

            actualAuthorizationHeader.Should().Be(expectedAuthorizationHeader);
            actualTimestamp.Should().Be(expectedTimestamp);
        }
示例#8
0
        public static bool Load(SecureString pasword)
        {
            try
            {
                byte[] xml = null;

                // Decrypt file
                if (File.Exists(GetCredentialsFilePath()))
                {
                    var cipherWithSaltAndIv = File.ReadAllBytes(GetCredentialsFilePath());

                    xml = Decrypt(cipherWithSaltAndIv, SecureStringHelper.ConvertToString(pasword));
                }

                // Save master pw for encryption
                SetMasterPassword(pasword);

                // Check if array is empty...
                if (xml != null && xml.Length > 0)
                {
                    DeserializeFromByteArray(xml);
                }

                Credentials.CollectionChanged += Credentials_CollectionChanged;

                IsLoaded = true;

                return(true);
            }
            catch (CryptographicException)
            {
                return(false);
            }
        }
示例#9
0
        /// <summary>
        /// GetObjectData
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                return;
            }

            // serialize the secure string
            string safePassword = string.Empty;

            if (_password != null && _password.Length > 0)
            {
                byte[] key;
                byte[] iv;
                if (s_delegate != null && s_delegate(context, out key, out iv))
                {
                    safePassword = SecureStringHelper.Encrypt(_password, key, iv).EncryptedData;
                }
                else
                {
                    try
                    {
                        safePassword = SecureStringHelper.Protect(_password);
                    }
                    catch (CryptographicException cryptographicException)
                    {
                        throw PSTraceSource.NewInvalidOperationException(cryptographicException, Credential.CredentialDisallowed);
                    }
                }
            }

            info.AddValue("UserName", _userName);
            info.AddValue("Password", safePassword);
        }
示例#10
0
        public void CreateAuthorizationRequest_with_session_token_should_have_expected_result()
        {
            var date                        = new DateTime(2020, 03, 12, 14, 23, 46);
            var accessKeyId                 = "permanentuser";
            var secretAccessKey             = "FAKEFAKEFAKEFAKEFAKEfakefakefakefakefake";
            var sessionToken                = "MXUpbuzwzPo67WKCNYtdBq47taFtIpt+SVx58hNx1/jSz37h9d67dtUOg0ejKrv83u8ai+VFZxMx=";
            var salt                        = new byte[] { 64, 230, 20, 164, 223, 96, 92, 144, 3, 240, 27, 110, 97, 65, 200, 11, 157, 162, 141, 4, 149, 86, 91, 108, 189, 194, 100, 90, 249, 219, 155, 235, };
            var host                        = "sts.amazonaws.com";
            var expectedAuthorizationHeader = "AWS4-HMAC-SHA256 " +
                                              "Credential=permanentuser/20200312/us-east-1/sts/aws4_request, " +
                                              "SignedHeaders=content-length;content-type;host;x-amz-date;x-amz-security-token;x-mongodb-gs2-cb-flag;x-mongodb-server-nonce, " +
                                              "Signature=d60ee7fe01c82631583a7534fe017e1840fd5975faf1593252e91c54573a93ae";
            var expectedTimestamp = "20200312T142346Z";

            AwsSignatureVersion4.CreateAuthorizationRequest(
                date,
                accessKeyId,
                SecureStringHelper.ToSecureString(secretAccessKey),
                sessionToken,
                salt,
                host,
                out var actualAuthorizationHeader,
                out var actualTimestamp);

            actualAuthorizationHeader.Should().Be(expectedAuthorizationHeader);
            actualTimestamp.Should().Be(expectedTimestamp);
        }
        protected void SetProvisioningConfiguration(LinuxProvisioningConfigurationSet provisioningConfiguration)
        {
            provisioningConfiguration.UserName     = LinuxUser;
            provisioningConfiguration.UserPassword = SecureStringHelper.GetSecureString(Password);
            if (NoSSHPassword.IsPresent)
            {
                provisioningConfiguration.UserPassword = SecureStringHelper.GetSecureString(String.Empty);
            }

            if (DisableSSH.IsPresent || NoSSHPassword.IsPresent)
            {
                provisioningConfiguration.DisableSshPasswordAuthentication = true;
            }
            else
            {
                provisioningConfiguration.DisableSshPasswordAuthentication = false;
            }

            if (SSHKeyPairs != null && SSHKeyPairs.Count > 0 || SSHPublicKeys != null && SSHPublicKeys.Count > 0)
            {
                provisioningConfiguration.SSH = new LinuxProvisioningConfigurationSet.SSHSettings {
                    PublicKeys = SSHPublicKeys, KeyPairs = SSHKeyPairs
                };
            }

            if (!string.IsNullOrEmpty(CustomDataFile))
            {
                string fileName = this.TryResolvePath(this.CustomDataFile);
                provisioningConfiguration.CustomData = PersistentVMHelper.ConvertCustomDataFileToBase64(fileName);
            }
        }
        internal void ExecuteCommand()
        {
            var extensionRefs = GetPredicateExtensionList();

            WriteObject(
                extensionRefs == null ? null : extensionRefs.Select(
                    r =>
            {
                GetVMAccessExtensionValues(r);
                return(new VirtualMachineAccessExtensionContext
                {
                    ExtensionName = r.Name,
                    Publisher = r.Publisher,
                    ReferenceName = r.ReferenceName,
                    Version = r.Version,
                    State = r.State,
                    Enabled = !Disable,
                    UserName = UserName,
                    Password = SecureStringHelper.GetSecureString(Password),
                    PublicConfiguration = PublicConfiguration,
                    PrivateConfiguration = SecureStringHelper.GetSecureString(PrivateConfiguration),
                    RoleName = VM.GetInstance().RoleName
                });
            }), true);
        }
        protected void SetProvisioningConfiguration(LinuxProvisioningConfigurationSet provisioningConfiguration)
        {
            provisioningConfiguration.UserName     = LinuxUser;
            provisioningConfiguration.UserPassword = SecureStringHelper.GetSecureString(Password);
            if (NoSSHPassword.IsPresent)
            {
                provisioningConfiguration.UserPassword = SecureStringHelper.GetSecureString(String.Empty);
            }

            if (DisableSSH.IsPresent || NoSSHPassword.IsPresent)
            {
                provisioningConfiguration.DisableSshPasswordAuthentication = true;
            }
            else
            {
                provisioningConfiguration.DisableSshPasswordAuthentication = false;
            }

            if (SSHKeyPairs != null && SSHKeyPairs.Count > 0 || SSHPublicKeys != null && SSHPublicKeys.Count > 0)
            {
                provisioningConfiguration.SSH = new LinuxProvisioningConfigurationSet.SSHSettings {
                    PublicKeys = SSHPublicKeys, KeyPairs = SSHKeyPairs
                };
            }
        }
        protected void SetProvisioningConfiguration(WindowsProvisioningConfigurationSet provisioningConfiguration)
        {
            provisioningConfiguration.AdminUsername             = AdminUsername;
            provisioningConfiguration.AdminPassword             = SecureStringHelper.GetSecureString(Password);
            provisioningConfiguration.ResetPasswordOnFirstLogon = ResetPasswordOnFirstLogon.IsPresent;
            provisioningConfiguration.StoredCertificateSettings = CertUtilsNewSM.GetCertificateSettings(Certificates, X509Certificates);
            provisioningConfiguration.EnableAutomaticUpdates    = !DisableAutomaticUpdates.IsPresent;

            if (provisioningConfiguration.StoredCertificateSettings == null)
            {
                provisioningConfiguration.StoredCertificateSettings = new CertificateSettingList();
            }

            if (!string.IsNullOrEmpty(TimeZone))
            {
                provisioningConfiguration.TimeZone = TimeZone;
            }

            if (WindowsDomainParameterSetName.Equals(ParameterSetName, StringComparison.OrdinalIgnoreCase))
            {
                provisioningConfiguration.DomainJoin = new WindowsProvisioningConfigurationSet.DomainJoinSettings
                {
                    Credentials = new WindowsProvisioningConfigurationSet.DomainJoinCredentials
                    {
                        Username = DomainUserName,
                        Password = SecureStringHelper.GetSecureString(DomainPassword),
                        Domain   = Domain
                    },
                    MachineObjectOU = MachineObjectOU,
                    JoinDomain      = JoinDomain
                };
            }
        }
示例#15
0
        private void Save(FileInfo file)
        {
            byte[] usernameBytes = Encoding.Unicode.GetBytes(Username);
            byte[] passwordBytes = new byte[SecureStringHelper.GetSecureStringByteCount(Password, Encoding.Unicode)];
            SecureStringHelper.SecureStringToBytes(Password, passwordBytes, 0, Encoding.Unicode);

            try
            {
                byte[] entropy = GenerateEntropy();
                byte[] protectedUsernameBytes = ProtectedData.Protect(usernameBytes, entropy, DataProtectionScope.CurrentUser);
                byte[] protectedPasswordBytes = ProtectedData.Protect(passwordBytes, entropy, DataProtectionScope.CurrentUser);

                var template = new CredentialsExportTemplate()
                {
                    Entropy           = Convert.ToBase64String(entropy),
                    ProtectedUsername = Convert.ToBase64String(protectedUsernameBytes),
                    ProtectedPassword = Convert.ToBase64String(protectedPasswordBytes),
                };

                JsonHelper.Serialize(template, file);
            }
            finally
            {
                SecureStringHelper.DestroySecureByteArray(passwordBytes);
            }
        }
示例#16
0
        /// <summary>
        /// PSCredential
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        private PSCredential(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                return;
            }

            _userName = (string)info.GetValue("UserName", typeof(string));

            // deserialize to secure string
            string safePassword = (string)info.GetValue("Password", typeof(string));

            if (safePassword == string.Empty)
            {
                _password = new SecureString();
            }
            else
            {
                byte[] key;
                byte[] iv;
                if (s_delegate != null && s_delegate(context, out key, out iv))
                {
                    _password = SecureStringHelper.Decrypt(safePassword, key, iv);
                }
                else
                {
                    _password = SecureStringHelper.Unprotect(safePassword);
                }
            }
        }
示例#17
0
        private static AwsCredentials CreateAwsCredentialsFromEnvironmentVariables()
        {
            var accessKeyId     = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID");
            var secretAccessKey = Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY");
            var sessionToken    = Environment.GetEnvironmentVariable("AWS_SESSION_TOKEN");

            if (accessKeyId == null && secretAccessKey == null && sessionToken == null)
            {
                return(null);
            }
            if (secretAccessKey != null && accessKeyId == null)
            {
                throw new InvalidOperationException("When using MONGODB-AWS authentication if a secret access key is provided via environment variables then an access key ID must be provided also.");
            }
            if (accessKeyId != null && secretAccessKey == null)
            {
                throw new InvalidOperationException("When using MONGODB-AWS authentication if an access key ID is provided via environment variables then a secret access key must be provided also.");
            }
            if (sessionToken != null && (accessKeyId == null || secretAccessKey == null))
            {
                throw new InvalidOperationException("When using MONGODB-AWS authentication if a session token is provided via environment variables then an access key ID and a secret access key must be provided also.");
            }

            return(new AwsCredentials(accessKeyId, SecureStringHelper.ToSecureString(secretAccessKey), sessionToken));
        }
示例#18
0
文件: Main.cs 项目: imnista/PassBerry
        private string GetCurrentPasteValue()
        {
            if (this.dataGridViewMain.SelectedRows.Count < 1)
            {
                return(null);
            }
            var currentSelectedItem = (Guid)this.dataGridViewMain.SelectedRows[0].Cells["Id"].Value;
            var record = allDataCache.Find(i => i.Id == currentSelectedItem);

            if (IsCurrentPasteUsername)
            {
                this.IsCurrentPasteUsername = false;
                if (string.IsNullOrWhiteSpace(record.Username))
                {
                    return(null);
                }
                return(record.Username);
            }
            else
            {
                this.IsCurrentPasteUsername = true;
                if (record.Password == null)
                {
                    return(null);
                }
                return(SecureStringHelper.GetStringFromSecureString(record.Password));
            }
        }
        internal void ExecuteCommand()
        {
            List <ResourceExtensionReference> extensionRefs = GetPredicateExtensionList();

            WriteObject(
                extensionRefs == null ? null : extensionRefs.Select(
                    r =>
            {
                GetExtensionValues(r);
                DscPublicSettings publicSettings = null;
                try
                {
                    publicSettings = DscSettingsSerializer.DeserializePublicSettings(PublicConfiguration);
                }
                catch (JsonException e)
                {
                    this.ThrowTerminatingError(
                        new ErrorRecord(
                            new JsonException(
                                String.Format(
                                    CultureInfo.CurrentUICulture,
                                    Properties.Resources.AzureVMDscWrongSettingsFormat,
                                    PublicConfiguration),
                                e),
                            string.Empty,
                            ErrorCategory.ParserError,
                            null));
                }
                var context = new VirtualMachineDscExtensionContext
                {
                    ExtensionName        = r.Name,
                    Publisher            = r.Publisher,
                    ReferenceName        = r.ReferenceName,
                    Version              = r.Version,
                    State                = r.State,
                    RoleName             = VM.GetInstance().RoleName,
                    PublicConfiguration  = PublicConfiguration,
                    PrivateConfiguration = SecureStringHelper.GetSecureString(PrivateConfiguration)
                };

                if (publicSettings == null)
                {
                    context.ModulesUrl            = string.Empty;
                    context.ConfigurationFunction = string.Empty;
                    context.Properties            = null;
                }
                else
                {
                    context.ModulesUrl            = publicSettings.ModulesUrl;
                    context.ConfigurationFunction = publicSettings.ConfigurationFunction;
                    context.Properties            = new Hashtable(publicSettings.Properties.ToDictionary(x => x.Name, x => x.Value));
                }

                return(context);
            }

                    ).FirstOrDefault());
        }
        public void Should_acquire_gssapi_security_credential_with_username_and_password()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var securePassword = SecureStringHelper.ToSecureString(_password);
            var credential     = GssapiSecurityCredential.Acquire(_username, securePassword);

            credential.Should().NotBeNull();
        }
        protected ResourceExtensionReference NewResourceExtension()
        {
            var extensionRef = new ResourceExtensionReference();

            extensionRef.Name      = this.ExtensionName;
            extensionRef.Publisher = this.Publisher;
            extensionRef.Version   = this.Version;
            extensionRef.State     = IsLegacyExtension() ? null :
                                     this.Uninstall.IsPresent ? ReferenceUninstallStateStr :
                                     this.Disable.IsPresent ? ReferenceDisableStateStr : ReferenceEnableStateStr;
            extensionRef.ResourceExtensionParameterValues = new ResourceExtensionParameterValueList();

            if (!string.IsNullOrEmpty(this.ReferenceName))
            {
                extensionRef.ReferenceName = this.ReferenceName;
            }
            else
            {
                extensionRef.ReferenceName = extensionRef.Name;
            }

            if (!string.IsNullOrEmpty(this.PublicConfigPath))
            {
                this.PublicConfiguration = FileUtilities.DataStore.ReadFileAsText(this.PublicConfigPath);
            }

            if (!string.IsNullOrEmpty(this.PublicConfiguration))
            {
                extensionRef.ResourceExtensionParameterValues.Add(
                    new ResourceExtensionParameterValue
                {
                    Key = !string.IsNullOrEmpty(this.PublicConfigKey) ? this.PublicConfigKey
                            : ExtensionName + (IsLegacyExtension() ? string.Empty : PublicTypeStr) + "ConfigParameter",
                    Type  = IsLegacyExtension() ? null : PublicTypeStr,
                    Value = PublicConfiguration
                });
            }

            if (!string.IsNullOrEmpty(this.PrivateConfigPath))
            {
                this.PrivateConfiguration = FileUtilities.DataStore.ReadFileAsText(this.PrivateConfigPath);
            }

            if (!string.IsNullOrEmpty(this.PrivateConfiguration))
            {
                extensionRef.ResourceExtensionParameterValues.Add(
                    new ResourceExtensionParameterValue
                {
                    Key = !string.IsNullOrEmpty(this.PrivateConfigKey) ? this.PrivateConfigKey
                            : ExtensionName + (IsLegacyExtension() ? string.Empty : PrivateTypeStr) + "ConfigParameter",
                    Type        = IsLegacyExtension() ? null : PrivateTypeStr,
                    SecureValue = SecureStringHelper.GetSecureString(PrivateConfiguration)
                });
            }

            return(extensionRef);
        }
        public void Example_SecureStringHelper()
        {
            SecureString pin = this.ObtrainPin();

            SecureStringHelper.ExecuteWithSecureString(pin, Encoding.UTF8, pin =>
            {
                SetPinToDevice(pin);
            });
        }
示例#23
0
 public RecordForDisplay(Record data)
 {
     this.Id             = data.Id;
     this.Name           = data.Name;
     this.PictureForLogo = ImageHelper.GetImageFromBase64String(data.PictureForLogo);
     this.Keywords       = data.Keywords;
     this.Username       = data.Username;
     this.Password       = SecureStringHelper.GetSecureStringFromString(data.Password);
     this.Remarks        = data.Remarks;
 }
示例#24
0
        public void SetLockPassword(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException("password");
            }

            this.LockPasswordHash = SecureStringHelper.HashPassword(password);
            this.SaveToFile();
        }
        public void Should_fail_to_acquire_gssapi_security_credential_with_username_and_bad_password()
        {
            RequireEnvironment.Check().EnvironmentVariable("GSSAPI_TESTS_ENABLED");

            var securePassword = SecureStringHelper.ToSecureString("BADPASSWORD");

            var exception = Record.Exception(() => GssapiSecurityCredential.Acquire(_username, securePassword));

            exception.Should().BeOfType <LibgssapiException>();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UsernamePasswordCredential"/> class.
 /// Less secure when used in conjunction with SCRAM-SHA-256, due to the need to store the password in a managed
 /// string in order to SaslPrep it.
 /// See <a href="https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst#scram-sha-256">Driver Authentication: SCRAM-SHA-256</a>
 /// for additional details.
 /// </summary>
 /// <param name="source">The source.</param>
 /// <param name="username">The username.</param>
 /// <param name="password">The password.</param>
 public UsernamePasswordCredential(string source, string username, SecureString password)
 {
     _source   = Ensure.IsNotNullOrEmpty(source, nameof(source));
     _username = Ensure.IsNotNullOrEmpty(username, nameof(username));
     _password = Ensure.IsNotNull(password, nameof(password));
     // defer computing the saslPreppedPassword until we need to since this will leak the password into managed
     // memory
     _saslPreppedPassword = new Lazy <SecureString>(
         () => SecureStringHelper.ToSecureString(SaslPrepHelper.SaslPrepStored(GetInsecurePassword())));
 }
示例#27
0
        private static AwsCredentials CreateAwsCredentialsFromEc2Response()
        {
            var response        = AwsHttpClientHelper.GetEC2ResponseAsync().GetAwaiter().GetResult();
            var parsedResponse  = BsonDocument.Parse(response);
            var accessKeyId     = parsedResponse.GetValue("AccessKeyId", null)?.AsString;
            var secretAccessKey = parsedResponse.GetValue("SecretAccessKey", null)?.AsString;
            var sessionToken    = parsedResponse.GetValue("Token", null)?.AsString;

            return(new AwsCredentials(accessKeyId, SecureStringHelper.ToSecureString(secretAccessKey), sessionToken));
        }
        // constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="UsernamePasswordCredential"/> class.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        public UsernamePasswordCredential(string source, string username, string password)
            : this(source, username, SecureStringHelper.ToSecureString(password))
        {
            // Compute saslPreppedPassword immediately and store it securely while the password is already in
            // managed memory. We don't create a closure over the password so that it will hopefully get
            // garbage-collected sooner rather than later.
            var saslPreppedPassword = SecureStringHelper.ToSecureString(SaslPrepHelper.SaslPrepStored(password));

            _saslPreppedPassword = new Lazy <SecureString>(() => saslPreppedPassword);
        }
 public static void Login(this ISession session, CKU userType, SecureString securePin)
 {
     if (securePin == null)
     {
         session.Login(userType, pin: null as byte[]);
     }
     else
     {
         SecureStringHelper.ExecuteWithSecureString(securePin, Encoding.UTF8, pin => session.Login(userType, pin));
     }
 }
示例#30
0
        /// <summary>
        /// Processes records from the input pipeline.
        /// For each input object, the command encrypts
        /// and exports the object.
        /// </summary>
        protected override void ProcessRecord()
        {
            string           exportedString   = null;
            EncryptionResult encryptionResult = null;

            const string argumentName = "SecureString";

            Utils.CheckSecureStringArg(SecureStringData, argumentName);
            if (SecureStringData.Length == 0)
            {
                throw PSTraceSource.NewArgumentException(argumentName);
            }

            if (SecureKey != null)
            {
                Dbg.Diagnostics.Assert(Key == null, "Only one encryption key should be specified");
                encryptionResult = SecureStringHelper.Encrypt(SecureString, SecureKey);
            }
            else if (Key != null)
            {
                encryptionResult = SecureStringHelper.Encrypt(SecureString, Key);
            }
            else
            {
                exportedString = SecureStringHelper.Protect(SecureString);
            }

            if (encryptionResult != null)
            {
                // The formatted string is Algorithm Version,
                // Initialization Vector, Encrypted Data
                string dataPackage = string.Format(
                    System.Globalization.CultureInfo.InvariantCulture,
                    "{0}|{1}|{2}",
                    2,
                    encryptionResult.IV,
                    encryptionResult.EncryptedData);

                // encode the package, and output it.
                // We also include a recognizable prefix so that
                // we can use the old decryption mechanism if we
                // don't see it. While the old decryption
                // generated invalid data for the first bit of the
                // SecureString, it at least didn't generate an
                // exception.
                byte[] outputBytes   = System.Text.Encoding.Unicode.GetBytes(dataPackage);
                string encodedString = Convert.ToBase64String(outputBytes);
                WriteObject(SecureStringHelper.SecureStringExportHeader + encodedString);
            }
            else if (exportedString != null)
            {
                WriteObject(exportedString);
            }
        }