private static List <string> ReadFromFile()
        {
            List <string> entries = new List <string>();

            byte[] encryptedFile = null;

            // Read the whole file into a byte array
            lock (fileLock)
            {
                encryptedFile = File.ReadAllBytes(path);
            }

            if (encryptedFile.Any())
            {
                // Convert the secure key into a byte array
                byte[] privateKeyBytes = StringConverter.ToBytes(PrivateKey);

                // Decrypt the file using the key
                string decryptedFile = AESEncrypter.Decrypt(encryptedFile, privateKeyBytes);

                // Clear the key byte array for security reasons
                Array.Clear(privateKeyBytes, 0, privateKeyBytes.Length);

                // Split the decrypted file into strings representing serialized entries
                string[] serializedEntries = decryptedFile.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                // Add all serialized entries into the list
                entries.AddRange(serializedEntries);
            }

            return(entries);
        }
Example #2
0
        public MainPage()
        {
            InitializeComponent();

            instance = this;

            // Navigate to the first page
            Navigate(typeof(AccountsPage), this);

            if (SettingsManager.Get <bool>(Setting.UseCloudSynchronization))
            {
                PasswordVault vault = new PasswordVault();
                IReadOnlyList <PasswordCredential> credentials = vault.RetrieveAll();

                if (credentials.Any())
                {
                    credentials[0].RetrievePassword();

                    ISynchronizer synchronizer = new OneDriveSynchronizer(OneDriveClientExtensions.GetUniversalClient(new[] { "onedrive.appfolder" }));
                    IEncrypter    encrypter    = new AESEncrypter();

                    synchronizer.SetEncrypter(encrypter, credentials[0].Password);

                    AccountStorage.Instance.SetSynchronizer(synchronizer);
                }
            }

            SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
        }
Example #3
0
        private async void ContinueButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            this.progressRing.Visibility = Visibility.Visible;
            this.progressRing.IsActive   = true;

            try
            {
                IEncrypter encrypter = new AESEncrypter();
                if (this.session.AccountType == AccountType.MicrosoftAccount)
                {
                    this.synchronizer.SetEncrypter(encrypter, this.encryptionKey);
                    await AccountStorage.Instance.Synchronize();
                }
            }
            catch (Exception ex)
            {
                this.onedriveErrorMessage.Text = "Couldn't encrypt OneDrive storage. Please try again.";
                this.showOnedriveError();
            }
            finally
            {
                this.progressRing.IsActive   = false;
                this.progressRing.Visibility = Visibility.Collapsed;
            }
        }
    // Loop principale:
    // Ogni secondo controlla se la postazione è occupata
    // Se lo è, mostra il messaggio "Postazione Occupata"
    // Se non lo è, genera il QR Code e lo mostra
    IEnumerator Loop()
    {
        bool generate = true;

        while (true)
        {
            yield return(StartCoroutine(IsLocationBusy(LocationID)));

            if (isBusy)
            {
                generate = true;
            }
            if (generate && !isBusy)
            {
                yield return(StartCoroutine(GetSessionToken(LocationID)));

                decryptedToken = AESEncrypter.Decrypt(lastToken, CypherKey);
                string    qrMessage = LocationID + "&" + decryptedToken;
                Texture2D tex2D     = CreateQRCode(qrMessage);
                QRCodeMaterial.SetTexture("_MainTex", tex2D);
                generate = false;
            }
            UpdateGraphics();
            yield return(new WaitForSeconds(1f));
        }
    }
        private async void Continue_Tapped(object sender, TappedRoutedEventArgs e)
        {
            try
            {
                MainPage.ShowLoader(ResourceLoader.GetForCurrentView().GetString("SynchronizingAccountsWithCloud"));

                IOneDriveClient oneDriveClient = OneDriveClientExtensions.GetUniversalClient(new[] { "onedrive.appfolder" });
                AccountSession  session        = await oneDriveClient.AuthenticateAsync();

                IEncrypter encrypter = new AESEncrypter();

                if (session.AccountType == AccountType.MicrosoftAccount)
                {
                    synchronizer.SetEncrypter(encrypter, userKey);
                    await AccountStorage.Instance.Synchronize();

                    MainPage.HideLoader();

                    Frame.Navigate(typeof(SetupSynchronizationFinishedPage), mainPage);
                }
            }
            catch (OneDriveException ex)
            {
                MessageDialog dialog = GetOneDriveErrorMessageDialog(ex);
                await dialog.ShowAsync();
            }
        }
