public WalletAddress GetAddress(
            CurrencyConfig currency,
            uint account,
            uint chain,
            uint index,
            int keyType)
        {
            using var securePublicKey = KeyStorage.GetPublicKey(
                      currency: currency,
                      account: account,
                      chain: chain,
                      index: index,
                      keyType: keyType);

            if (securePublicKey == null)
            {
                return(null);
            }

            using var publicKey = securePublicKey.ToUnsecuredBytes();

            var address = currency.AddressFromKey(publicKey);

            return(new WalletAddress
            {
                Currency = currency.Name,
                Address = address,
                PublicKey = Convert.ToBase64String(publicKey),
                KeyIndex = new KeyIndex {
                    Account = account, Chain = chain, Index = index
                },
                KeyType = keyType
            });
        }
Beispiel #2
0
        public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params)
        {
            var twitterService = new TwitterService(KeyStorage.Get("twitterKey"), KeyStorage.Get("twitterSecret"));

            if (String.IsNullOrEmpty(context.Request["oauth_token"]) ||
                String.IsNullOrEmpty(context.Request["oauth_verifier"]))
            {
                var requestToken = twitterService.GetRequestToken(context.Request.Url.AbsoluteUri);

                var uri = twitterService.GetAuthorizationUri(requestToken);

                context.Response.Redirect(uri.ToString(), true);
            }
            else
            {
                var requestToken = new OAuthRequestToken {
                    Token = context.Request["oauth_token"]
                };
                var accessToken = twitterService.GetAccessToken(requestToken, context.Request["oauth_verifier"]);
                twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret);

                var user = twitterService.VerifyCredentials(new VerifyCredentialsOptions());

                return(ProfileFromTwitter(user));
            }

            return(new LoginProfile());
        }
        public static T CreateDesignData <T>(params string[] propertyValues) where T : class
        {
            if (typeof(T).Name.Contains("EcKeyPairInfo"))
            {
                var seed = Encoding.UTF8.GetBytes(propertyValues.Aggregate((s, s1) => s + s1));
                seed = SHA1.Create().ComputeHash(seed);
                var key = ToHexString(seed);

                if (!KeyStorage.ContainsKey(key))
                {
                    KeyStorage.Add(key, EncryptionSuite.Encryption.EllipticCurveCryptographer.CreateKeyPair(false));
                }

                return(new EncryptionSuite.Contract.EcKeyPairInfo()
                {
                    TokenLabel = propertyValues[1],
                    ManufacturerId = "Nitrokey",
                    CurveDescription = "brainpoolP320r1 (320 bit)",
                    ECParamsData = StringToByteArray("06092b2403030208010109"),
                    PublicKey = KeyStorage[key],
                    EcIdentifier = new EcIdentifier()
                    {
                        KeyLabel = propertyValues[0],
                        TokenSerialNumber = propertyValues[2]
                    }
                } as T);
            }

            return(default(T));
        }
Beispiel #4
0
 /// <summary>
 ///     Initializes the new instance of the <see cref="ManifestBuilder"/> class.
 /// </summary>
 /// <param name="issuerName"></param>
 /// <param name="issuerXmlPath"></param>
 /// <param name="assemblyName"></param>
 /// <param name="directory"></param>
 /// <param name="keyStore"></param>
 /// <param name="keyPassword"></param>
 public ManifestBuilder(string issuerName, string issuerXmlPath, string assemblyName,
                        string directory, KeyStorage keyStore, string keyPassword)
     : this(
         issuerName, issuerXmlPath, assemblyName, directory, keyStore, keyPassword,
         ManifestBuilderConfiguration.Default)
 {
 }
Beispiel #5
0
        public static void Main(string[] args)
        {
#if DEBUG
            args = new string[] { "SafeBox", "Repo", "watchTest", "Bob" };
#else
            if (args.Length != 4)
            {
                Console.WriteLine("Usage: Watcher.exe <directory path> <repo> <prefix> <recipient key>");
                return;
            }
#endif

            string path          = args [0];
            Repo   repo          = Repo.Create(args [1]);
            string prefix        = args [2];
            string recipientName = args [3];

            Directory.CreateDirectory(path);

            KeyStorage keyStorage = KeyStorage.Default;

            PublicKey recipientKey = null;
            if (recipientName != null)
            {
                recipientKey = keyStorage.GetPublic(recipientName);
                EncryptedRepo er = new EncryptedRepo(repo, keyStorage);
                er.AddKey(recipientKey);
                repo = er;
            }

            DirectoryWatcher dw = new DirectoryWatcher(path, repo, prefix);
            dw.Run();
        }
