Example #1
0
    public static void SerializeXML(object obj, string FilePath, bool IsEncrypted = false)
    {
        XmlSerializer ser = new XmlSerializer(obj.GetType());

        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }

        MemoryStream mem = new MemoryStream();

        ser.Serialize(mem, obj);

        string txt = EncryptionUtility.ByteArrayToString(mem.ToArray());

        mem.Dispose();
        mem.Close();

        string finaltext = (IsEncrypted) ? EncryptionUtility.EncryptString(txt) : txt;

        byte[] data = EncryptionUtility.StringToByeArray(finaltext);

        mem = new MemoryStream(data);

        FileStream file = new FileStream(FilePath, FileMode.Create);

        mem.WriteTo(file);

        file.Close();
        mem.Dispose();
        mem.Close();
    }
Example #2
0
        public void LoadPackageSourcesReadsCredentialPairs()
        {
            // Arrange
            string encryptedPassword = EncryptionUtility.EncryptString("topsecret");

            var settings = new Mock <ISettings>();

            settings.Setup(s => s.GetValues("packageSources"))
            .Returns(new[] { new KeyValuePair <string, string>("one", "onesource"),
                             new KeyValuePair <string, string>("two", "twosource"),
                             new KeyValuePair <string, string>("three", "threesource") });

            settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two"))
            .Returns(new[] { new KeyValuePair <string, string>("Username", "user1"), new KeyValuePair <string, string>("Password", encryptedPassword) });

            var provider = CreatePackageSourceProvider(settings.Object);

            // Act
            var values = provider.LoadPackageSources().ToList();

            // Assert
            Assert.Equal(3, values.Count);
            AssertPackageSource(values[1], "two", "twosource", true);
            Assert.Equal("user1", values[1].UserName);
            Assert.Equal("topsecret", values[1].Password);
        }
        public void TestEncryptDecrypt()
        {
            string key           = "46f44ece-e897-47d1-8ad0-10753208d9f8";
            string input         = "String to encrypt.";
            string encrypted     = EncryptionUtility.EncryptString(input, key);
            string resultingData = EncryptionUtility.DecryptString(encrypted, key);

            Assert.Equal(resultingData, input);
        }
Example #4
0
 public static string SerializeToJson(object obj, bool IsEncrypted = false)
 {
     if (IsEncrypted)
     {
         return(EncryptionUtility.EncryptString(Customprovider == null? JsonUtility.ToJson(obj) : Customprovider.ToJSON(obj)));
     }
     else
     {
         return(Customprovider == null?JsonUtility.ToJson(obj) : Customprovider.ToJSON(obj));
     }
 }
Example #5
0
        public void GetConfigSettingReadsEncryptedValueFromConfigSection()
        {
            // Arrange
            var settings = new Mock <ISettings>(MockBehavior.Strict);
            var value    = EncryptionUtility.EncryptString("hello world");

            settings.Setup(s => s.GetValue("config", "foo"))
            .Returns(value)
            .Verifiable();

            // Act
            var result = settings.Object.GetConfigValue("foo", decrypt: true);

            // Assert
            Assert.Equal("hello world", result);
            settings.Verify();
        }