Example #6
0
        public QlikSessionMgr()
        {
            using (var reader = new StreamReader(KEY_FILENAME))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.StartsWith("key="))
                    {
                        key = line.Substring(4);
                    }

                    if (line.StartsWith("iv="))
                    {
                        iv = line.Substring(3);
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(iv))
            {
                throw new FileNotFoundException(string.Format("Could not read key value pair 'key' or 'iv' from '{0}'.", KEY_FILENAME));
            }
            Encryptor = new AESEncrypter(key);
        }
        public void TestEncryptAndDecrypt()
        {
            string input = "Test";

            AESEncrypter encrypter = GetAESEncrypter();
            string       encrypted = encrypter.Encrypt(input);
            string       decrypted = encrypter.Decrypt(encrypted);

            Assert.AreEqual(input, decrypted);
        }
        private async void ButtonConnect_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (UserKeyToValidate.Text.Length == 23)
            {
                MainPage.ShowLoader(ResourceLoader.GetForCurrentView().GetString("CheckingKey"));

                IEncrypter encrypter = new AESEncrypter();
                synchronizer.SetEncrypter(encrypter, UserKeyToValidate.Text);

                bool result = false;

                try
                {
                    result = await synchronizer.DecryptWithKey(UserKeyToValidate.Text);

                    if (result)
                    {
                        MainPage.ShowLoader(ResourceLoader.GetForCurrentView().GetString("SynchronizingAccountsWithCloud"));

                        try
                        {
                            await AccountStorage.Instance.Synchronize();

                            vault.Add(new PasswordCredential(RESOURCE_NAME, USERNAME_NAME, UserKeyToValidate.Text));

                            Frame.Navigate(typeof(SetupSynchronizationFinishedPage), mainPage);
                        }
                        catch (OneDriveException ex)
                        {
                            MessageDialog dialog = GetOneDriveErrorMessageDialog(ex);
                            await dialog.ShowAsync();
                        }
                        finally
                        {
                            MainPage.HideLoader();
                        }
                    }
                    else
                    {
                        MainPage.HideLoader();

                        MainPage.AddBanner(new Banner(BannerType.Danger, ResourceLoader.GetForCurrentView().GetString("EnteredKeyIncorrect"), true));
                    }
                }
                catch (NetworkException)
                {
                    MainPage.HideLoader();

                    MainPage.AddBanner(new Banner(BannerType.Danger, ResourceLoader.GetForCurrentView().GetString("BannerUnableToValidateKey"), true));
                }
            }
        }
Example #9
0
 protected static string decrypt(YopRequest request, string strResult)
 {
     if (request.isEncrypt() && StringUtils.isNotBlank(strResult))
     {
         if (StringUtils.isNotBlank(request.getParamValue(YopConstants.APP_KEY)))
         {
             strResult = AESEncrypter.decrypt(strResult,
                                              request.getSecretKey());
         }
         else
         {
             strResult = BlowFish.Decrypt(strResult,
                                          request.getSecretKey());
         }
     }
     return(strResult);
 }
        private static void WriteToFile(List <string> entries)
        {
            // Concatenate all serialized entries into a string ready for encrypting
            string serializedEntries = string.Join("|", entries);

            // Convert the secure key into a byte array
            byte[] privateKeyBytes = StringConverter.ToBytes(PrivateKey);

            // Encrypt the file using the key
            byte[] encryptedFile = AESEncrypter.Encrypt(serializedEntries, privateKeyBytes);

            // Clear the key byte array for security reasons
            Array.Clear(privateKeyBytes, 0, privateKeyBytes.Length);

            // Overwrite the existing file with the encryped and serialized entries
            lock (fileLock)
            {
                File.WriteAllBytes(path, encryptedFile);
            }
        }
        private static void ReadFile(SecureString key)
        {
            using (WCFServiceClient client = new WCFServiceClient())
            {
                byte[] encryptedFile = client.ReadFile();

                if (encryptedFile != null)
                {
                    List <string> serializedEntries = new List <string>();

                    if (encryptedFile.Any())
                    {
                        string decryptedFile = AESEncrypter.Decrypt(encryptedFile, StringConverter.ToBytes(key));

                        serializedEntries.AddRange(decryptedFile.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries));
                    }

                    HashSet <EventEntry> entries = new HashSet <EventEntry>();
                    foreach (string serializedEntry in serializedEntries)
                    {
                        entries.Add(new EventEntry(serializedEntry));
                    }

                    if (!entries.Any())
                    {
                        Console.WriteLine("Entry list is empty");
                    }
                    else
                    {
                        foreach (var entry in entries)
                        {
                            Console.WriteLine(entry.ToString());
                        }
                    }
                }
            }
        }
Example #12
0
        /**
         * 请求加密,使用AES算法,要求secret为正常的AESkey
         *
         * @throws Exception
         */
        protected static void encrypt(YopRequest request)
        {
            StringBuilder       builder  = new StringBuilder();
            bool                first    = true;
            NameValueCollection myparams = request.getParams();

            foreach (string key in myparams.AllKeys)
            {
                if (YopConstants.isProtectedKey(key))
                {
                    continue;
                }

                string[]      strValues = myparams.GetValues(key);
                List <string> values    = new List <string>();
                foreach (string s in strValues)
                {
                    values.Add(s);
                }
                myparams.Remove(key);
                if (values == null || values.Count == 0)
                {
                    continue;
                }
                foreach (string v in values)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        builder.Append("&");
                    }
                    // 避免解密后解析异常,此处需进行encode(此逻辑在整个request做encoding前)
                    builder.Append(key).Append("=").Append(HttpUtility.UrlEncode(v, Encoding.UTF8));//YopConstants.ENCODING
                }
            }
            string encryptBody = builder.ToString();

            if (StringUtils.isBlank(encryptBody))
            {
                // 没有需加密的参数,则只标识响应需加密
                request.addParam(YopConstants.ENCRYPT, true);
            }
            else
            {
                if (StringUtils.isNotBlank(request
                                           .getParamValue(YopConstants.APP_KEY)))
                {
                    // 开放应用使用AES加密
                    string encrypt = AESEncrypter.encrypt(encryptBody,
                                                          request.getSecretKey());
                    request.addParam(YopConstants.ENCRYPT, encrypt);
                }
                else
                {
                    // 商户身份调用使用Blowfish加密
                    string encrypt = BlowFish.Encrypt(encryptBody,
                                                      request.getSecretKey());

                    request.addParam(YopConstants.ENCRYPT, encrypt);
                }
            }
        }