Esempio n. 1
0
        public void TestEncryptDecrypt()
        {
            string encrypted = AESEncryption.Encrypt("message", "password");

            Assert.AreEqual("message", AESEncryption.Decrypt(encrypted, "password"), "Decrypted(Encrypted(message)) == mesage");
            Assert.AreNotEqual("message", encrypted, "Encrypted(message) != message");
        }
 public static void SetString(string key, string value, string password)
 {
     var aesEncryption = new AESEncryption();
     string hashedKey = GenerateMD5(key);
     string encryptedValue = aesEncryption.Encrypt(value, password);
     PlayerPrefs.SetString(hashedKey, encryptedValue);
 }
Esempio n. 3
0
        private void JangoDesktopLoad(object sender, EventArgs e)
        {
            if (!Settings.Default.StartMinimized)
            {
                ToggleJangoDesktop();
            }
            if (Settings.Default.AutoLogin)
            {
                //AutoLogin is turned on
                string decryptedUsername = AESEncryption.Decrypt(Settings.Default.JangoUsername, Environment.MachineName + Environment.ProcessorCount, Environment.UserName, "SHA1", Environment.ProcessorCount, "16CHARSLONG12345", 256);
                string decryptedPassword = AESEncryption.Decrypt(Settings.Default.JangoPassword, Environment.MachineName + Environment.ProcessorCount, Environment.UserName, "SHA1", Environment.ProcessorCount, "16CHARSLONG12345", 256);
                JangoBrowser.Navigate("http://www.jango.com/splogin?user[email]=" + decryptedUsername + "&user[password]=" + decryptedPassword);
            }
            else
            {
                JangoBrowser.Navigate("http://www.jango.com");
            }

            //Start Keyboard Hook
            try
            {
                _actHook          = new UserActivityHook();
                _actHook.KeyDown += new KeyEventHandler(MyKeyDown);
                _actHook.Start();
            }
            catch (Exception)
            {
                MessageBox.Show("Error setting up media keys. They will not work. Try restarting Jango Desktop");
            }

            _starting = false;
        }
Esempio n. 4
0
    void Start()
    {
        if (UseStream)
        {
            StreamEncryption.DecryptAssetBundle(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
            });

            StartCoroutine(StreamEncryption.AsyncLoad(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
                //为什么会有rotation,属性窗口有数值,但是右键reset,物体也没变化,就是000的
            }));
        }
        else
        {
            AESEncryption.DecryptAssetBundle(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
            });

            StartCoroutine(AESEncryption.AsyncLoad(Application.streamingAssetsPath + "/assets/cube.ab", "Cube", (prefab) => {
                var obj = GameObject.Instantiate <GameObject>(prefab as GameObject);
                obj.transform.localPosition = new Vector3(0, 0, 0);
                obj.transform.localRotation = Quaternion.Euler(0, 0, 0);
                //为什么会有rotation,属性窗口有数值,但是右键reset,物体也没变化,就是000的
            }));
        }
    }
        public SmartApartmentDataTestDataAccess()
        {
            var encryptedConnectionString = ConfigurationManager.ConnectionStrings["SmartApartmentEntities"];
            var connectionString          = AESEncryption.Decrypt(encryptedConnectionString.ConnectionString, EncryptionKey);

            _entities = new SmartApartmentEntities(connectionString);
        }
        private ImageDetails SetImageDetails(string senderId, string receiverId)
        {
            var imageDetails = new ImageDetails();

            watchAesEncrypt = new Stopwatch();
            watchAesEncrypt.Start();

            var aesEncrypt        = new AESEncryption <Parameters>(SetParameters());
            var IV                = aesEncrypt.GenerateAesKeys();
            var encryptParameters = aesEncrypt.EncryptAES();

            watchAesEncrypt.Stop();
            AesEncryptTime = watchAesEncrypt.ElapsedMilliseconds;

            using (CryptoDbContext db = new CryptoDbContext())
            {
                imageDetails.SenderId   = senderId;
                imageDetails.ReceiverId = receiverId;
                imageDetails.Parameters = encryptParameters;
                imageDetails.IVAes      = IV;
                imageDetails.Image      = null;
                imageDetails.ImageId    = Guid.NewGuid().ToString();
                db.ImageDetails.Add(imageDetails);
                db.SaveChanges();
            }
            return(imageDetails);
        }