Beispiel #6
0
 static SmsProviderManager()
 {
     SmscProvider          = new SmscProvider();
     ClickatellProvider    = new ClickatellProvider(KeyStorage.Get("clickatellapiKey"));
     ClickatellUSAProvider = new ClickatellProvider(KeyStorage.Get("clickatellUSAapiKey"), KeyStorage.Get("clickatellUSAsender"));
     TwilioProvider        = new TwilioProvider();
 }
Beispiel #7
0
 /// <summary>
 /// Imports the symmetric key as a clear text.
 /// </summary>
 /// <param name="key">The key.</param>
 public virtual void ImportSymmetricKey(
     byte[] key)
 {
     _hashAlgorithm.Key   = key;
     IsHashKeyInitialized = true;
     KeyStorage?.PutKey(EncryptHashKey(), KeyLocation);
 }
Beispiel #8
0
        static ImportConfiguration()
        {
            SupportBoxNetImport = !string.IsNullOrEmpty(KeyStorage.Get("box.net"));
            SupportGoogleImport = !string.IsNullOrEmpty(KeyStorage.Get("googleConsumerKey"));
            SupportZohoImport   = !string.IsNullOrEmpty(KeyStorage.Get("zoho"));
            SupportImport       = SupportBoxNetImport || SupportGoogleImport || SupportZohoImport;

            var providers = (WebConfigurationManager.AppSettings["files.thirdparty.enable"] ?? "").Split(new char[] { '|', ',' }, StringSplitOptions.RemoveEmptyEntries);

            SupportBoxNetInclusion  = providers.Contains("boxnet");
            SupportDropboxInclusion = providers.Contains("dropbox") && !string.IsNullOrEmpty(KeyStorage.Get("dropboxappkey")) && !string.IsNullOrEmpty(KeyStorage.Get("dropboxappsecret"));
            SupportGoogleInclusion  = providers.Contains("google") && SupportGoogleImport;
            SupportInclusion        = SupportBoxNetInclusion || SupportDropboxInclusion || SupportGoogleInclusion;

            if (SupportBoxNetImport)
            {
                BoxNetApiKey        = KeyStorage.Get("box.net");
                BoxNetIFrameAddress = KeyStorage.Get("box.net.framehandler");
            }
            if (SupportGoogleImport)
            {
                GoogleTokenManager = TokenManagerHolder.Get("google", "googleConsumerKey", "googleConsumerSecret");
            }
            if (SupportZohoImport)
            {
                ZohoApiKey = KeyStorage.Get("zoho");
            }

            if (SupportDropboxInclusion)
            {
                DropboxAppKey    = KeyStorage.Get("dropboxappkey");
                DropboxAppSecret = KeyStorage.Get("dropboxappsecret");
            }
        }
Beispiel #9
0
 public virtual void ImportSymmetricKey(
     byte[] key)
 {
     Symmetric.Key = key;
     KeyStorage?.PutKey(EncryptSymmetricKey(), KeyLocation);
     IsSymmetricKeyInitialized = true;
 }
Beispiel #10
0
        public static object GetEasyBibCitation(string data)
        {
            try
            {
                var easyBibappkey = KeyStorage.Get("easyBibappkey");

                var jsonBlogInfo = JObject.Parse(data);
                jsonBlogInfo.Add("key", easyBibappkey);
                var citationData = jsonBlogInfo.ToString();

                var          uri         = "https://api.citation-api.com/2.0/rest/cite";
                const string contentType = "application/json";
                const string method      = "POST";
                var          body        = citationData;
                var          headers     = new Dictionary <string, string>()
                {
                };

                return(RequestHelper.PerformRequest(uri, contentType, method, body, headers));
            }
            catch (Exception)
            {
                return(null);

                throw;
            }
        }
