private void Btn_Decrypt_Click(object sender, EventArgs e)
 {
     if (Rdb_RsaEncrypt.Checked)
     {
         Txt_PlainText.Text = decrypt1(Txt_CipherText.Text, Txt_PrivateKey.Text);
     }
     else if (Rdb_AesECBEncrypt.Checked)
     {
         try
         {
             AESCryptography Aes = new AESCryptography();
             var             Dec = Aes.DecryptAsync(Txt_PublicKey.Text, Txt_CipherText.Text);
             Txt_PlainText.Text = Dec;
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.GetErrorMessage());
         }
     }
     else if (Rdb_AesCBCEncrypt.Checked)
     {
         try
         {
             AESCBCModeCryptography Aes = new AESCBCModeCryptography();
             var Dec = Aes.Decrypt(Txt_PublicKey.Text, Txt_CipherText.Text);
             Txt_PlainText.Text = Dec;
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.GetErrorMessage());
         }
     }
 }
        // trả về response ứng với từng lệnh trong session


        public string DecryptWithDefaultKey_IV(byte[] ciphertext)
        {
            string keyAES = "12345678123456781234567812345678";
            string ivAES  = "1122334455667788";

            return(AESCryptography.DecryptWithAES(ciphertext, keyAES, ivAES));
        }
        public byte[] EncryptWithDefaultKey_IV(string plaintext)
        {
            string keyAES = "12345678123456781234567812345678";
            string ivAES  = "1122334455667788";

            return(AESCryptography.EncryptWithAES(plaintext, keyAES, ivAES));
        }
Exemplo n.º 4
0
 public static Byte[] Encrypt(Byte[] bytesToBeEncrypted)
 {
     Byte[] array  = AESCryptography.GetPassword();
     Byte[] result = null;
     Byte[] salt   = AESCryptography.GetSalt();
     using (MemoryStream memoryStream = new MemoryStream())
     {
         using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
         {
             rijndaelManaged.KeySize   = 256;
             rijndaelManaged.BlockSize = 128;
             Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(array, salt, 1000);
             rijndaelManaged.Key  = rfc2898DeriveBytes.GetBytes(rijndaelManaged.KeySize / 8);
             rijndaelManaged.IV   = rfc2898DeriveBytes.GetBytes(rijndaelManaged.BlockSize / 8);
             rijndaelManaged.Mode = CipherMode.CBC;
             using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(), CryptoStreamMode.Write))
             {
                 cryptoStream.Write(bytesToBeEncrypted, 0, (Int32)bytesToBeEncrypted.Length);
                 cryptoStream.Close();
             }
             result = memoryStream.ToArray();
         }
     }
     return(result);
 }
