Esempio n. 1
0
 private byte[] ProtectPassword(UserEntity usr, string password)
 {
     return(ProtectedData.Protect(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(usr.Username), DataProtectionScope.LocalMachine));
 }
Esempio n. 2
0
        internal static string Protect(string str)
        {
            var entropy = Encoding.ASCII.GetBytes(Environment.MachineName);

            return(Convert.ToBase64String(ProtectedData.Protect(Encoding.ASCII.GetBytes(str), entropy, DataProtectionScope.CurrentUser)));
        }
Esempio n. 3
0
 /// <summary>
 /// Encrypts the symmetric key.
 /// </summary>
 /// <remarks>
 /// The method is called by the GoF template-methods.
 /// </remarks>
 /// <returns>System.Byte[].</returns>
 protected override byte[] EncryptSymmetricKey()
 => ProtectedData.Protect(Symmetric.Key, null, DataProtectionScope.LocalMachine);
 public string EncryptString(string serverName, string accountName, string password)
 {
     return(Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(password ?? string.Empty), saltBytes, DataProtectionScope.CurrentUser)));
 }
 public virtual byte[] Protect(byte[] userData)
 {
     return(ProtectedData.Protect(userData, null, DataProtectionScope.LocalMachine));
 }
Esempio n. 6
0
 public string Encrypt(string unencrypted)
 {
     byte[] tmp = ProtectedData.Protect(encoder.GetBytes(unencrypted), entropy, DataProtectionScope.LocalMachine);
     return(Convert.ToBase64String(Encrypt(tmp)));
 }
Esempio n. 7
0
 public void SetPassword(string password)
 {
     Password = Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(password), null, DataProtectionScope.CurrentUser));
 }
 protected internal override byte [] EncodeSecurityState(byte [] data)
 {
     return(ProtectedData.Protect(data, entropy, DataProtectionScope.CurrentUser));
 }
Esempio n. 9
0
 public static string EncryptString(string clearText)
 {
     byte[] decryptedTextBytes = ASCIIEncoding.ASCII.GetBytes(clearText);
     byte[] encryptedTextBytes = ProtectedData.Protect(decryptedTextBytes, entropicData, DataProtectionScope.CurrentUser);
     return(Convert.ToBase64String(encryptedTextBytes));
 }
 public static string SymEncryptLocalPC(string data)
 {
     byte[] bytes = Encoding.UTF8.GetBytes(data);
     bytes = ProtectedData.Protect(bytes, aditionalEntropy, DataProtectionScope.LocalMachine);
     return(Convert.ToBase64String(bytes));
 }
Esempio n. 11
0
 private string EncryptToken(AuthTokenResponse token, byte[] salt) =>
 Convert.ToBase64String(
     ProtectedData.Protect(
         JsonSerializer.SerializeToUtf8Bytes(token),
         salt,
         DataProtectionScope.CurrentUser));
Esempio n. 12
0
 internal static string Protect(string value)
 {
     byte[] rawData = Encoding.UTF8.GetBytes(value);
     byte[] encData = ProtectedData.Protect(rawData, EntropyBytes, DataProtectionScope.CurrentUser);
     return(Convert.ToBase64String(encData));
 }