Esempio n. 7
0
        public IActionResult ReceiveMessage(SendMessageModel messageModel)
        {
            string        filePublicKey = parameters.Value.FilesOutput + parameters.Value.PubKeyFile + messageModel.userNameDestination + messageModel.userNameOrigin;
            RSAEncryption rsaEncryption = new RSAEncryption();
            AESEncryption aesEncryption = new AESEncryption();
            RSASigning    rsaSigning    = new RSASigning();

            //Decrypt symmetric key
            ResponseRSADecryption rsaDecryptResponse = new ResponseRSADecryption();

            rsaDecryptResponse = rsaEncryption.DecryptAESKey(messageModel.encryptedKey, messageModel.userNameDestination + messageModel.userNameOrigin);
            if (!rsaDecryptResponse.result)
            {
                FileWriter.WriteOnEvents(EventLevel.Error, "Error descifrando llave AES con RSA.");
                return(BadRequest(new { result = false }));
            }
            //Decrypt Message
            ResponseAESDecryption responseAESDecryption = new ResponseAESDecryption();

            responseAESDecryption = aesEncryption.DecryptMessage(messageModel, rsaDecryptResponse.decryptedKey);
            if (!responseAESDecryption.result)
            {
                FileWriter.WriteOnEvents(EventLevel.Error, "Error descifrando mensaje con AES.");
                return(BadRequest(new { result = false }));
            }
            //Validate Sign
            if (!rsaSigning.validateSignAndHash(responseAESDecryption.decryptedMessage, messageModel.encryptSignature, filePublicKey))
            {
                FileWriter.WriteOnEvents(EventLevel.Atention, "La información recibida es corrupta.");
                return(BadRequest(new { result = false }));
            }
            //Muestra mensaje
            return(Ok(new{ mensaje = responseAESDecryption.decryptedMessage }));
        }
Esempio n. 8
0
        /// <summary>
        /// Method to loading document from xml file saved in IsolatedStorage.
        /// </summary>
        /// <returns>Return all information about document as XDocument.</returns>
        public XDocument GetSavedDocument()
        {
            XDocument document = null;

            try
            {
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string directoryPath  = string.Format("surveys/{0}", Id);
                    string resultFilePath = System.IO.Path.Combine(directoryPath, string.Format("r_{0}.xml", ResultInfo.Id));
                    if (!isoStore.FileExists(resultFilePath))
                    {
                        return(null);
                    }
                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(resultFilePath, FileMode.Open, isoStore))
                    {
                        StreamReader reader = new StreamReader(isoStream);
                        string       strDoc = reader.ReadToEnd();

                        if ((bool)OperationsOnSettings.Instance.IsEncryptionEnabled)
                        {
                            AESEncryption encrypter = new AESEncryption();
                            strDoc = encrypter.Decrypt(strDoc, App.AppDictionary["EncryptionPassword"] as string, "qwhmvbzx");
                        }

                        document = XDocument.Parse(strDoc);
                    }
                }
            }
            catch (IsolatedStorageException)
            {
            }
            return(document);
        }
Esempio n. 9
0
    public static void EncryptBlobs(CloudStorageAccount storageAccount, AESEncryption encrypt)
    {
        // Create the blob client.
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        foreach (CloudBlobContainer containter in blobClient.ListContainers())
        {
            // Retrieve reference to a previously created container.
            CloudBlobContainer cont = blobClient.GetContainerReference(containter.Name);


            foreach (IListBlobItem item in cont.ListBlobs(null, false))
            {
                if (item.GetType() == typeof(CloudBlockBlob) || item.GetType() == typeof(CloudPageBlob))
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                    try
                    {
                        blob.Delete(DeleteSnapshotsOption.DeleteSnapshotsOnly);
                    }
                    catch (Exception e) { }
                    // part of disable backups
                    Console.WriteLine("Encrypting Block blob named: {0}", blob.Name);
                    Download(blob, Utils.getPath());

                    // AESEncryption encrypt = new AESEncryption();
                    encrypt.EncryptAES(Utils.getPath() + blob.Name, storageAccount);
                    //encrypt.OnFinishEncryption(storageAccount);
                    Upload(blob, Utils.getPath());
                }
            }
        }
    }