Exemplo n.º 5
0
        public string EncryptData(string data, Algorithm.StringTransformationFormat inputStringEncode, Algorithm.Cryptography cryptographyAlgorithm, Algorithm.StringEncodeFormat outputStringEncode)
        {
            string encryptText = string.Empty;

            if (!string.IsNullOrEmpty(data))
            {
                byte[] cipherText = null;
                try
                {
                    BinaryEncodeHelper encodeHelper = new BinaryEncodeHelper(Algorithm.StringTransformationFormat.UTF8);
                    byte[]             dataBinary   = encodeHelper.Decode(data);

                    switch (outputStringEncode)
                    {
                    case Algorithm.StringEncodeFormat.Base32:
                    {
                        encodeHelper.SetEncodeFormat(Algorithm.StringTransformationFormat.Base32);
                        break;
                    }

                    case Algorithm.StringEncodeFormat.Base64:
                    {
                        encodeHelper.SetEncodeFormat(Algorithm.StringTransformationFormat.Base64);
                        break;
                    }
                    }
                    switch (cryptographyAlgorithm)
                    {
                    case Algorithm.Cryptography.AES:
                    {
                        AESCryptography aes = new AESCryptography();
                        cipherText = aes.EncryptData(dataBinary);
                        m_Password = encodeHelper.Encode(aes.Password);
                        m_Salt     = encodeHelper.Encode(aes.Salt);
                        break;
                    }

                    case Algorithm.Cryptography.RSA:
                    {
                        RSACryptography rsa = new RSACryptography();
                        cipherText = rsa.EncryptData(dataBinary);
                        BinaryEncodeHelper encodeLittleHelper = new BinaryEncodeHelper(Algorithm.StringTransformationFormat.UTF8);
                        m_Password = encodeHelper.Encode(encodeLittleHelper.Decode(rsa.PublicKey));
                        break;
                    }
                    }

                    if (cipherText != null)
                    {
                        encryptText = encodeHelper.Encode(cipherText);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
            return(encryptText);
        }
        public byte[] GetEncrytionResponse(byte[] encryptCommand)
        {
            string keyAES      = "12345678123456781234567812345678";
            string ivAES       = "1122334455667788";
            string commandLine = AESCryptography.DecryptWithAES(encryptCommand, keyAES, ivAES);

            this.respose = GetResposed(commandLine) + "\r\n";
            return(AESCryptography.EncryptWithAES(this.respose, keyAES, ivAES));
        }
Exemplo n.º 7
0
        public void DecryptStringAESTest()
        {
            var cipherText = EncryptString();

            Assert.IsNotNull(cipherText);

            var decryptedText = AESCryptography.DecryptStringAES(cipherText, pass, salt);

            Assert.AreEqual(plainText, decryptedText);
        }
Exemplo n.º 8
0
 public ActionResult Edit([Bind(Include = "personaleID,fornavn,efternavn,brugernavn,adgangskode,rolleID")] Personale personale)
 {
     if (ModelState.IsValid)
     {
         personale.adgangskode     = AESCryptography.Encryption(personale.adgangskode);
         db.Entry(personale).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(personale));
 }
 private string GenerateAesKey(bool isEcb)
 {
     if (isEcb)
     {
         AESCryptography aESCryptography = new AESCryptography();
         return(aESCryptography.GenerateKey());
     }
     else
     {
         AESCBCModeCryptography aESCBCMode = new AESCBCModeCryptography();
         return(aESCBCMode.GenerateKey());
     }
 }
Exemplo n.º 10
0
        public ActionResult Create([Bind(Include = "personaleID,fornavn,efternavn,brugernavn,adgangskode,rolleID")] Personale personale)
        {
            if (ModelState.IsValid)
            {
                personale.adgangskode = AESCryptography.Encryption(personale.adgangskode);
                db.Personales.Add(personale);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            ModelState.Clear();
            ViewBag.Message = "Successfully Registered MR. " + personale.fornavn + " " + personale.efternavn;

            return(View(personale));
        }
Exemplo n.º 11
0
        public ActionResult <Boolean> DisconnectfromQBO(QBODisconnect qbodisconnect)
        {
            _logger.LogInfo("Start Disconnect for Subscriber " + qbodisconnect.Id);
            AESCryptography cryptography = new AESCryptography(_configuration);
            var             connString   = new QuickBooksOnlineConnectionStringBuilder();

            connString.Offline           = false;
            connString.Logfile           = "c:\\users\\public\\documents\\QBOLog.txt";
            connString.Verbosity         = "5";
            connString.OAuthClientId     = appClientId;
            connString.OAuthClientSecret = appClientSecret;
            connString.OAuthAccessToken  = qbodisconnect.Authtoken;
            connString.OAuthRefreshToken = cryptography.Decrypt(qbodisconnect.OAuthRefreshToken);
            connString.CompanyId         = cryptography.Decrypt(qbodisconnect.CompanyId);
            //connString.OAuthRefreshToken = "AB11614292706tcN0cfVUHXDtH4hovOiLE9ZmexvIIVNsIUErk";
            //connString.CompanyId = "193514469951999"; //PlanGuru LLC Support Company
            String callbackURL = _configuration["CFXServiceConfiguration:AuthanticateServiceEndPoint"] + "api/master/finalauthorize";

            currentMethodName = this.ControllerContext.RouteData.Values["action"].ToString();

            try
            {
                using (QuickBooksOnlineConnection connQBO = new QuickBooksOnlineConnection(connString.ToString()))
                {
                    connQBO.RuntimeLicense = runTimeLicense;

                    using (QuickBooksOnlineCommand cmdQBO = new QuickBooksOnlineCommand("DisconnectOauthAccessToken", connQBO))
                    {
                        cmdQBO.Parameters.Add(new QuickBooksOnlineParameter("CallbackURL", callbackURL));
                        cmdQBO.CommandType = CommandType.StoredProcedure;
                        var iSuccess = cmdQBO.ExecuteNonQuery();
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                _errorLogRepo.InsertErrorLog(new ErrorLog
                {
                    SubscriberId  = qbodisconnect.Id,
                    ErrorMessage  = ex.Message,
                    ServiceName   = serviceName,
                    MethodName    = currentMethodName,
                    ErrorDateTime = DateTime.Now
                });
                return(false);
            }
        }
Exemplo n.º 12
0
        public void LongDecryptTest()
        {
            var inputText = @"
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus viverra facilisis sapien ut commodo. Pellentesque porttitor tellus ut dui facilisis tincidunt. Phasellus sed mi enim. Fusce non orci diam. Vestibulum non felis sit amet neque ultrices consequat in ac dolor. Ut at lorem ac nunc gravida vestibulum sit amet in mauris. Quisque eleifend venenatis velit, pulvinar tempor velit sodales nec. Phasellus id mi lacus. Donec sed magna ligula, ut suscipit libero. Sed aliquet feugiat tristique. In nec metus lacus. Etiam malesuada gravida urna eu sagittis. Maecenas pretium feugiat felis eu ornare. Phasellus venenatis urna id turpis facilisis at eleifend turpis accumsan. Quisque sit amet elit nisl, sagittis pellentesque lorem. Mauris accumsan vestibulum neque, ut mollis dolor convallis nec. Suspendisse ornare vulputate justo at molestie.

              Aliquam ut fringilla leo. Nulla facilisi. Fusce placerat rutrum velit a tincidunt. Etiam quis massa metus. Praesent scelerisque tincidunt lectus et fermentum. In in ligula lectus, quis faucibus velit. Vivamus lacus eros, aliquet non viverra in, pharetra quis lacus. Sed mollis, eros non viverra tincidunt, magna metus blandit neque, a venenatis lectus lorem sit amet tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla arcu ipsum, tempor in euismod et, imperdiet vel augue. Etiam id nulla in lorem tristique volutpat non nec augue. Ut dignissim tincidunt lectus, semper dictum tellus suscipit vel. In rhoncus mollis leo, sit amet facilisis sapien volutpat quis. Cras viverra lorem ut erat facilisis molestie. Nunc id erat et libero rhoncus pharetra. Aenean sodales mauris ut metus lacinia consectetur.

              Sed varius tincidunt lorem, id porttitor odio tincidunt sed. Duis pellentesque, diam sit amet sodales imperdiet, sapien risus pellentesque eros, vitae condimentum nunc nibh sit amet purus. Maecenas nec metus id justo vulputate ullamcorper et ut ante. Sed commodo consequat diam, quis aliquet odio laoreet in. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis sed ipsum quam, quis congue sem. Nunc et nulla tortor. Curabitur at porttitor leo. Nullam varius tempus urna, vel lobortis mi malesuada nec. Sed mi diam, posuere eu aliquam vel, porttitor suscipit tellus. Vestibulum porttitor, nisl in blandit egestas, eros quam dictum risus, a interdum ipsum mauris non sem. Cras felis diam, elementum vel dictum in, fringilla et ipsum. Vivamus tristique mauris at dolor consequat in porta diam imperdiet. Donec arcu nisl, vestibulum a placerat sit amet, porttitor id est.

              Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nulla mattis nisl vel lorem bibendum facilisis at quis tellus. Ut vehicula lorem et leo scelerisque sollicitudin. Nulla facilisi. Phasellus vehicula malesuada nulla eu tincidunt. Ut lobortis libero quis metus condimentum at placerat magna ornare. Duis scelerisque fringilla lorem non luctus. Aliquam facilisis lacus id magna fermentum laoreet in ultrices erat. Etiam ac odio porta libero volutpat pulvinar. Praesent vel facilisis massa. Curabitur nulla nisl, dignissim vitae consequat a, venenatis in erat. Etiam a nisi eu sem lobortis sollicitudin. Donec ante massa, tristique eu dapibus id, vehicula sit amet urna. Sed a arcu nunc. Mauris volutpat, metus eget vehicula interdum, nisl nisl bibendum enim, sit amet vehicula turpis sem eu magna.

              Mauris venenatis, arcu id accumsan faucibus, eros urna mattis leo, et viverra sapien urna et dui. Nunc risus tellus, congue nec tempus ac, pharetra semper neque. Nam pharetra semper faucibus. Sed in tortor nec mauris porttitor mattis nec sit amet lectus. Nulla non dignissim neque. Curabitur neque enim, ultricies vitae tempor ut, aliquet ut quam. Aliquam sed sapien et odio rhoncus pharetra vel at dui. Fusce consequat, arcu et feugiat vulputate, tellus turpis tempus elit, eget sodales diam ante id nibh. Donec ornare pellentesque lectus vitae tempor. Nulla ac lorem eros, quis volutpat justo. Donec egestas justo quis mi ullamcorper ornare. Sed sit amet ligula at nunc commodo rhoncus.
              ";

            var cipherText = EncryptString(inputText);

            Assert.IsNotNull(cipherText);

            var decryptedText = AESCryptography.DecryptStringAES(cipherText, pass, salt);

            Assert.AreEqual(inputText, decryptedText);
        }
Exemplo n.º 13
0
        private async void Btn_Encrypt_ClickAsync(object sender, EventArgs e)
        {
            if (Rdb_RsaEncrypt.Checked)
            {
                var Enc = await Rsa.EncryptAsync(Txt_PublicKey.Text, Txt_PlainText.Text);

                Txt_CipherText.Text = Enc;
            }
            else
            {
                try
                {
                    AESCryptography Aes = new AESCryptography();
                    var             Enc = Aes.EncryptAsync(Txt_PublicKey.Text, Txt_PlainText.Text);
                    Txt_CipherText.Text = Enc;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.GetErrorMessage());
                }
            }
        }
Exemplo n.º 14
0
        public void EncryptStringAESTest()
        {
            var aesString = AESCryptography.EncryptStringAES(plainText, pass, salt);

            Assert.IsNotNull(aesString);
        }
Exemplo n.º 15
0
 public void BadPasswordTest()
 {
     var cipherText    = EncryptString();
     var decryptedText = AESCryptography.DecryptStringAES(cipherText, "A bad password", salt);
 }
Exemplo n.º 16
0
        private void StartDecrypting(Object sender, RoutedEventArgs e)
        {
            if (filename == null)
            {
                MessageBox.Show("No file chosen", "Cryptographer", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            string selectedUserEmail;

            try
            {
                selectedUserEmail = usersBox.SelectedItem.ToString().Split(' ')[1];
            }
            catch (Exception) { return; }

            if (selectedUserEmail != UsersControler.currentUser.email)
            {
                var x = usersBox.SelectedItem.ToString();
                var y = UsersControler.currentUser.email;
                return;
            }

            string      encryptedFileContent = File.ReadAllText(filepath);
            string      XMLStringMetadata    = encryptedFileContent.Split(new[] { "</EncryptedFileHeader>" }, StringSplitOptions.None)[0] + "</EncryptedFileHeader>";
            string      encyptedData         = encryptedFileContent.Split(new[] { "</EncryptedFileHeader>" }, StringSplitOptions.None)[1];
            string      sessionKey           = null;
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(XMLStringMetadata);

            byte[] IV = Convert.FromBase64String(doc.SelectSingleNode("EncryptedFileHeader/IV").InnerText);

            CipherMode encryptionMode = 0;
            string     cipherMode     = doc.SelectSingleNode("EncryptedFileHeader/CipherMode").InnerText;

            if (cipherMode == "ECB")
            {
                encryptionMode = CipherMode.ECB;
            }
            if (cipherMode == "CBC")
            {
                encryptionMode = CipherMode.CBC;
            }
            if (cipherMode == "CFB")
            {
                encryptionMode = CipherMode.CFB;
            }

            XmlNodeList approvedUserNodes = doc.SelectNodes("/EncryptedFileHeader/ApprovedUsers");

            foreach (XmlNode node in approvedUserNodes)
            {
                if (UsersControler.currentUser.email == node.SelectSingleNode("User/Email").InnerText)
                {
                    string encryptedSessionKey = node.SelectSingleNode("User/SessionKey").InnerText;
                    sessionKey = Decrypt(encryptedSessionKey, UsersControler.currentUser.rsaPublicPrivateKey);
                    break;
                }
            }
            if (sessionKey == null)
            {
                MessageBox.Show("No user fitting to detailed in XML metadata");
                return;
            }
            SaveFileDialog sf = new SaveFileDialog();

            sf.FileName = filename.Remove(filename.Length - 4);
            bool?safeDialogResult = sf.ShowDialog();

            if (safeDialogResult == true)
            {
                File.WriteAllText(Path.GetFullPath(sf.FileName), AESCryptography.DecryptStringFromBytes(Convert.FromBase64String(encyptedData), Convert.FromBase64String(sessionKey), IV, encryptionMode));
            }
        }
Exemplo n.º 17
0
        public ActionResult <QBSyncResponse> Client(int id)
        {
            //If the id is 0, return all subscribers otherwise return the requested subscriber
            string bRtn;
            bool   updateAccessTableResult;

            subscriberId = id;
            IEnumerable <Subscriber> subscriber;

            currentMethodName = this.ControllerContext.RouteData.Values["action"].ToString();

            if (subscriberId == 0)
            {
                subscriber = _subscriberRepo.GetAllSubscribers();
            }
            else
            {
                subscriber = _subscriberRepo.GetById(subscriberId);
                if (subscriber == null)
                {
                    _logger.LogError("subscriber not found");
                    return(new QBSyncResponse()
                    {
                        ResponseStatus = false,
                        ResponseMessage = "Subscriber not found."
                    });
                }
            }

            foreach (Subscriber subs in subscriber)
            {
                subscriberId = subs.Id;
                _logger.LogInfo("Begin Subscriber " + subscriberId + " Authorization");
                QBOAccess qboAccess = _qboaccessRepo.GetById(subscriberId);
                if (qboAccess == null)
                {
                    _logger.LogError("You must authorize with QuickBooks before syncing your data.");
                    return(new QBSyncResponse()
                    {
                        ResponseStatus = false,
                        ResponseMessage = "You must authorize with QuickBooks before syncing your data."
                    });
                }
                // save Access Id
                int qboAccessId = qboAccess.Id;

                // Refresh QBO connection
                bRtn = RefreshQBO(qboAccess);
                if (bRtn != SuccessMessage)
                {
                    _qboaccessRepo.DeleteQBOAccess(subscriberId);
                    return(new QBSyncResponse()
                    {
                        ResponseStatus = false,
                        ResponseMessage = bRtn
                    });
                }
                // Update Access table with new refresh token
                try
                {
                    AESCryptography cryptography = new AESCryptography(_configuration);
                    appOauthRefreshToken = cryptography.Encrypt(appOauthRefreshToken);
                    if (IsAllDigits(qboAccess.Company))
                    {
                        companyId = cryptography.Encrypt(qboAccess.Company);
                    }
                    else
                    {
                        companyId = qboAccess.Company;
                    }
                    updateAccessTableResult = _qboaccessRepo.UpdateQBOAccess(qboAccessId, companyId, appOauthAccessToken, appOauthRefreshToken, qboAccess);
                    if (updateAccessTableResult == false)
                    {
                        _logger.LogError("You will need to re-authorize your QuickBooks account and try to sync again.");
                        return(new QBSyncResponse()
                        {
                            ResponseStatus = false,
                            ResponseMessage = "You will need to re-authorize your QuickBooks account and try to sync again."
                        });
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("error occurred" + ex.Message);
                    _errorLogRepo.InsertErrorLog(new ErrorLog
                    {
                        SubscriberId  = subscriberId,
                        ErrorMessage  = ex.Message,
                        ServiceName   = serviceName,
                        MethodName    = currentMethodName,
                        ErrorDateTime = DateTime.Now
                    });
                    return(new QBSyncResponse()
                    {
                        ResponseStatus = false,
                        ResponseMessage = "Error occurred " + ex.Message
                    });
                }
                _logger.LogInfo("End Subscriber " + subscriberId + " Authorization");

                //Time to get some data from QBO
                _logger.LogInfo("Begin QBO Data Access for Subscriber " + subscriberId);
                // Get and Update Customers & Invoices
                bRtn = GetQBOCustomers(qboAccess);
                if (bRtn != SuccessMessage)
                {
                    _logger.LogError(bRtn);
                    return(new QBSyncResponse()
                    {
                        ResponseStatus = false,
                        ResponseMessage = bRtn
                    });
                }
                _logger.LogInfo("End QBO Data Access for Subscriber " + subscriberId);
                //Update the last sync date in the subscriber table
                var updateSyncDateResult = _subscriberRepo.UpdateSubscriber(subscriberId, DateTime.Now, subs);
                if (updateSyncDateResult == false)
                {
                    _logger.LogError("Not able to update last sync date for subscriber");
                    return(new QBSyncResponse()
                    {
                        ResponseStatus = false,
                        ResponseMessage = "Not able to update last sync date for subscriber"
                    });
                }
            }
            return(new QBSyncResponse()
            {
                ResponseStatus = true,
                ResponseMessage = SuccessMessage
            });
        }
Exemplo n.º 18
0
 public void BadSaltTest()
 {
     var cipherText    = EncryptString();
     var badSalt       = Encoding.ASCII.GetBytes("11112222");
     var decryptedText = AESCryptography.DecryptStringAES(cipherText, pass, badSalt);
 }
Exemplo n.º 19
0
        public ContentResult FinalAuthorize()
        {
            string verifierToken      = "";
            var    webRoot            = _env.ContentRootPath;
            var    successFileContent = System.IO.File.ReadAllText(webRoot + "/HTMLResponse/Successful.html");
            var    failureFileContent = System.IO.File.ReadAllText(webRoot + "/HTMLResponse/Unsuccessful.html");
            int    sid;

            try
            {
                sid = (int)HttpContext.Session.GetInt32("subscriberId");
            }
            catch (Exception)
            {
                sid = _cache.Get <int>("subscriberId");
            }
            // will delete this
            //var qboQueryString = Request.Query;
            //foreach (var qbItem in qboQueryString.Keys)
            //{
            //    System.Diagnostics.Debug.WriteLine("Key: " + qbItem + ", Value: " + Request.Query[qbItem]);
            //}
            _logger.LogInfo("Start FinalAuthorize for Subscriber " + sid);
            string qboCode = Request.Query["code"];

            if (qboCode == null)
            {
                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = failureFileContent
                });
            }
            verifierToken = qboCode;
            companyId     = Request.Query["realmid"];
            var connString = new QuickBooksOnlineConnectionStringBuilder();

            connString.OAuthClientId     = appClientId;
            connString.OAuthClientSecret = appClientSecret;
            connString.UseSandbox        = useSandBox;
            connString.Logfile           = "c:\\users\\public\\documents\\QBOLog.txt";
            connString.Verbosity         = "5";
            string callbackURL = _configuration["CFXServiceConfiguration:AuthanticateServiceEndPoint"] + "api/master/finalauthorize";

            currentMethodName = this.ControllerContext.RouteData.Values["action"].ToString();

            try
            {
                using (QuickBooksOnlineConnection connQBO = new QuickBooksOnlineConnection(connString.ToString()))
                {
                    connQBO.RuntimeLicense = runTimeLicense;
                    using (QuickBooksOnlineCommand cmdQBO = new QuickBooksOnlineCommand("GetOAuthAccessToken", connQBO))
                    {
                        cmdQBO.Parameters.Add(new QuickBooksOnlineParameter("Authmode", "WEB"));
                        cmdQBO.Parameters.Add(new QuickBooksOnlineParameter("Verifier", verifierToken));
                        cmdQBO.Parameters.Add(new QuickBooksOnlineParameter("CompanyId", companyId));
                        cmdQBO.Parameters.Add(new QuickBooksOnlineParameter("CallbackURL", callbackURL));
                        cmdQBO.CommandType = CommandType.StoredProcedure;

                        using (QuickBooksOnlineDataReader reader = cmdQBO.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                appOauthAccessToken  = (String)reader["OAuthAccessToken"];
                                appOauthRefreshToken = (String)reader["OAuthRefreshToken"];
                            }
                            else
                            {
                                _errorLogRepo.InsertErrorLog(new ErrorLog
                                {
                                    SubscriberId  = sid,
                                    ErrorMessage  = "No OAuthRefreshToken available",
                                    ServiceName   = serviceName,
                                    MethodName    = currentMethodName,
                                    ErrorDateTime = DateTime.Now
                                });
                                return(new ContentResult
                                {
                                    ContentType = "text/html",
                                    Content = failureFileContent
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _errorLogRepo.InsertErrorLog(new ErrorLog
                {
                    SubscriberId  = sid,
                    ErrorMessage  = ex.Message,
                    ServiceName   = serviceName,
                    MethodName    = currentMethodName,
                    ErrorDateTime = DateTime.Now
                });
                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = failureFileContent
                });
            }
            // Get/Update our QBOAccess record
            bool bRtn;

            DataServices.Models.QBOAccess qboAccess = _qboaccessRepo.GetById(sid);
            AESCryptography cryptography            = new AESCryptography(_configuration);

            companyId            = cryptography.Encrypt(companyId);
            appOauthRefreshToken = cryptography.Encrypt(appOauthRefreshToken);
            if (qboAccess == null)
            {
                bRtn = _qboaccessRepo.AddQBOAccess(appClientId, appClientSecret, companyId, appOauthAccessToken, appOauthRefreshToken, sid);
            }
            else
            {
                bRtn = _qboaccessRepo.UpdateQBOAccess(qboAccess.Id, companyId, appOauthAccessToken, appOauthRefreshToken, qboAccess);
            }
            if (bRtn == true)
            {
                _logger.LogInfo("End FinalAuthorize for Subscriber " + sid);
                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = successFileContent
                });
            }
            return(new ContentResult
            {
                ContentType = "text/html",
                Content = failureFileContent
            });
        }
Exemplo n.º 20
0
        public string DecryptData(string encryptText, Algorithm.StringEncodeFormat inputStringEncode, Algorithm.Cryptography cryptographyAlgorithm, Algorithm.StringTransformationFormat outputStringEncode)
        {
            string data = string.Empty;

            if (!string.IsNullOrEmpty(encryptText))
            {
                byte[] cipherText = null;
                byte[] password   = null;
                byte[] salt       = null;
                try
                {
                    BinaryEncodeHelper encodeHelper = new BinaryEncodeHelper(Algorithm.StringTransformationFormat.Base64);
                    switch (inputStringEncode)
                    {
                    case Algorithm.StringEncodeFormat.Base32:
                    {
                        encodeHelper.SetEncodeFormat(Algorithm.StringTransformationFormat.Base32);
                        break;
                    }

                    case Algorithm.StringEncodeFormat.Base64:
                    {
                        encodeHelper.SetEncodeFormat(Algorithm.StringTransformationFormat.Base64);
                        break;
                    }
                    }
                    cipherText = encodeHelper.Decode(encryptText);
                    if (!string.IsNullOrEmpty(m_Password))
                    {
                        password = encodeHelper.Decode(m_Password);
                    }
                    if (!string.IsNullOrEmpty(m_Salt))
                    {
                        salt = encodeHelper.Decode(m_Salt);
                    }

                    byte[] text = null;
                    switch (cryptographyAlgorithm)
                    {
                    case Algorithm.Cryptography.AES:
                    {
                        if (cipherText != null && password != null && salt != null)
                        {
                            AESCryptography aes = new AESCryptography(password, salt);
                            text = aes.DecryptData(cipherText);
                        }
                        break;
                    }

                    case Algorithm.Cryptography.RSA:
                    {
                        RSACryptography rsa = new RSACryptography();
                        text = rsa.DecryptData(cipherText);
                        break;
                    }
                    }
                    if (text != null)
                    {
                        encodeHelper.SetEncodeFormat(outputStringEncode);
                        data = encodeHelper.Encode(text);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
            return(data);
        }
Exemplo n.º 21
0
 public void SaltOutOfRangeTest()
 {
     var cipherText    = EncryptString();
     var badSalt       = Encoding.ASCII.GetBytes("bad");
     var decryptedText = AESCryptography.DecryptStringAES(cipherText, pass, badSalt);
 }
Exemplo n.º 22
0
        private string EncryptString(string inputText)
        {
            var cipherText = AESCryptography.EncryptStringAES(inputText, pass, salt);

            return(cipherText);
        }
Exemplo n.º 23
0
 public AESCryptographyTest()
 {
     this.aesCrypt = new AESCryptography();
     this.aesCrypt.Key = new System.Text.ASCIIEncoding().GetBytes("1234512345123456");
 }
Exemplo n.º 24
0
        private void StartEncoding(Object sender, RoutedEventArgs e)
        {
            if (filename == null)
            {
                MessageBox.Show("No file chosen", "Cryptographer", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            CipherMode encryptionMode = 0;

            if ((bool)ECBRadioButton.IsChecked)
            {
                encryptionMode = CipherMode.ECB;
            }
            if ((bool)CBCRadioButton.IsChecked)
            {
                encryptionMode = CipherMode.CBC;
            }
            if ((bool)CFBRadioButton.IsChecked)
            {
                encryptionMode = CipherMode.CFB;
            }

            String fileContent = File.ReadAllText(filepath);

            if (encryptionMode == 0)
            {
                MessageBox.Show("You must choose encryption mode", "Cryptographer", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            List <User> encryptionUsers = new List <User>();

            foreach (ListBoxItem userItem in usersBox.Items)
            {
                if (userItem.IsSelected)
                {
                    encryptionUsers.Add(GetUserFromFile(userItem.Content.ToString()));
                }
            }

            if (encryptionUsers.Count == 0)
            {
                MessageBox.Show("No receiver choosen", "Cryptographer", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            byte[] generatedIV         = null;
            byte[] generatedSessionKey = null;
            RSA    sessionKey          = new RSACryptoServiceProvider(2048); // Generate a new 2048 bit RSA key

            using (RijndaelManaged myRijndael = new RijndaelManaged())
            {
                myRijndael.GenerateKey();
                generatedSessionKey = myRijndael.Key;

                myRijndael.GenerateIV();
                generatedIV = myRijndael.IV;
            }

            var approvedUsers = new XElement("ApprovedUsers");

            foreach (var user in encryptionUsers)
            {
                var encryptedSessionKey = Encrypt(Convert.ToBase64String(generatedSessionKey), user.rsaPublicKey);
                approvedUsers.Add(new XElement("User",
                                               new XElement("Email", user.email),
                                               new XElement("SessionKey", encryptedSessionKey)
                                               ));
            }

            var fileHeaders = new XElement("EncryptedFileHeader");

            fileHeaders.Add(new XElement("Algorithm", "AES"));
            fileHeaders.Add(new XElement("KeySize", "196")); // TODO is it OK?
            fileHeaders.Add(new XElement("BlockSize", "128"));
            fileHeaders.Add(new XElement("CipherMode", encryptionMode.ToString()));
            fileHeaders.Add(new XElement("IV", Convert.ToBase64String(generatedIV)));
            fileHeaders.Add(approvedUsers);

            var resultXMLFile = new XDocument(
                fileHeaders
                );

            resultXMLFile.Save(ResultFileNameBox.Text + ".xml"); // Path.GetExtension(filepath)

            // var temp = AESCryptography.EncryptStringToBytes(File.ReadAllText(filepath), generatedSessionKey, generatedIV, encryptionMode);
            // var temp1 = AESCryptography.DecryptStringFromBytes(temp, generatedSessionKey, generatedIV, encryptionMode);

            using (StreamWriter sw = File.AppendText(ResultFileNameBox.Text + ".xml"))
            {
                sw.Write(Convert.ToBase64String(AESCryptography.EncryptStringToBytes(File.ReadAllText(filepath), generatedSessionKey, generatedIV, encryptionMode)));
            }
        }
Exemplo n.º 25
0
 public void AESCreateTest()
 {
     var aes = new AESCryptography();
 }
Exemplo n.º 26
0
 public override Byte[] Decrypt(Byte[] bytes)
 {
     return(AESCryptography.Decrypt(bytes));
 }
Exemplo n.º 27
0
        //Refresh QBO
        private string RefreshQBO(QBOAccess qboAccess)
        {
            _logger.LogInfo("Refresh QBO started for subscriber id" + subscriberId);
            AESCryptography cryptography = new AESCryptography(_configuration);
            var             connString   = new QuickBooksOnlineConnectionStringBuilder();

            connString.Offline           = false;
            connString.OAuthClientId     = qboAccess.ClientId;
            connString.OAuthClientSecret = qboAccess.ClientSecret;
            if (!IsAllDigits(qboAccess.Company))
            {
                qboAccess.Company      = cryptography.Decrypt(qboAccess.Company);
                qboAccess.RefreshToken = cryptography.Decrypt(qboAccess.RefreshToken);
            }
            connString.CompanyId         = qboAccess.Company;
            connString.OAuthRefreshToken = qboAccess.RefreshToken;
            connString.OAuthVersion      = "2.0";
            connString.UseSandbox        = useSandBox;
            //connString.InitiateOAuth = "GETANDREFRESH";
            connString.Logfile   = "c:\\users\\public\\documents\\rssApiLog.txt";
            connString.Verbosity = "5";
            currentMethodName    = this.ControllerContext.RouteData.Values["action"].ToString();

            try
            {
                using (QuickBooksOnlineConnection connQBO = new QuickBooksOnlineConnection(connString.ToString()))
                {
                    connQBO.RuntimeLicense = runTimeLicense;
                    using (QuickBooksOnlineCommand cmdQBO = new QuickBooksOnlineCommand("RefreshOAuthAccessToken", connQBO))
                    {
                        cmdQBO.Parameters.Add(new QuickBooksOnlineParameter("OAuthRefreshToken", qboAccess.RefreshToken));
                        cmdQBO.CommandType = CommandType.StoredProcedure;

                        using (QuickBooksOnlineDataReader reader = cmdQBO.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                appOauthAccessToken  = (String)reader["OAuthAccessToken"];
                                appOauthRefreshToken = (String)reader["OAuthRefreshToken"];
                            }
                            else
                            {
                                _errorLogRepo.InsertErrorLog(new ErrorLog
                                {
                                    SubscriberId  = qboAccess.SubscriberId,
                                    ErrorMessage  = "You will need to re-authorize your QuickBooks account and try to sync again.",
                                    ServiceName   = serviceName,
                                    MethodName    = currentMethodName,
                                    ErrorDateTime = DateTime.Now
                                });
                                return("You will need to re-authorize your QuickBooks account and try to sync again.");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("error occurred in refresh qbo method " + ex.Message);
                _errorLogRepo.InsertErrorLog(new ErrorLog
                {
                    SubscriberId  = qboAccess.SubscriberId,
                    ErrorMessage  = ex.Message,
                    ServiceName   = serviceName,
                    MethodName    = currentMethodName,
                    ErrorDateTime = DateTime.Now
                });
                return(ex.Message);
            }
            _logger.LogInfo("Refresh QBO ended for subscriber id" + subscriberId);
            return(SuccessMessage);
        }