Example #6
0
        internal static PackageSource BuildPackageSource([NotNull] this SnapNugetFeed snapFeed, [NotNull] ISettings settings)
        {
            if (snapFeed == null)
            {
                throw new ArgumentNullException(nameof(snapFeed));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            var packageSource = new PackageSource(snapFeed.Source.ToString(), snapFeed.Name, true, true, false);

            var storePasswordInClearText = !settings.IsPasswordEncryptionSupported();

            if (snapFeed.Username != null && snapFeed.Password != null)
            {
                snapFeed.Password = storePasswordInClearText ? snapFeed.Password : EncryptionUtility.EncryptString(snapFeed.Password);

                // Comma-delimited list of authentication types the credential is valid for as stored in the config file.
                // If null or empty, all authentication types are valid. Example: 'basic,negotiate'
                string validAuthenticationTypesText = null;

                packageSource.Credentials = new PackageSourceCredential(packageSource.Name,
                                                                        // ReSharper disable once ExpressionIsAlwaysNull
                                                                        snapFeed.Username, snapFeed.Password, storePasswordInClearText, validAuthenticationTypesText);

                settings.AddOrUpdate(ConfigurationConstants.CredentialsSectionName, packageSource.Credentials.AsCredentialsItem());
            }

            if (snapFeed.ApiKey != null)
            {
                if (storePasswordInClearText)
                {
                    settings.AddOrUpdate(ConfigurationConstants.ApiKeys, new AddItem(packageSource.Source, snapFeed.ApiKey));
                }
                else
                {
                    SettingsUtility.SetEncryptedValueForAddItem(settings, ConfigurationConstants.ApiKeys, packageSource.Source, snapFeed.ApiKey);
                }
            }

            packageSource.ProtocolVersion = (int)snapFeed.ProtocolVersion;

            return(packageSource);
        }
Example #7
0
        public void GetApiKey_ReturnsApiKeyForMatchingEndpointUrl_Success()
        {
            // Arrange
            string encryptedApiKey = EncryptionUtility.EncryptString(_apikey);

            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetSection("apikeys"))
            .Returns(new MockSettingSection("apikeys",
                                            new AddItem(EndpointUrl, encryptedApiKey)
                                            ));

            //Act
            string apikey = CommandRunnerUtility.GetApiKey(settings.Object, EndpointUrl, NuGetConstants.V3FeedUrl);

            //Assert
            Assert.Equal(_apikey, apikey);
        }
Example #8
0
        public ActionResult GetToken()
        {
            string result = Configuration["BASE_URI"] + Configuration["BASE_PATH"];

            result += "/bcservice?code=";

            // generate a payload.
            string payload = "Sample token generated " + DateTime.Now.ToLongDateString();

            // encrypt that using two way encryption.
            result += System.Net.WebUtility.UrlEncode(EncryptionUtility.EncryptString(payload, _encryptionKey));

            return(new ContentResult
            {
                ContentType = "text/html",
                StatusCode = (int)HttpStatusCode.OK,
                Content = $"<html><body><h1>Token Generation Test</h1><p><a href=\"{result}\">{result}</body></html>"
            });
        }
Example #9
0
        public void GetApiKey_ReturnsDefaultGalleryServerUrlApiKeyIfSourceHostNameIsNuGetOrg_Success()
        {
            // Arrange
            string encryptedApiKey = EncryptionUtility.EncryptString(_apikey);

            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetSection("apikeys"))
            .Returns(new MockSettingSection("apikeys",
                                            new AddItem("http://endpointUrl", _apikey),
                                            new AddItem(NuGetConstants.DefaultGalleryServerUrl, encryptedApiKey)
                                            ));

            //Act
            string apikey = CommandRunnerUtility.GetApiKey(settings.Object, EndpointUrl, NuGetConstants.V3FeedUrl);

            //Assert
            Assert.Equal(_apikey, apikey);
        }
Example #10
0
        public void GetApiKey_ReturnsApiKeyForMatchingPackageSourceUrl_Success()
        {
            // Arrange
            string encryptedApiKey = EncryptionUtility.EncryptString(_apikey);

            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetSection("apikeys"))
            .Returns(new MockSettingSection("apikeys",
                                            new AddItem("http://endpointUrl", _apikey),//dummy endpoint url passed to ensure apikey is read from source url config entry
                                            new AddItem(NuGetConstants.V3FeedUrl, encryptedApiKey)
                                            ));

            //Act
            string apikey = CommandRunnerUtility.GetApiKey(settings.Object, EndpointUrl, NuGetConstants.V3FeedUrl);

            //Assert
            Assert.Equal(_apikey, apikey);
        }
Example #11
0
        public void GetApiKey_ReturnsNullWhenApiKeyIsNotFound_Success()
        {
            // Arrange
            string encryptedApiKey = EncryptionUtility.EncryptString(_apikey);

            var settings = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetSection("apikeys"))
            .Returns(new MockSettingSection("apikeys",
                                            new AddItem("http://endpointUrl", encryptedApiKey),
                                            new AddItem(NuGetConstants.DefaultGalleryServerUrl, encryptedApiKey),
                                            new AddItem("https://sourceUrl", encryptedApiKey)
                                            ));

            //Act
            string apikey = CommandRunnerUtility.GetApiKey(settings.Object, EndpointUrl, "https://someothersourceUrl");

            //Assert
            Assert.True(string.IsNullOrEmpty(apikey));
        }