Beispiel #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                var scope = KeyStorage.Get("mail.googleScopes");
                var token = GoogleLoginProvider.Auth(HttpContext.Current, scope);

                var email = GetEmail(token.AccessToken);

                var emailInfo = new EmailAccessInfo
                {
                    Email        = email,
                    RefreshToken = token.RefreshToken
                };
                SubmitEmailInfo(emailInfo);
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                ErrorScope = ex.Message;
                SubmitEmailInfo(new EmailAccessInfo());
            }
        }
Beispiel #12
0
        private static AuthService ToAuthService(string consumerName, KeyElement consumerKey, KeyElement consumerSecret, KeyElement consumerKeyDefault, KeyElement consumerSecretDefault)
        {
            var authService = new AuthService(consumerName);

            if (consumerKey != null)
            {
                authService.WithKey(consumerKey.Name, KeyStorage.Get(consumerKey.Name));
                if (KeyStorage.CanSet(consumerKey.Name))
                {
                    authService.CanSet = true;
                }
                if (consumerKey.Order.HasValue)
                {
                    authService.Order = consumerKey.Order;
                }
            }
            if (consumerSecret != null)
            {
                authService.WithSecret(consumerSecret.Name, KeyStorage.Get(consumerSecret.Name));
                if (!authService.CanSet && KeyStorage.CanSet(consumerSecret.Name))
                {
                    authService.CanSet = true;
                }
                if (!authService.Order.HasValue && consumerSecret.Order.HasValue)
                {
                    authService.Order = consumerSecret.Order;
                }
            }
            if (consumerKeyDefault != null)
            {
                authService.WithKeyDefault(consumerKeyDefault.Name, KeyStorage.Get(consumerKeyDefault.Name));
                if (!authService.CanSet && KeyStorage.CanSet(consumerKeyDefault.Name))
                {
                    authService.CanSet = true;
                }
                if (!authService.Order.HasValue && consumerKeyDefault.Order.HasValue)
                {
                    authService.Order = consumerKeyDefault.Order;
                }
            }
            if (consumerSecretDefault != null)
            {
                authService.WithSecretDefault(consumerSecretDefault.Name, KeyStorage.Get(consumerSecretDefault.Name));
                if (!authService.CanSet && KeyStorage.CanSet(consumerSecretDefault.Name))
                {
                    authService.CanSet = true;
                }
                if (!authService.Order.HasValue && consumerSecretDefault.Order.HasValue)
                {
                    authService.Order = consumerSecretDefault.Order;
                }
            }

            if (!authService.Order.HasValue)
            {
                authService.Order = int.MaxValue;
            }

            return(authService);
        }
Beispiel #13
0
        private void InitProviders()
        {
            IEnumerable <LoginProfile> linkedAccounts = new List <LoginProfile>();

            if (SecurityContext.IsAuthenticated)
            {
                linkedAccounts = GetLinker().GetLinkedProfiles(SecurityContext.CurrentAccount.ID.ToString());
            }

            var fromOnly = string.IsNullOrWhiteSpace(HttpContext.Current.Request["fromonly"]) ? string.Empty : HttpContext.Current.Request["fromonly"].ToLower();

            if (!string.IsNullOrEmpty(GoogleLoginProvider.GoogleOAuth20ClientId) && (string.IsNullOrEmpty(fromOnly) || fromOnly == "google" || fromOnly == "openid"))
            {
                AddProvider(ProviderConstants.Google, linkedAccounts);
            }

            if (!string.IsNullOrEmpty(FacebookLoginProvider.FacebookOAuth20ClientId) && (string.IsNullOrEmpty(fromOnly) || fromOnly == "facebook"))
            {
                AddProvider(ProviderConstants.Facebook, linkedAccounts);
            }

            if (!string.IsNullOrEmpty(KeyStorage.Get("twitterKey")) && (string.IsNullOrEmpty(fromOnly) || fromOnly == "twitter"))
            {
                AddProvider(ProviderConstants.Twitter, linkedAccounts);
            }

            if (!string.IsNullOrEmpty(LinkedInLoginProvider.LinkedInOAuth20ClientId) && (string.IsNullOrEmpty(fromOnly) || fromOnly == "linkedin"))
            {
                AddProvider(ProviderConstants.LinkedIn, linkedAccounts);
            }
        }