Esempio n. 10
0
        private void SavetTestResult(Survey survey, XDocument documentXML)
        {
            String dataToSave;

            if ((bool)OperationsOnSettings.Instance.IsEncryptionEnabled)
            {
                AESEncryption encrypter = new AESEncryption();
                dataToSave = encrypter.Encrypt(documentXML.ToString(), App.AppDictionary["EncryptionPassword"] as String, "qwhmvbzx");
            }
            else
            {
                dataToSave = documentXML.ToString();
            }

            using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                String directoryPath  = String.Format("surveys/{0}", survey.Id);
                string resultFilePath = System.IO.Path.Combine(directoryPath, String.Format("r_{0}.xml", survey.ResultInfo.Id));
                if (!isolatedStorage.DirectoryExists(directoryPath))
                {
                    isolatedStorage.CreateDirectory(directoryPath);
                }

                using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(resultFilePath, FileMode.Create, isolatedStorage))
                {
                    StreamWriter writer = new StreamWriter(isoStream);
                    writer.Write(dataToSave);
                    writer.Close();
                }
            }

            OperationsOnListOfResults operationsOnListOfResults = new OperationsOnListOfResults(SurveyId);

            operationsOnListOfResults.Add(survey.ResultInfo);
        }
Esempio n. 11
0
        private void SetCookies()
        {
            try
            {
                logger.Info("Set cookies called.");
                StringBuilder data = new StringBuilder();
                data.Append("SessionID" + "=" + Session.SessionID + "&");
                data.Append("Email" + "=" + email.Text + "&");
                data.Append("PAN" + "=" + pan.Text + "&");
                data.Append("Password" + "=" + password.Text + "&");
                data.Append("FirstName" + "=" + firstname.Text + "&");
                data.Append("LastName" + "=" + lastname.Text + "&");
                data.Append("Phone" + "=" + phone.Text + "&");
                var encryptedData = AESEncryption.EncryptAndroid(Convert.ToString(data));

                HttpCookie userInfo = new HttpCookie(cookieName);
                userInfo.Secure = true;
                //userInfo["SessionID"] = Session.SessionID;
                //userInfo["Email"] = email.Text;
                //userInfo["PAN"] = pan.Text;
                //userInfo["Password"] = password.Text;
                //userInfo["FirstName"] = firstname.Text;
                //userInfo["LastName"] = lastname.Text;
                //userInfo["Phone"] = phone.Text;
                userInfo["Data"] = encryptedData;
                userInfo.Expires = DateTime.Now.AddMonths(Convert.ToInt32(AppConfig.CookieExpiry));
                Response.Cookies.Add(userInfo);
                logger.Info("Data: " + Convert.ToString(encryptedData));
            }
            catch (Exception ex)
            {
                logger.Error("Unable to set cookies.\n" + ex);
            }
        }
Esempio n. 12
0
        public void TestAESEncryption()
        {
            string encryptMe = "Christoph";
            string encrypted = AESEncryption.HashStringAes256(encryptMe);

            Assert.NotEqual(encrypted, encryptMe);
        }
Esempio n. 13
0
    public static void EncryptTables(CloudStorageAccount storageAccount, AESEncryption encrypt)
    {
        // Create the table client.
        // Table has no snapshot so nothing to disable.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        foreach (CloudTable table in tableClient.ListTables())
        {
            // Retrieve reference to a previously created tables.
            CloudTable tbl = tableClient.GetTableReference(table.Name);

            TableQuery query = new TableQuery();

            foreach (ITableEntity entity in table.ExecuteQuery(query))
            {
                // Create a retrieve operation that takes a customer entity.
                TableOperation retrieveOperation = TableOperation.Retrieve(entity.PartitionKey, entity.RowKey);

                // Execute the operation.
                TableResult retrievedResult = table.Execute(retrieveOperation);

                // Assign the result to a CustomerEntity object.
                ITableEntity updateEntity = (ITableEntity)retrievedResult.Result;

                if (updateEntity != null)
                {
                    //encrypt the entity's properties (patition & row)
                    EncryptFitTableConstrains(entity, tbl, encrypt);
                }
            }
            Console.Read(); //keep console open for dubug
        }
    }