Esempio n. 13
0
 public byte[] Protect(byte[] unprotectedData)
 {
     return(ProtectedData.Protect(unprotectedData, null, DataProtectionScope.CurrentUser));
 }
        public IBuildServerCredentials GetBuildServerCredentials(IBuildServerAdapter buildServerAdapter, bool useStoredCredentialsIfExisting)
        {
            lock (_buildServerCredentialsLock)
            {
                IBuildServerCredentials buildServerCredentials = new BuildServerCredentials {
                    UseGuestAccess = true
                };
                var foundInConfig = false;

                const string CredentialsConfigName = "Credentials";
                const string UseGuestAccessKey     = "UseGuestAccess";
                const string UsernameKey           = "Username";
                const string PasswordKey           = "Password";
                using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Read, FileShare.Read))
                {
                    if (stream.Position < stream.Length)
                    {
                        var protectedData = new byte[stream.Length];

                        stream.Read(protectedData, 0, (int)stream.Length);
                        try
                        {
                            byte[] unprotectedData = ProtectedData.Unprotect(protectedData, null,
                                                                             DataProtectionScope.CurrentUser);
                            using (var memoryStream = new MemoryStream(unprotectedData))
                            {
                                var credentialsConfig = new ConfigFile("", false);

                                using (var textReader = new StreamReader(memoryStream, Encoding.UTF8))
                                {
                                    credentialsConfig.LoadFromString(textReader.ReadToEnd());
                                }

                                var section = credentialsConfig.FindConfigSection(CredentialsConfigName);

                                if (section != null)
                                {
                                    buildServerCredentials.UseGuestAccess = section.GetValueAsBool(UseGuestAccessKey,
                                                                                                   true);
                                    buildServerCredentials.Username = section.GetValue(UsernameKey);
                                    buildServerCredentials.Password = section.GetValue(PasswordKey);
                                    foundInConfig = true;

                                    if (useStoredCredentialsIfExisting)
                                    {
                                        return(buildServerCredentials);
                                    }
                                }
                            }
                        }
                        catch (CryptographicException)
                        {
                            // As per MSDN, the ProtectedData.Unprotect method is per user,
                            // it will throw the CryptographicException if the current user
                            // is not the one who protected the data.

                            // Set this variable to false so the user can reset the credentials.
                            useStoredCredentialsIfExisting = false;
                        }
                    }
                }

                if (!useStoredCredentialsIfExisting || !foundInConfig)
                {
                    buildServerCredentials = ThreadHelper.JoinableTaskFactory.Run(() => ShowBuildServerCredentialsFormAsync(buildServerAdapter.UniqueKey, buildServerCredentials));

                    if (buildServerCredentials != null)
                    {
                        var credentialsConfig = new ConfigFile("", true);

                        var section = credentialsConfig.FindOrCreateConfigSection(CredentialsConfigName);

                        section.SetValueAsBool(UseGuestAccessKey, buildServerCredentials.UseGuestAccess);
                        section.SetValue(UsernameKey, buildServerCredentials.Username);
                        section.SetValue(PasswordKey, buildServerCredentials.Password);

                        using (var stream = GetBuildServerOptionsIsolatedStorageStream(buildServerAdapter, FileAccess.Write, FileShare.None))
                        {
                            using (var memoryStream = new MemoryStream())
                            {
                                using (var textWriter = new StreamWriter(memoryStream, Encoding.UTF8))
                                {
                                    textWriter.Write(credentialsConfig.GetAsString());
                                }

                                var protectedData = ProtectedData.Protect(memoryStream.ToArray(), null, DataProtectionScope.CurrentUser);
                                stream.Write(protectedData, 0, protectedData.Length);
                            }
                        }

                        return(buildServerCredentials);
                    }
                }

                return(null);
            }
        }
        public static string GetSqlConnectionString(string stampName, bool forceValidate = false, bool forceRenew = false)
        {
            string connStr = null;

            if (!forceRenew && SqlConnectionStrings.TryGetValue(stampName, out connStr))
            {
                return(connStr);
            }

            var file = string.Format(@"{0}\{1}.ro-sql.txt", CacheDirectory.Value, stampName);

            if (!forceRenew && File.Exists(file))
            {
                try
                {
                    var encrypted = Convert.FromBase64String(File.ReadAllText(file));
                    connStr = Encoding.UTF8.GetString(ProtectedData.Unprotect(encrypted, null, DataProtectionScope.CurrentUser));
                    if (!forceValidate || ValidateSqlConnectionString(stampName, connStr))
                    {
                        SqlConnectionStrings[stampName] = connStr;
                        return(connStr);
                    }
                }
                catch (Exception)
                {
                }
            }

            var db = "hosting";

            if (stampName.StartsWith("gm-"))
            {
                db = "geomaster";
            }
            else if (stampName.StartsWith("gr-"))
            {
                db = "georegionservice";
            }

            try
            {
                var privateDefinition = string.Format(@"\\AntaresDeployment\PublicLockbox\{0}\developer.definitions", stampName);
                if (File.Exists(privateDefinition))
                {
                    connStr = ReadFromPrivateDefinition(privateDefinition);
                }
                else
                {
                    //connStr = AntaresDiagnosticsCommon.Value.GetHostingDBConnectionStringForStamp(stampName, db);
                    connStr = GetConnectionStringAsync(db, stampName).Result;
                }

                if (ValidateSqlConnectionString(stampName, connStr))
                {
                    var encrypted = ProtectedData.Protect(Encoding.UTF8.GetBytes(connStr), null, DataProtectionScope.CurrentUser);
                    File.WriteAllText(file, Convert.ToBase64String(encrypted));
                    SqlConnectionStrings[stampName] = connStr;
                    return(connStr);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine("R/O SqlConnection {0} failed with {1}", stampName, ex.Message);
                Console.WriteLine();
                if (forceRenew)
                {
                    throw;
                }
            }

            return(null);
        }
 public static string Protect(string data)
 {
     byte[] bytes     = Encoding.UTF8.GetBytes(data);
     byte[] encrypted = ProtectedData.Protect(bytes, null, DataProtectionScope.LocalMachine);
     return(Convert.ToBase64String(encrypted));
 }
Esempio n. 17
0
 /// <summary>
 /// Protects the specified user data.
 /// </summary>
 /// <param name="userData">The user data.</param>
 /// <param name="entropy">The entropy.</param>
 /// <returns>The protected user data.</returns>
 public byte[] Protect(byte[] userData, byte[] entropy)
 {
     return(ProtectedData.Protect(userData, entropy, DataProtectionScope.CurrentUser));
 }
Esempio n. 18
0
 protected KeyVaultFile(T obj)
 {
     CreatedBy    = $"{Environment.UserDomainName}\\{Environment.UserName}";
     CreationTime = DateTimeOffset.UtcNow;
     Data         = ProtectedData.Protect(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj, Formatting.Indented)), null, DataProtectionScope.CurrentUser);
 }