Beispiel #14
0
        public void TestEncryptedField()
        {
            KeyStorage.Shared.ClearKeys();
            Environment.SetEnvironmentVariable("MORPHIC_ENC_KEY_PRIMARY", null);
            Environment.SetEnvironmentVariable("MORPHIC_HASH_SALT_PRIMARY", "SALT1:361e665ef378ab06031806469b7879bd");

            var keyName = "TEST_KEY";
            var keyData = "8C532F0C2CCE7AF471111285340B6353FCB327DF9AB9F0121731F403E3FFDC7C";

            Environment.SetEnvironmentVariable("MORPHIC_ENC_KEY_PRIMARY", $"{keyName}:{keyData}");
            Assert.Equal(KeyStorage.HexStringToBytes(keyData), KeyStorage.Shared.GetPrimary().KeyData);

            string plainText      = "thequickbrownfoxjumpedoverthelazydog";
            var    encryptedField = AssertProperlyEncrypted(keyName, plainText);

            string decryptedText = encryptedField.Decrypt();

            Assert.Equal(plainText, decryptedText);

            var otherEncryptedField = EncryptedField.FromCombinedString(encryptedField.ToCombinedString());

            decryptedText = otherEncryptedField.Decrypt();
            Assert.Equal(plainText, decryptedText);

            AssertProperlyEncrypted(keyName, "");
        }
Beispiel #15
0
        async void Initialize()
        {
            var keys = new KeyStorage();
            var client = new DropNetClient(await keys.Get("dropbox-apikey"), await keys.Get("dropbox-secret"));
            client.UseSandbox = true;

            var token = await client.GetRequestToken();
            var url = client.BuildAuthorizeUrl(token, "http://localhost");

            var regClient = new WebClientImpl();
            browser.SetWebViewClient(regClient);
            browser.LoadUrl(url);

            await regClient.Callback.Task;
            await client.GetAccessToken();

            browser.Visibility = ViewStates.Gone;

            var items = new List<Adaptar.Item>();
            foreach (var file in (await client.GetMetaData("/")).Contents.Take(10))
            {
                var buffer = await client.GetThumbnail(file);
                items.Add(
                    new Adaptar.Item
                    {
                        Title = file.Name,
                        Icon = await BitmapFactory.DecodeByteArrayAsync(buffer, 0, buffer.Length),
                    });
            }
            adapter.Update(items);
        }
Beispiel #16
0
 public static ISmsSender CreateSender(string phoneNumber)
 {
     // CIS
     if (Regex.IsMatch(phoneNumber, KeyStorage.Get("sms.CISregex")))
     {
         return new SmscSender {
                    PhoneNumber = phoneNumber
         }
     }
     ;
     // US
     else if (Regex.IsMatch(phoneNumber, KeyStorage.Get("sms.USregex")))
     {
         return new USClickatellSender {
                    PhoneNumber = phoneNumber
         }
     }
     ;
     // Other countries
     else
     {
         return new ClickatellSender {
                    PhoneNumber = phoneNumber
         }
     };
 }
 public void SaveAuthKeys(List <AuthKey> authKeys)
 {
     SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
     foreach (var authKey in authKeys)
     {
         KeyStorage.Set(authKey.Name, authKey.Value);
     }
 }
 static SmsProviderManager()
 {
     SmscProvider          = new SmscProvider();
     ClickatellProvider    = new ClickatellProvider(KeyStorage.Get("clickatellapiKey"));
     ClickatellUSAProvider = new ClickatellProvider(KeyStorage.Get("clickatellUSAapiKey"), KeyStorage.Get("clickatellUSAsender"));
     TwilioProvider        = new TwilioProvider(TwilioLoginProvider.TwilioAccountSid, TwilioLoginProvider.TwilioAuthToken, KeyStorage.Get("twiliosender"));
     TwilioSaaSProvider    = new TwilioProvider(KeyStorage.Get("twilioSaaSAccountSid"), KeyStorage.Get("twilioSaaSAuthToken"), KeyStorage.Get("twilioSaaSsender"));
 }