Esempio n. 14
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            model.Password = AESEncryption.Encrypt(model.Password);
            var response = model.PostRequest(WebApiRequests.AuthenticateUser); // call to webapi to authenticate user

            if (response)
            {
                var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie);
                FormsAuthentication.SetAuthCookie(model.UserName, true);
                Authentication.SignIn(new AuthenticationProperties
                {
                    IsPersistent = model.RememberMe
                }, identity);

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
Esempio n. 15
0
        private void graphicCrypt_Click(object sender, EventArgs e)
        {
            if (base64strRES != null)
            {
                if (selMode.SelectedIndex == 0)

                #region Graphical encryption
                {
                    string IV        = AESEncryption.GenerateIV();
                    string plaintext = txInput3.Text;
                    string salt      = txSalt3.Text;
                    string password  = base64strRES;

                    txOutput3.Text = _Encrypt(plaintext, password, IV, salt, positionStart3.Checked);
                }
                #endregion

                else if (selMode.SelectedIndex == 1)

                #region Graphical decryption
                {
                    string input    = txInput3.Text;
                    string password = base64strRES;
                    string salt     = txSalt3.Text;

                    txOutput3.Text = _Decrypt(input, password, salt, positionStart3.Checked);
                }
                #endregion
            }
        }
Esempio n. 16
0
        public static string Decrypt(X509Certificate2 privateKey, EncryptedPayload payload)
        {
            byte [] decryptedKey = X509Encryption.Decrypt(privateKey, payload.Key);

            string retVal = AESEncryption.Decrypt(decryptedKey, Convert.FromBase64String(payload.Salt), payload.Data);

            return(retVal);
        }
Esempio n. 17
0
        public static byte[] Decrypt(EncryptedObj data)
        {
            var keys = AESEncryption.GetKeys(data.VectorData);
            var str  = AESEncryption.DecryptStringFromBytes_Aes(data.EncryptedData, keys.Key, keys.IV);
            var res  = Convert.FromBase64String(str);

            return(res);
        }
Esempio n. 18
0
            /// <summary>
            /// Requires: string GAF API Key
            /// </summary>
            /// <param name="writer"></param>
            /// <param name="client"></param>
            /// <param name="data">string GAF API Key</param>
            public void Send(PacketWriter writer, Client client, params object[] data)
            {
                string apiKeyEncrypted = AESEncryption.EncryptString(ApiKey);

                writer.Write(apiKeyEncrypted);

                client.WriteAsync(writer.Build());
            }
Esempio n. 19
0
    public string generateASPEncryptedKey(string encKey, string asp_secret)
    {
        byte[] enc_key        = AESEncryption.decrypt(encKey, System.Text.Encoding.UTF8.GetBytes(asp_secret));
        string enc_asp_secret = AESEncryption.encryptEK(System.Text.Encoding.UTF8.GetBytes(asp_secret),
                                                        AESEncryption.decodeBase64StringTOByte(AESEncryption.encodeBase64String(enc_key)));

        return(enc_asp_secret);
    }
Esempio n. 20
0
        public void Encrypt_EncryptedStringLengthBase64()
        {
            //Arrange
            //Act
            var encrypted = AESEncryption.Encrypt(encryptString);

            //Assert
            Assert.AreEqual(64, encrypted.Length);
        }
Esempio n. 21
0
            public void Send(PacketWriter writer, Client client, params object[] data)
            {
                writer.Write(AESEncryption.EncryptString(ApiKey));
                writer.Write(RegisterCode);
                writer.Write(EncryptionKey.Length);
                writer.Write(-1, EncryptionKey);

                client.WriteAsync(writer.Build());
            }
Esempio n. 22
0
        public void CreateKey()
        {
            var ret = AESEncryption.CreateKey();

            Assert.IsTrue(ret.Length == 32 && ret[0] > 0 && ret[31] > 0);

            var retString = AESEncryption.CreateKeyString();

            Assert.IsTrue(ret.Length == 32);
        }
Esempio n. 23
0
        public void Encrypt_ShouldReturnStringEncrypted()
        {
            //Arrange
            //Act
            var encrypted = AESEncryption.Encrypt(encryptString);

            //Assert
            Assert.AreEqual(64, encrypted.Length);
            Assert.AreNotEqual(encryptString, encrypted);
        }