Esempio n. 19
0
 private static byte[] EncryptWithDpapi(string value) => ProtectedData.Protect(Encoding.UTF8.GetBytes(value), OptionalEntropy, DataProtectionScope.CurrentUser);
Esempio n. 20
0
 public string Encrypt(byte[] valueToEncrypt)
 => ProtectedData.Protect(valueToEncrypt, null, DataProtectionScope).ToBase64String();
Esempio n. 21
0
        private static void Main(string[] args)
        {
            const string dataToProtect        = "This is a bunch of super secret content!";
            var          dataToProtectAsArray = Encoding.Unicode.GetBytes(dataToProtect);

            #region File.Encrypt

            var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                                        "MyDataFile.txt");

            // Encrypt a file in the file system
            File.WriteAllText(fileName, dataToProtect);

            // now we can encrypt it - only we can access it now
            File.Encrypt(fileName);

            #endregion

            #region Windows Data Protection

            // Windows Data Protection (we can also protect for the LocalMachine too)
            // note, the null can be replaced with a byte[] for additional entropy
            var wdpEncryptedData = ProtectedData.Protect(dataToProtectAsArray, null, DataProtectionScope.CurrentUser);

            var wdpUnEncryptedData   = ProtectedData.Unprotect(wdpEncryptedData, null, DataProtectionScope.CurrentUser);
            var wdpUnencryptedString = Encoding.Unicode.GetString(wdpUnEncryptedData);

            Debug.Assert(dataToProtect.Equals(wdpUnencryptedString));

            #endregion

            #region Hashing
            // hashing - one-way encryption

            // this represents a hashed password stored in a database
            var storedPasswordHash = new byte[]
            {
                148, 152, 235, 251, 242, 51, 18, 100, 176, 51, 147, 249, 128, 175, 164, 106, 204, 48, 47, 154, 75,
                82, 83, 170, 111, 8, 107, 51, 13, 83, 2, 252
            };

            var password     = Encoding.Unicode.GetBytes("P4ssw0rd!");
            var passwordHash = SHA256.Create().ComputeHash(password);

            // nice convenience method - can also supply a custom comparator
            if (passwordHash.SequenceEqual(storedPasswordHash))
            {
                Console.WriteLine("Passwords match!");
            }
            #endregion

            #region Symmetric
            // symmetric encryption

            // Uses Rijndael as an algorithm
            // two classes Rijndael and Aes - use Aes (more secure)

            // array of 16 random bytes
            // must be used for decryption
            // should be secret
            var key = new byte[] { 12, 2, 56, 117, 12, 67, 33, 23, 12, 2, 56, 117, 12, 67, 33, 23 };

            // another list of 16 bytes - can be shared publically, should be changed for each message exchange
            var initializationVector = new byte[] { 37, 99, 102, 23, 12, 22, 156, 204, 11, 12, 23, 44, 55, 1, 157, 233 };

            byte[] symEncryptedData;

            // save for reuse
            var algorithm = Aes.Create();

            // encrypt
            using (var encryptor = algorithm.CreateEncryptor(key, initializationVector))
                using (var memoryStream = new MemoryStream())
                    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(dataToProtectAsArray, 0, dataToProtectAsArray.Length);
                        cryptoStream.FlushFinalBlock();
                        symEncryptedData = memoryStream.ToArray();
                    }

            // decrypt
            byte[] symUnencryptedData;
            using (var decryptor = algorithm.CreateDecryptor(key, initializationVector))
                using (var memoryStream = new MemoryStream())
                    using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(symEncryptedData, 0, symEncryptedData.Length);
                        cryptoStream.FlushFinalBlock();
                        symUnencryptedData = memoryStream.ToArray();
                    }

            algorithm.Dispose();

            if (dataToProtectAsArray.SequenceEqual(symUnencryptedData))
            {
                Console.WriteLine("Symmetric encrypted values match!");
            }

            #endregion

            #region Asymmetric

            byte[] signature;
            byte[] publicAndPrivateKey;
            byte[] publicKeyOnly;
            var    hashImplementation = SHA1.Create();

            // create a signature, create our public and private keys - we could save these out as XML, etc.
            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                signature           = rsaProvider.SignData(dataToProtectAsArray, hashImplementation);
                publicAndPrivateKey = rsaProvider.ExportCspBlob(true);
                publicKeyOnly       = rsaProvider.ExportCspBlob(false);
            }

            // create a new RSA
            using (var rsaProvider = new RSACryptoServiceProvider())
            {
                // import our public key
                rsaProvider.ImportCspBlob(publicKeyOnly);

                // has it been tampered with?
                if (!rsaProvider.VerifyData(dataToProtectAsArray, hashImplementation, signature))
                {
                    Console.WriteLine("Data has been tampered with");
                }

                // now let's tamper with our data

                dataToProtectAsArray[5] = 255;
                if (!rsaProvider.VerifyData(dataToProtectAsArray, hashImplementation, signature))
                {
                    Console.WriteLine("Data has been tampered with");
                }
            }

            hashImplementation.Dispose();

            #endregion
        }