Beispiel #19
0
        static void Main(string[] args)
        {
            CreateJSON cj = new CreateJSON();

            KeyStorage ks = new KeyStorage();

            ks.GetKeysUser();
            ks.GetKeysMachine();
        }
Beispiel #20
0
        public static void Main(string[] args, KeyStorage keyStorage)
        {
            //Usage
            if (args.Length != 4)
            {
                throw new HelpException("Missing arguments");
            }
            string sourcePath     = args [1];
            string repoPath       = args [2];
            string receipientName = args [3];

            //Source
            if (Directory.Exists(sourcePath) == false)
            {
                throw new HelpException("Source directory not found: " + sourcePath);
            }

            //Repo
            Repo repo = Repo.Create(repoPath);

            //Sender and Recipient keys
            PrivateKey senderKey    = keyStorage.DefaultKey;
            PublicKey  recipientKey = keyStorage.GetPublic(receipientName);

            //Prepare Route message recording of ChunkID
            RouteRepo rr = new RouteRepo(repo);

            //Prepare Encryption
            EncryptedRepo er = new EncryptedRepo(rr, null);

            er.AddKey(recipientKey);

            Console.Write("Generating Tree...");

            //Send Tree
            ChunkHash tree = TreeChunk.GenerateChunk(sourcePath, er);

            //TreeMessage
            TreeMessage tm   = new TreeMessage(tree, Path.GetDirectoryName(sourcePath));
            Chunk       tmc  = Message.ToChunk(tm, senderKey);
            ChunkHash   tmch = er.WriteChunk(tmc);

            er.StoreMessage("file", tmch);

            //RouteMessage
            RouteMessage rm = rr.RouteMessage;

            rm.MessageChunkHash = tmch.bytes;
            rm.To = receipientName;

            //Store unencrypted RouteMessage
            Chunk rmChunk = Message.ToChunk(rm);

            repo.WriteChunk(rmChunk);
            repo.StoreMessage("route", rmChunk.ChunkHash);
            Console.WriteLine("RouteMessage Stored");
        }
Beispiel #21
0
        protected override Task <int> OnExecute(CommandLineApplication app)
        {
            var keyBytes = Encoding.UTF8.GetBytes(Key);
            var password = KeyStorage.SaveKey(KeyName, keyBytes);

            Console.WriteLine($"Password for saved key: {password}");
            Console.WriteLine($"Please store this password in order to be able to use this key when executing queries through the CLI.");
            return(Task.FromResult(0));
        }
Beispiel #22
0
        public static Message FromChunk(Chunk chunk, KeyStorage keyStorage)
        {
            if (chunk == null)
            {
                return(null);
            }

            using (MemoryStream ms = new MemoryStream(chunk.Data)) {
                byte[] whisper = new byte[7];
                if (ms.Read(whisper, 0, whisper.Length) != whisper.Length)
                {
                    throw new InvalidDataException("Header not right length");
                }
                if (Encoding.ASCII.GetString(whisper) != "Whisper")
                {
                    throw new InvalidDataException("Missing header");
                }

                MessageHeader header = MessageHeader.Deserialize(ProtocolParser.ReadBytes(ms));

                byte[]  messageBytes = ProtocolParser.ReadBytes(ms);
                Message message;
                switch (header.MessageId)
                {
                case 1:
                    message = TreeMessage.Deserialize(messageBytes);
                    break;

                case 2:
                    message = RouteMessage.Deserialize(messageBytes);
                    break;

                case 3:
                    message = ListMessage.Deserialize(messageBytes);
                    break;

                default:
                    throw new NotImplementedException();
                }

                //Verify signature
                if (header.Signature != null)
                {
                    foreach (PublicKey key in keyStorage.PublicKeys)
                    {
                        if (key.Verify(messageBytes, header.Signature))
                        {
                            message.Signature = key;
                            break;
                        }
                    }
                }

                return(message);
            }
        }