Esempio n. 24
0
        public void EncryptDecryptAutoGeneratedKey()
        {
            String ToEncrypt = "What the hell is this";
            var    key       = AESEncryption.CreateKey();
            String encrypted = AESEncryption.EncryptToString(ToEncrypt, key, out byte [] IV);

            String decrypted = AESEncryption.Decrypt(key, IV, encrypted);

            Assert.IsTrue(decrypted == ToEncrypt);
        }
Esempio n. 25
0
        public ActionResult getsql()
        {
            string plainStr           = "06969b0d-0523-11e9-8656-00ff3751ad98";
            int    keySize            = 256;
            string completeEncodedKey = AESEncryption.GenerateKey(keySize);
            string encryptedText      = plainStr.Encrypt();
            string decrypted          = encryptedText.Decrypt().ValidateGuid();

            return(Ok());
        }
        public EncryptionScenarioViewModel(
            DESEncryption desEncryption,
            AESEncryption aesEncryption,
            TrueCrypt trueCrypt) : base()
        {
            DisplayName = "Encryption";

            Scenarios.Add(desEncryption);
            Scenarios.Add(aesEncryption);
            Scenarios.Add(trueCrypt);
        }
Esempio n. 27
0
        public void Decrypt_ShouldReturnStringDecrypted()
        {
            //Arrange
            const string decryptString = "7Ph4a7D5vLSJccbHGxojCByaXvBFn6kwW4UZAx10EkQVynabuGmC4QjPzaBmsoZS";

            //Act
            var decrypted = AESEncryption.Decrypt(decryptString);

            //Assert
            Assert.AreEqual(encryptString, decrypted);
        }
Esempio n. 28
0
        public void Decrypt_ShouldNotDecryptCorrectly()
        {
            //Arrange
            const string decryptHackString = "lPh4a7D5vLopccbHGxojCByaXvBFn6kwW4UZAx10EkQVynabuGmC4QjPzaBmsoZS";

            //Act
            var decrypted = AESEncryption.Decrypt(decryptHackString);

            //Assert
            Assert.AreNotEqual(encryptString, decrypted);
        }
Esempio n. 29
0
        public void EncryptDecryptWithKnownKey()
        {
            String Key       = "1234567890123456"; // minimum 16 characters
            String ToEncrypt = "What the hell is this";
            var    key       = Encoding.UTF8.GetBytes(Key);
            String encrypted = AESEncryption.EncryptToString(ToEncrypt, key, out byte[] IV);

            String decrypted = AESEncryption.Decrypt(key, IV, encrypted);

            Assert.IsTrue(decrypted == ToEncrypt);
        }
        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            if (pbImage.Image == null)
            {
                WarningNotice.NoImage();
                return;
            }
            if (tbPassword.Text.Length != 16 && tbPassword.Text.Length != 24 && tbPassword.Text.Length != 32)
            {
                WarningNotice.KeyLength(16, 24, 32);
                return;
            }
            if (tbIV.Text.Length != 16)
            {
                WarningNotice.IVLength(16);
                return;
            }
            Bitmap bitmap = (Bitmap)pbImage.Image;
            Bitmap result;

            if (sfdFile.ShowDialog() == DialogResult.OK)
            {
                string fileName = sfdFile.FileName;
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        string hiddenText = AESEncryption.Encrypt(tbFromText.Text, tbPassword.Text, tbIV.Text);
                        ControlEnable(this.Controls, false);
                        fileSize = bitmap.Height;
                        result   = SteganographyConvert.Encrypt(hiddenText, (Bitmap)bitmap.Clone());

                        switch (sfdFile.FilterIndex)
                        {
                        case 0: result.Save(fileName, ImageFormat.Png); break;

                        case 1: result.Save(fileName, ImageFormat.Bmp); break;

                        case 2: result.Save(fileName, ImageFormat.Jpeg); break;
                        }
                        this.Invoke(new Action(() => WarningNotice.Save()));
                    }
                    catch (SteganographySizeException ex)
                    {
                        this.Invoke(new Action(() => WarningNotice.CantConvertImage()));
                    }
                    finally
                    {
                        ControlEnable(this.Controls, true);
                    }
                });
            }
            sfdFile.FileName = "";
        }