Esempio n. 22
0
 public static string ProtectLocalPassword(string str)
 {
     byte[] entropy = Encoding.ASCII.GetBytes(Assembly.GetExecutingAssembly().FullName);
     byte[] data    = Encoding.ASCII.GetBytes(str);
     return(Convert.ToBase64String(ProtectedData.Protect(data, entropy, DataProtectionScope.CurrentUser)));
 }
        public void AfterAccessNotification(TokenCacheNotificationArgs args)
        {
            // if the access operation resulted in a cache update
            if (args.TokenCache.HasStateChanged)
            {
                lock (FileLock)
                {
                    var fileTask = storageService.UploadBlobAsync(configuration["TokenCacheBlobName"], ProtectedData.Protect(args.TokenCache.Serialize(), null, DataProtectionScope.CurrentUser));

                    Task.WaitAll(fileTask);

                    // once the write operationtakes place restore the HasStateChanged bit to filse
                    args.TokenCache.HasStateChanged = false;
                }
            }
        }
Esempio n. 24
0
        public byte[] Serialize(IDictionary <string, object> sessionState)
        {
            var unprotectedBytes = _innerSessionStateSerializer.Serialize(sessionState);

            return(ProtectedData.Protect(unprotectedBytes, _additionalEntropy, DataProtectionScope.CurrentUser));
        }
Esempio n. 25
0
 private static byte[] EncryptPassword(string password)
 {
     byte[] protectedData = ProtectedData.Protect(Encoding.UTF8.GetBytes(password), null, DataProtectionScope.CurrentUser);
     return(protectedData);
 }