Beispiel #23
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     services.Configure <MorphicSettings>(Configuration.GetSection("MorphicSettings"));
     services.AddSingleton <MorphicSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <MorphicSettings> >().Value);
     services.Configure <DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
     services.AddSingleton <DatabaseSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <DatabaseSettings> >().Value);
     services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
     services.AddSingleton <EmailSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <EmailSettings> >().Value);
     services.Configure <KeyStorageSettings>(Configuration.GetSection("KeyStorageSettings"));
     services.AddSingleton <KeyStorageSettings>(serviceProvider => serviceProvider.GetRequiredService <IOptions <KeyStorageSettings> >().Value);
     services.AddSingleton <KeyStorage>(serviceProvider => KeyStorage.CreateShared(serviceProvider.GetRequiredService <KeyStorageSettings>(), serviceProvider.GetRequiredService <ILogger <KeyStorage> >()));
     services.AddSingleton <Database>();
     services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
     services.AddSingleton <IRecaptcha, MockRecaptcha>();
     services.AddSingleton <IBackgroundJobClient, MockBackgroundJobClient>();
     services.AddSingleton <StripeSettings>(new StripeSettings()
     {
         WebhookSecret = "webhooksecret"
     });
     services.AddSingleton <IPaymentProcessor, MockPaymentProcessor>();
     services.AddSingleton <Plans>(new Plans(
                                       new Plan[]
     {
         new Plan()
         {
             Id          = "testplan1",
             IsDefault   = true,
             IsActive    = true,
             MemberLimit = 5,
             Months      = 1,
             Price       = 500,
             Currency    = "USD"
         },
         new Plan()
         {
             Id          = "testplan2",
             IsActive    = true,
             MemberLimit = 10,
             Months      = 1,
             Price       = 1000,
             Currency    = "USD"
         },
         new Plan()
         {
             Id          = "testplan3",
             IsActive    = false,
             MemberLimit = 5,
             Months      = 1,
             Price       = 600,
             Currency    = "USD"
         }
     }
                                       ));
     services.AddRouting();
     services.AddEndpoints();
 }
        public Task <byte[]> SignAsync(
            byte[] data,
            WalletAddress address,
            CurrencyConfig currency,
            CancellationToken cancellationToken = default)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

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

            Log.Verbose("Sign request for data {@data} with key for address {@address}",
                        data.ToHexString(),
                        address.Address);

            if (IsLocked)
            {
                Log.Warning("Wallet locked");
                return(Task.FromResult <byte[]>(null));
            }

            if (address.KeyIndex == null)
            {
                Log.Error($"Can't find private key for address {address.Address}");
                return(Task.FromResult <byte[]>(null));
            }

            var signature = KeyStorage.SignMessage(
                currency: currency,
                data: data,
                keyIndex: address.KeyIndex,
                keyType: address.KeyType);

            Log.Verbose("Data signature in base64: {@signature}",
                        Convert.ToBase64String(signature));

            if (!KeyStorage.VerifyMessage(
                    currency: currency,
                    data: data,
                    signature: signature,
                    keyIndex: address.KeyIndex,
                    keyType: address.KeyType))
            {
                Log.Error("Signature verify error");
                return(Task.FromResult <byte[]>(null));
            }

            Log.Verbose("Data successfully signed");

            return(Task.FromResult(signature));
        }
        public void SaveAuthKeys(List <AuthKey> authKeys)
        {
            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
            foreach (var authKey in authKeys.Where(authKey => KeyStorage.Get(authKey.Name) != authKey.Value))
            {
                KeyStorage.Set(authKey.Name, authKey.Value);
            }

            MessageService.Send(HttpContext.Current.Request, MessageAction.AuthorizationKeysSetting);
        }
Beispiel #26
0
        static Global()
        {
            const StringComparison cmp = StringComparison.InvariantCultureIgnoreCase;

            EnableUploadFilter = Boolean.TrueString.Equals(WebConfigurationManager.AppSettings["files.upload-filter"] ?? "false", cmp);

            EnableEmbedded = Boolean.TrueString.Equals(WebConfigurationManager.AppSettings["files.docservice.embedded"] ?? "true", cmp);

            BitlyUrl = KeyStorage.Get("bitly-url");
        }
 private void AddToKeyStorage(string strKey, string strValue)
 {
     if (!KeyStorage.ContainsKey(strKey))
     {
         KeyStorage.Add(strKey, strValue);
     }
     else
     {
         KeyStorage[strKey] = strValue;
     }
 }