Esempio n. 31
0
        private void Encrypt_Click(object sender, EventArgs e)
        {
            //input
            string IV        = AESEncryption.GenerateIV();
            string plaintext = txInput1.Text;
            string salt      = txSalt1.Text;
            string password  = txPass1.Text;

            //output
            txOutput1.Text = _Encrypt(plaintext, password, IV, salt, optionStart.Checked);
        }
Esempio n. 32
0
        internal ConfigureFile( MainForm UseForm, string FileToUseName )
        {
            MForm = UseForm;
            FileName = FileToUseName;
            AESEncrypt = new AESEncryption();
            string ExampleKey = "Where does this key come from on a production server" +
              " that is running on an Amazon EC2 instance (for example) where you don't" +
              " have access to the physical hardware?";

            AESEncrypt.SetKey( ExampleKey );

            CDictionary = new Dictionary<string, string>();
            ReadFromTextFile();
        }
 public static string GetString(string key, string password)
 {
     string hashedKey = GenerateMD5(key);
     if (PlayerPrefs.HasKey(hashedKey))
     {
         var aesEncryption = new AESEncryption();
         string encryptedValue = PlayerPrefs.GetString(hashedKey);
         string decryptedValue;
         aesEncryption.TryDecrypt(encryptedValue, password, out decryptedValue);
         return decryptedValue;
     }
     else
     {
         return "";
     }
 }
Esempio n. 34
0
        /// <summary>
        /// Method to loading document from xml file saved in IsolatedStorage.
        /// </summary>
        /// <returns>Return all information about document as XDocument.</returns>
        public XDocument GetSavedDocument()
        {
            XDocument document = null;
            try
            {
                using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    string directoryPath = string.Format("surveys/{0}", Id);
                    string resultFilePath = System.IO.Path.Combine(directoryPath, string.Format("r_{0}.xml", ResultInfo.Id));
                    if (!isoStore.FileExists(resultFilePath))
                    {
                        return null;
                    }
                    using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(resultFilePath, FileMode.Open, isoStore))
                    {
                        StreamReader reader = new StreamReader(isoStream);
                        string strDoc = reader.ReadToEnd();

                        if ((bool)OperationsOnSettings.Instance.IsEncryptionEnabled)
                        {
                            AESEncryption encrypter = new AESEncryption();
                            strDoc = encrypter.Decrypt(strDoc, App.AppDictionary["EncryptionPassword"] as string, "qwhmvbzx");
                        }

                        document = XDocument.Parse(strDoc);
                    }
                }
            }
            catch (IsolatedStorageException)
            {
            }
            return document;
        }
Esempio n. 35
0
        /// <summary>
        /// Method to saving new/modified result.
        /// </summary>
        public void SaveSurveyResult()
        {
            Thread t = new Thread(new ThreadStart(() =>
            {
                if (!string.IsNullOrEmpty(ResultInfo.Title))
                {
                    DateOperations operationsOnDate = new DateOperations();

                    XDocument documentXML = PrepareResultDocument();
                    string dataToSave;

                    if ((bool)OperationsOnSettings.Instance.IsEncryptionEnabled)
                    {
                        AESEncryption encrypter = new AESEncryption();
                        dataToSave = encrypter.Encrypt(documentXML.ToString(), App.AppDictionary["EncryptionPassword"] as string, "qwhmvbzx");
                    }
                    else

                    {
                        dataToSave = documentXML.ToString();
                    }

                    using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        string directoryPath = string.Format("surveys/{0}", Id);
                        string resultFilePath = System.IO.Path.Combine(directoryPath, string.Format("r_{0}.xml", ResultInfo.Id));
                        if (!isolatedStorage.DirectoryExists(directoryPath))
                        {
                            isolatedStorage.CreateDirectory(directoryPath);
                        }
                        using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(resultFilePath, FileMode.Create, isolatedStorage))
                        {

                            StreamWriter writer = new StreamWriter(isoStream);
                            writer.Write(dataToSave);
                            writer.Close();
                        }
                    }
                    AddResultToList();
                }
                EventHandler handler = SavingCompletedEventHandler;
                if (handler != null)
                    handler(this, EventArgs.Empty);
                IsResultChanged = false;
            }));
            t.Start();
        }