Esempio n. 26
0
        public void LoginIfNeeded()
        {
            if (!App.Current.Settings.Contains("auth"))
            {
                App.Current.RootFrame.Dispatcher.BeginInvoke(
                    () => App.Current.RootFrame.Navigate(new Uri("/Pages/Login.xaml", UriKind.Relative))
                    );

                return;
            }

            if (gtalk.LoggedIn)
            {
                return;
            }

            Connected = false;

            if (settings.Contains("token") && settings.Contains("rootUrl"))
            {
                var tokenBytes = ProtectedData.Unprotect(settings["token"] as byte[], null);
                App.Current.GtalkClient.SetToken(Encoding.UTF8.GetString(tokenBytes, 0, tokenBytes.Length));
                App.Current.GtalkClient.RootUrl = settings["rootUrl"] as string;

                TokenUpdated();
            }
            else
            {
                var authBytes = ProtectedData.Unprotect(settings["auth"] as byte[], null);
                App.Current.GtalkClient.Login(
                    settings["username"] as string,
                    Encoding.UTF8.GetString(authBytes, 0, authBytes.Length),
                    token => {
                    settings["token"]   = ProtectedData.Protect(Encoding.UTF8.GetBytes(token), null);
                    settings["rootUrl"] = App.Current.GtalkClient.RootUrl;

                    TokenUpdated();
                },
                    error => {
                    if (error.Equals(""))
                    {
                        if (ConnectFailed != null)
                        {
                            ConnectFailed(
                                AppResources.Error_ConnectionErrorMessage,
                                AppResources.Error_ConnectionErrorTitle
                                );
                        }
                    }
                    else if (error.StartsWith("401"))
                    {
                        // stale auth token. get a new one and we should be all happy again.
                        settings.Remove("auth");

                        App.Current.RootFrame.Dispatcher.BeginInvoke(
                            () => {
                            MessageBox.Show(
                                AppResources.Error_AuthErrorMessage,
                                AppResources.Error_AuthErrorTitle,
                                MessageBoxButton.OK
                                );
                            App.Current.RootFrame.Navigate(new Uri("/Pages/Login.xaml", UriKind.Relative));
                        });
                    }
                    else
                    {
                        if (ConnectFailed != null)
                        {
                            ConnectFailed(error, "Login");
                        }
                    }
                }
                    );
            }
        }
Esempio n. 27
0
        private void btn_save_Click(object sender, EventArgs e)
        {
            RegistryKey reg = null;

            try
            {
                reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\VKFlasterBot", true);
            }
            catch { try { reg = Registry.CurrentUser.OpenSubKey(@"SOFTWARE", true).CreateSubKey("VKFlasterBot", RegistryKeyPermissionCheck.ReadWriteSubTree); } catch { } }

            if (reg != null)
            {
                try
                {
                    // Основные настройки...
                    int var_check1 = check1.Checked ? 1 : 0;
                    int var_check2 = check2.Checked ? 1 : 0;


                    // Доп. настройки...
                    int var_imlike       = form2.imlike.Checked ? 1 : 0;
                    int var_video        = form2.check2.Checked ? 1 : 0;
                    int var_commentGroup = form2.checkBox1.Checked ? 1 : 0;


                    // Комментарии...
                    string comments = "";
                    if (Comments.comments.Items.Count > 0)
                    {
                        for (int i = 0; i < Comments.comments.Items.Count; i++)
                        {
                            comments += Comments.comments.Items[i].Text + "<attachment/>" + Comments.comments.Items[i].SubItems[2].Text + "<nextline/>";
                        }
                    }
                    else
                    {
                        comments = "<null/>";
                    }

                    // Группы...
                    string groups = "";
                    if (Groups.groups.Items.Count > 0)
                    {
                        for (int i = 0; i < Groups.groups.Items.Count; i++)
                        {
                            groups += Groups.groups.Items[i].Text + "<group_id/>" + Groups.groups.Items[i].SubItems[1].Text + "<nextline/>";
                        }
                    }
                    else
                    {
                        groups = "<null/>";
                    }

                    // Страницы...
                    string profiles = "";
                    if (Profiles.profiles.Items.Count > 0)
                    {
                        for (int i = 0; i < Profiles.profiles.Items.Count; i++)
                        {
                            profiles += Profiles.profiles.Items[i].Text + "<user_id/>" + Profiles.profiles.Items[i].SubItems[1].Text + "<nextline/>";
                        }
                    }
                    else
                    {
                        profiles = "<null/>";
                    }


                    string[] settings = new string[] { var_check1.ToString(), var_check2.ToString(), var_imlike.ToString(), var_video.ToString(), var_commentGroup.ToString(),
                             comments.Trim(), groups.Trim(), profiles.Trim(), form2.group_id.Text.ToLower().Trim() };

                    reg.SetValue("Settings", ProtectedData.Protect(Encoding.UTF8.GetBytes(string.Join("<#TAG>", settings)), null, DataProtectionScope.CurrentUser), RegistryValueKind.Binary);
                    reg.Close();
                }
                catch { }
            }

            Close();
        }
Esempio n. 28
0
 // Building ciphertext by 3DES.
 private byte[] ciphertext(string plaintext, string key)
 {
     byte[] plainByte = Encoding.UTF8.GetBytes(plaintext);
     byte[] entropy   = Encoding.UTF8.GetBytes(key);
     return(ProtectedData.Protect(plainByte, entropy, DataProtectionScope.CurrentUser));
 }