Beispiel #28
0
        public bool SaveAuthKeys(List <AuthKey> authKeys)
        {
            SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
            if (!SetupInfo.IsVisibleSettings(ManagementType.ThirdPartyAuthorization.ToString()))
            {
                throw new BillingException(Resource.ErrorNotAllowedOption, "ThirdPartyAuthorization");
            }

            var changed = false;

            var mapKeys = new Dictionary <string, List <KeyElement> >();

            foreach (var authKey in authKeys.Where(authKey => KeyStorage.Get(authKey.Name) != authKey.Value))
            {
                var keyElement = ConsumerConfigurationSection.GetSection().Keys.GetKey(authKey.Name);

                if (keyElement != null && Providers.ContainsKey(keyElement.ConsumerName))
                {
                    RemoveOldNumberFromTwilio(Providers[keyElement.ConsumerName]);

                    if (!string.IsNullOrEmpty(authKey.Value))
                    {
                        if (!mapKeys.ContainsKey(keyElement.ConsumerName))
                        {
                            mapKeys.Add(keyElement.ConsumerName, new List <KeyElement>());
                        }
                        mapKeys[keyElement.ConsumerName].Add(keyElement);
                    }
                }


                KeyStorage.Set(authKey.Name, authKey.Value);
                changed = true;
            }

            foreach (var providerKeys in mapKeys)
            {
                if (!Providers[providerKeys.Key].ValidateKeys())
                {
                    foreach (var providerKey in providerKeys.Value)
                    {
                        KeyStorage.Set(providerKey.Name, null);
                    }
                    throw new ArgumentException(Resource.ErrorBadKeys);
                }
            }

            if (changed)
            {
                MessageService.Send(HttpContext.Current.Request, MessageAction.AuthorizationKeysSetting);
            }

            return(changed);
        }
        public LoginProfile GetLoginProfile(string accessToken)
        {
            var twitterService = new TwitterService(KeyStorage.Get("twitterKey"), KeyStorage.Get("twitterSecret"));

            //??? tokenSecret
            twitterService.AuthenticateWith(accessToken, null);

            var user = twitterService.VerifyCredentials(new VerifyCredentialsOptions());

            return(ProfileFromTwitter(user));
        }
Beispiel #30
0
        public static TwitterApiInfo GetTwitterApiInfoForCurrentUser()
        {
            TwitterApiInfo apiInfo = new TwitterApiInfo
            {
                ConsumerKey    = KeyStorage.Get(SocialMediaConstants.ConfigKeyTwitterConsumerKey),
                ConsumerSecret = KeyStorage.Get(SocialMediaConstants.ConfigKeyTwitterConsumerSecretKey)
            };

            SetDefaultTokens(apiInfo);

            return(apiInfo);
        }
        public Task <byte[]> SignHashAsync(
            byte[] hash,
            WalletAddress address,
            CurrencyConfig currencyConfig,
            CancellationToken cancellationToken = default)
        {
            if (hash == null)
            {
                throw new ArgumentNullException(nameof(hash));
            }

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

            Log.Verbose("Sign request for hash {@hash}", hash.ToHexString());

            if (IsLocked)
            {
                Log.Warning("Wallet locked");
                return(Task.FromResult <byte[]>(null));
            }

            if (address.KeyIndex == null)
            {
                Log.Error($"Can't find private key for address {address.Address}");
                return(Task.FromResult <byte[]>(null));
            }

            var signature = KeyStorage.SignHash(
                currency: currencyConfig,
                hash: hash,
                keyIndex: address.KeyIndex,
                keyType: address.KeyType);

            Log.Verbose("Hash signature in base64: {@signature}", Convert.ToBase64String(signature));

            if (!KeyStorage.VerifyHash(
                    currency: currencyConfig,
                    hash: hash,
                    signature: signature,
                    keyIndex: address.KeyIndex,
                    keyType: address.KeyType))
            {
                Log.Error("Signature verify error");
                return(Task.FromResult <byte[]>(null));
            }

            Log.Verbose("Hash successfully signed");

            return(Task.FromResult(signature));
        }