Example #12
0
        private string GetConfirmationLink(string slug, string email)
        {
            string result = _configuration["BASE_URI"] + _configuration["BASE_PATH"];

            result += "/newsletter-confirm/" + slug + "?code=";

            // create a newsletter confirmation object.

            ViewModels.NewsletterConfirmation newsletterConfirmation = new ViewModels.NewsletterConfirmation();
            newsletterConfirmation.email = email;
            newsletterConfirmation.slug  = slug;

            // convert it to a json string.
            string json = JsonConvert.SerializeObject(newsletterConfirmation);

            // encrypt that using two way encryption.

            result += System.Net.WebUtility.UrlEncode(EncryptionUtility.EncryptString(json, _encryptionKey));

            return(result);
        }
Example #13
0
        public void GetUserConfiguredProxy_OnWindows_ReadsCredentialsFromSettings()
        {
            // Arrange
            var host = "http://127.0.0.1";
            var user = "******";
            var encryptedPassword = EncryptionUtility.EncryptString("password");
            var settings          = new Mock <ISettings>(MockBehavior.Strict);

            settings.Setup(s => s.GetValue("config", "http_proxy", false)).Returns(host);
            settings.Setup(s => s.GetValue("config", "http_proxy.user", false)).Returns(user);
            settings.Setup(s => s.GetValue("config", "http_proxy.password", false)).Returns(encryptedPassword);
            settings.Setup(s => s.GetValue("config", "no_proxy", false)).Returns("");
            var environment = Mock.Of <IEnvironmentVariableReader>();
            var proxyCache  = new ProxyCache(settings.Object, environment);

            // Act
            var proxy = proxyCache.GetUserConfiguredProxy() as WebProxy;

            // Assert
            AssertProxy(host, user, "password", proxy);
        }
        private static IFileSystem GetFileSystemWithConfigWithCredential()
        {
            var fileSystem = new MockFileSystem(@"C:\This\Is\My\Install\Path\.nuget");

            fileSystem.AddFile("nuget.config",
                               @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <solution>
    <add key=""disableSourceControlIntegration"" value=""true"" />
  </solution>
  <packageSources>
    <add key=""__ATESTREPO__"" value=""http://www.myprivatefeed.example/"" />
  </packageSources>
  <packageSourceCredentials>
      <__ATESTREPO__>
          <add key=""Username"" value=""user"" />
          <add key=""Password"" value=""" + EncryptionUtility.EncryptString("123abc") + @""" />
      </__ATESTREPO__>
  </packageSourceCredentials>
</configuration>");
            return(fileSystem);
        }
Example #15
0
        /// <summary>
        /// Generate a link to be sent to an email address.
        /// </summary>
        /// <param name="email"></param>
        /// <param name="individualId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private string GetConsentLink(string email, string individualId, string parentId)
        {
            string result = Configuration["BASE_URI"] + Configuration["BASE_PATH"];

            result += "/bcservice?path=/security-consent/" + parentId + "/" + individualId + "?code=";

            // create a newsletter confirmation object.

            ViewModels.SecurityConsentConfirmation securityConsentConfirmation = new ViewModels.SecurityConsentConfirmation()
            {
                email        = email,
                parentid     = parentId,
                individualid = individualId
            };

            // convert it to a json string.
            string json = JsonConvert.SerializeObject(securityConsentConfirmation);

            // encrypt that using two way encryption.

            result += System.Net.WebUtility.UrlEncode(EncryptionUtility.EncryptString(json, _encryptionKey));

            return(result);
        }
Example #16
0
        /// <inheritdoc />
        public void SetEncryptedValue(string settingName, string value)
        {
            string encryptedValue = EncryptionUtility.EncryptString(value);

            SetValue(settingName, encryptedValue);
        }