Esempio n. 29
0
        public async Task CertificateAndMasterKeyExecTest()
        {
            string script;
            IDictionary <string, string> customSettings = new ConcurrentDictionary <string, string>();
            var keyPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var buffer  = new byte[256 / 8];

            using (var cryptoRandom = new RNGCryptoServiceProvider())
            {
                cryptoRandom.GetBytes(buffer);
            }
            File.WriteAllBytes(keyPath, buffer);
            var certificates = GenerateAndSaveSelfSignedCertificate();

            if (PlatformDetails.RunningOnPosix)
            {
                var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".sh"));
                var keyArgs    = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    scriptPath, keyPath
                });
                var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    scriptPath, certificates.ServerCertificatePath
                });

                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)]                = "bash";
                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)]       = $"{keyArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExec)]          = "bash";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExecArguments)] = $"{certArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0";

                script = "#!/bin/bash\ncat \"$1\"";
                File.WriteAllText(scriptPath, script);
                Process.Start("chmod", $"700 {scriptPath}");
            }
            else
            {
                var scriptPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), ".ps1"));
                var keyArgs    = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    "-NoProfile", scriptPath, keyPath
                });
                var certArgs = CommandLineArgumentEscaper.EscapeAndConcatenate(new List <string> {
                    "-NoProfile", scriptPath, certificates.ServerCertificatePath
                });

                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExec)]                = "powershell";
                customSettings[RavenConfiguration.GetKey(x => x.Security.MasterKeyExecArguments)]       = $"{keyArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExec)]          = "powershell";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateRenewExec)]         = "powershell";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateChangeExec)]        = "powershell";
                customSettings[RavenConfiguration.GetKey(x => x.Security.CertificateLoadExecArguments)] = $"{certArgs}";
                customSettings[RavenConfiguration.GetKey(x => x.Core.ServerUrls)] = "https://" + Environment.MachineName + ":0";
                script = @"param([string]$userArg)
try {
    $bytes = Get-Content -path $userArg -encoding Byte
    $stdout = [System.Console]::OpenStandardOutput()
    $stdout.Write($bytes, 0, $bytes.Length)
}
catch {
    Write-Error $_.Exception
    exit 1
}
exit 0";
                File.WriteAllText(scriptPath, script);
            }

            UseNewLocalServer(customSettings: customSettings, runInMemory: false);
            // The master key loading is lazy, let's put a database secret key to invoke it.
            var dbName      = GetDatabaseName();
            var databaseKey = new byte[32];

            using (var rand = RandomNumberGenerator.Create())
            {
                rand.GetBytes(databaseKey);
            }
            var base64Key = Convert.ToBase64String(databaseKey);

            // sometimes when using `dotnet xunit` we get platform not supported from ProtectedData
            try
            {
#pragma warning disable CA1416 // Validate platform compatibility
                ProtectedData.Protect(Encoding.UTF8.GetBytes("Is supported?"), null, DataProtectionScope.CurrentUser);
#pragma warning restore CA1416 // Validate platform compatibility
            }
            catch (PlatformNotSupportedException)
            {
                return;
            }

            await Server.ServerStore.EnsureNotPassiveAsync();

            Server.ServerStore.PutSecretKey(base64Key, dbName, true);
            X509Certificate2 serverCertificate;
            try
            {
                serverCertificate = new X509Certificate2(certificates.ServerCertificatePath, (string)null, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
            }
            catch (CryptographicException e)
            {
                throw new CryptographicException($"Failed to load the test certificate from {certificates}.", e);
            }
            using (var store = GetDocumentStore(new Options
            {
                AdminCertificate = serverCertificate,
                ClientCertificate = serverCertificate,
                ModifyDatabaseName = s => dbName,
                ModifyDatabaseRecord = record => record.Encrypted = true,
                Path = NewDataPath()
            }))
            {
            }
            var secrets         = Server.ServerStore.Secrets;
            var serverMasterKey = (Lazy <byte[]>) typeof(SecretProtection).GetField("_serverMasterKey", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(secrets);
            Assert.True(serverMasterKey.Value.SequenceEqual(buffer));
            Assert.True(Server.Certificate.Certificate.Equals(serverCertificate));
        }
Esempio n. 30
0
 public static string Crypt(string text)
 {
     return(Convert.ToBase64String(
                ProtectedData.Protect(
                    Encoding.Unicode.GetBytes(text), null, DataProtectionScope.CurrentUser)));
 }