public string GetCookie(string CookieName) { if (System.Web.HttpContext.Current.Request.Cookies[CookieName] != null) { return(rijndaelKey.Decrypt(System.Web.HttpContext.Current.Request.Cookies[CookieName].Value.ToString())); } else { return(""); } }
public void TestJwt() { string plainText = "Проверка!"; // original plaintext string passPhrase = "Pas5pr@sePas5pr@sePas5pr@sePas5pr@sePas5pr@se"; // can be any string string initVector = "@1B2c3D4e5F6g7H8"; // must be 16 bytes // Before encrypting data, we will append plain text to a random // salt value, which will be between 4 and 8 bytes long (implicitly // used defaults). using (var rijndaelKey = new RijndaelEnhanced(passPhrase, initVector, 8, 16, 256, "qwertyuiqwertyuiqwertyui", 1000)) { // Encrypt the same plain text data 10 time (using the same key, // initialization vector, etc) and see the resulting cipher text; // encrypted values will be different. for (int i = 0; i < 10; i++) { string cipherText = rijndaelKey.Encrypt(plainText); string decripted = rijndaelKey.Decrypt(cipherText); Assert.Equal(plainText, decripted); using (var rijndaelKey2 = new RijndaelEnhanced(passPhrase, initVector, 8, 16, 256, "qwertyuiqwertyuiqwertyui", 1000)) { string decripted2 = rijndaelKey2.Decrypt(cipherText); Assert.Equal(plainText, decripted2); } } } }
public static string Decrypt(string stringToDecrypt, string iv) { string pp = MachineKeySettings.MachineKey; RijndaelEnhanced crypto = new RijndaelEnhanced(pp, iv); return crypto.Decrypt(stringToDecrypt); }
public string GetConnectionString(string Name) { if (ConfigurationManager.ConnectionStrings[Name] == null) { return(""); } RijndaelEnhanced rijndaelKey = new RijndaelEnhanced("20b2", "@1B2c3D4e5F6g7H8"); return(rijndaelKey.Decrypt(ConfigurationManager.ConnectionStrings[Name].ConnectionString)); }
public static Dictionary <string, string> DocIdToKeys(string DocId) { return(string.IsNullOrWhiteSpace(DocId) ? new Dictionary <string, string>() : Serialize.Json.Deserialize <Dictionary <string, string> >( rijndaelKey .Decrypt( DocId .Replace("_", "/") .Replace("-", "+") .Replace("%3d", "=")))); }
public static string Decrypt(string key, string encryptedValue) { string value = string.Empty; try { RijndaelEnhanced rijndaelKey = new RijndaelEnhanced(key); value = rijndaelKey.Decrypt(encryptedValue); } catch (Exception error) { Console.WriteLine("Error Occurred | Decrypter Failed |" + error); } return(value); }
public static string DecryptString(string str) { string passPhrase = _passPhrase; string initVector = _initVector; RijndaelEnhanced rijndaelKey = new RijndaelEnhanced(passPhrase, initVector); string decryptedString = ""; try { decryptedString = rijndaelKey.Decrypt(str); } catch { } return(decryptedString); }
/// <summary> /// Decrypt the SOAP Stream BeforeSerialize. /// </summary> /// <param name="message"></param> private void Decrypt(SoapMessage message) { if (encryptMessage) { CopyBinaryStream(oldStream, newStream); MemoryStream ms = new MemoryStream(); newStream.Position = 0; CopyBinaryStream(newStream, ms); ms.Position = 0; byte[] encryptedBytes = ms.ToArray(); RijndaelEnhanced rj = new RijndaelEnhanced(sPassPhrase, sInitVector); if (compressMessage) { byte[] compressedBytes = rj.DecryptToBytes(encryptedBytes); newStream.Position = 0; BinaryWriter binaryWriter = new BinaryWriter(newStream); binaryWriter.Write(compressedBytes); binaryWriter.Flush(); } else { string soapMessage = rj.Decrypt(encryptedBytes);; newStream.Position = 0; StreamWriter streamWriter = new StreamWriter(newStream); // Clear all newStream contents with WhiteSpace before overwrite for (int i = 0; i < newStream.Length; i++) { streamWriter.Write(" "); streamWriter.Flush(); } newStream.Position = 0; streamWriter.Write(soapMessage); streamWriter.Flush(); } newStream.Position = 0; } }
public static bool authorise(string remKey, string passKey) { try { String iniVector = "@1B2c3D4e5F6g7H8"; [email protected] hasher = new RijndaelEnhanced(passKey, iniVector); String key = File.ReadAllText("License.key"); if (remKey == hasher.Decrypt(key)) { return(true); } else { return(false); } } catch (Exception e) { return(false); } }
public JsonResult GetUsers() { _cnn.Open(); var re = new RijndaelEnhanced(Key, InitVector); var userList = new List <UsersModel>(); var selectAll = new SqlCommand("SELECT dbo.sec_info.sign,dbo.sec_info.id,dbo.sec_info.usrlevel,ROW_NUMBER()over(order by dbo.sec_info.id)as rn " + ", dbo.sec_info.name,dbo.sec_info.username, dbo.sec_info.password,sec_info.tell,sec_info.email,sec_info.office_id, " + "CASE WHEN sec_info.usrlevel = 0 THEN 'مدیریت' WHEN sec_info.usrlevel = 1 " + "THEN 'دبیرخانه' ELSE 'شرکت تابعه' END AS uslevel, dbo.sec_info.permit, dbo.office_list.office_name " + "FROM dbo.sec_info INNER JOIN dbo.office_list ON dbo.sec_info.office_id = dbo.office_list.office_id", _cnn); var rd = selectAll.ExecuteReader(); while (rd.Read()) { var password = re.Decrypt(rd["password"].ToString()); userList.Add(new UsersModel() { Id = Convert.ToInt32(rd["id"]), UserLevel = Convert.ToInt32(rd["usrlevel"]), Name = rd["name"].ToString() , UserName = rd["username"].ToString(), Password = password, UsrLvl = rd["uslevel"].ToString(), Permit = Convert.ToInt32(rd["permit"]), OfficeId = Convert.ToInt32(rd["office_id"]) , OfficeName = rd["office_name"].ToString(), Tell = rd["tell"].ToString(), Email = rd["email"].ToString(), Sign = rd["sign"].ToString() }); } _cnn.Close(); return(new JsonResult(userList)); }
protected void btDeEncrypt_Click(object sender, EventArgs e) { RijndaelEnhanced rijndaelKey = new RijndaelEnhanced(txtKey.Text, "@1B2c3D4e5F6g7H8"); txtResult.Text = rijndaelKey.Decrypt(txtData.Text); }
private void UpdateData() { try { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); List <Field> fields = jsSerializer.Deserialize <List <Field> >(Request.Form["fields"]); Campaign objcampaign = (Campaign)Session["Campaign"]; XmlDocument xDocCampaign = new XmlDocument(); xDocCampaign.LoadXml(Serialize.SerializeObject(objcampaign, "Campaign")); System.Text.StringBuilder sbQuery = new System.Text.StringBuilder(); System.Collections.ArrayList alfields = new ArrayList(); bool bolLastWasEncrypted = false; if (fields.Count > 0) { sbQuery.Append("UPDATE Campaign SET "); for (int i = 0; i < fields.Count; i++) { Field field = fields[i]; string fieldName = field.name; string fieldValue = field.value; if (i == (fields.Count - 1)) { // uniquekey sbQuery.AppendFormat("WHERE {0}={1} ", fieldName, fieldValue); break; } if (alfields.Contains(fieldName)) { continue; } alfields.Add(fieldName); //if it is encrypted then run the algorythm if (field.type == "encrypted") { if (fieldValue != "This is encrypted data") { string plainText = fieldValue; string cipherText = ""; // encrypted text string passPhrase = "whatevesfasdfasdfr23"; // can be any string string initVector = "Qt@&^SDF15F6g7H8"; // must be 16 bytes // Before encrypting data, we will append plain text to a random // salt value, which will be between 4 and 8 bytes long (implicitly // used defaults). RijndaelEnhanced rijndaelKey = new RijndaelEnhanced(passPhrase, initVector); Console.WriteLine(String.Format("Plaintext : {0}\n", plainText)); // Encrypt the same plain text data 10 time (using the same key, // initialization vector, etc) and see the resulting cipher text; // encrypted values will be different. for (int ii = 0; ii < 10; ii++) { cipherText = rijndaelKey.Encrypt(plainText); Console.WriteLine( String.Format("Encrypted #{0}: {1}", ii, cipherText)); plainText = rijndaelKey.Decrypt(cipherText); } // Make sure we got decryption working correctly. Console.WriteLine(String.Format("\nDecrypted :{0}", plainText)); fieldValue = cipherText; fieldValue = "'" + fieldValue + "'"; } } else { fieldValue = fieldValue.Replace("'", "''"); if (fieldValue.Trim() != "") { if (field.type == "s" || field.type == "dt" || IsCampaignDefined(fieldName)) { fieldValue = "'" + fieldValue + "'"; } else if (field.type == "bool") { bool value = false; try { if (IsInt(fieldValue)) { value = Convert.ToBoolean(Convert.ToInt32(fieldValue)); } else { value = Convert.ToBoolean(fieldValue); } } catch { } fieldValue = value ? "1" : "0"; } } else { fieldValue = "null"; } } if (fieldValue != "This is encrypted data") { if (!bolLastWasEncrypted) { sbQuery.AppendFormat("{2}{0}={1} ", fieldName, fieldValue, i == 0 ? "" : ","); } else { sbQuery.AppendFormat("{0}={1} ", fieldName, fieldValue); } bolLastWasEncrypted = false; } else { //set that last field in recordset an encrypted so don't use comma bolLastWasEncrypted = true; } } string sbQuerystring = sbQuery.ToString(); if (!sbQuerystring.StartsWith("UPDATE Campaign SET WHERE")) { CampaignService campService = new CampaignService(); if (Session["LoggedAgent"] != null) { ActivityLogger.WriteAgentEntry((Agent)Session["LoggedAgent"], "Posting campaign update query: '{0}'.", sbQuery.ToString()); } campService.UpdateCampaignDetails(xDocCampaign, sbQuery.ToString()); long key = 0; try { key = Convert.ToInt64(Session["UniqueKey"]); } catch { } if (key > 0) { DataSet dsCampaigndtls = (DataSet)Session["CampaignDtls"]; long queryId = 0; try { queryId = Convert.ToInt64(dsCampaigndtls.Tables[0].Rows[0]["QueryId"]); } catch { } dsCampaigndtls = campService.GetCampaignDetailsByKey(objcampaign.CampaignDBConnString, key, queryId); if (dsCampaigndtls != null) { if (dsCampaigndtls.Tables[0].Rows.Count > 0) { Session["CampaignDtls"] = dsCampaigndtls; } } } } } } catch (Exception ex) { if (Session["LoggedAgent"] != null) { ActivityLogger.WriteAgentEntry((Agent)Session["LoggedAgent"], "PostCampaignDetails UpdateData exception : '{0}'.", ex.Message); } throw ex; } }
//public static string _CONNECTION_STRING = getConnStr("CONNECTION_STRING"); public static string getConnStr(string Name) { RijndaelEnhanced rijndaelKey = new RijndaelEnhanced("CDR", "@1B2c3D4e5F6g7H8"); return rijndaelKey.Decrypt("J0/HDHjRC+z1MzutidYOtcOXlINZ4zcLb4F9wvHuWqos5rjdo1FrhYp8ltTX3EpH"); //ConfigurationManager.ConnectionStrings[Name].ConnectionString }
public string Decrypt(string data, string key) { var rij = new RijndaelEnhanced(key); return rij.Decrypt(data); }
/// <summary> /// Saves result code for call, /// update agent Stat, /// and update status to Ready for waiting for call agent, /// update call campaign fields /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lbtnSave_Click(object sender, EventArgs e) { try { string exportFilePath = ""; string exportFileName = txtFileName.Text; if (txtFileName.Text.Length < 1) { Response.Write("<script>alert('You must specify a valid file name.');</script>"); return; } try { exportFilePath = Path.Combine(Server.MapPath("~/campaign/DataExports/"), exportFileName); } catch { Response.Write("<script>alert('Error creating a file path on the server. Your filename may have invalid characters or saving on the server may not be permitted.');</script>"); return; } Campaign currentCampaign = new Campaign(); if (Session["Campaign"] != null) { // we have an existing campaign currentCampaign = (Campaign)Session["Campaign"]; } else { Response.Write("<script>alert('There is no campaign selected to export from. Please go back to Data Manager and select one.');</script>"); return; } if (Session["SelectStmt"] == null || Session["SelectStmt"].ToString().Length < 2) { Response.Write("<script>alert('There is no query selected to export from. Please go back to Data Manager and select one.');</script>"); return; } //Response.Write("<script>alert('Please wait for the Save As dialog to appear. \n The system is working on your export.\n Depending on your export size, this may take a few minutes. \n Only close the window after you have been prompted to save.');</script>"); string selectStatement = Session["SelectStmt"].ToString(); // Load up the query dsExportData.ConnectionString = currentCampaign.CampaignDBConnString; dsExportData.SelectCommand = selectStatement; DataView dv = new DataView(); dv = (DataView)dsExportData.Select(DataSourceSelectArguments.Empty); // add csv extension unless another extension exists if (exportFilePath.LastIndexOf('.') < (exportFilePath.Length - 4)) { exportFilePath = exportFilePath + ".csv"; exportFileName = exportFileName + ".csv"; } // Make the file FileInfo file = new FileInfo(exportFilePath); file.Directory.Create(); //Response.Write("<script>displayLoading();</script>"); // Open the file stream object to start writing StreamWriter sw = new StreamWriter(exportFilePath, false); DataRowView drv = dv[0]; // Write out column names int iColCount = dv.Table.Columns.Count; string fieldContents = ""; for (int i = 0; i < iColCount; i++) { fieldContents = dv.Table.Columns[i].ToString(); // Remove commas fieldContents = fieldContents.Replace(",", " "); sw.Write(fieldContents); if (i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); ActivityLogger.WriteAdminEntry(currentCampaign, "Exporting {0} record to file '{1}'", dv.Table.Rows.Count, exportFilePath); // Now write all the rows. foreach (DataRow dr in dv.Table.Rows) { for (int i = 0; i < iColCount; i++) { if (!Convert.IsDBNull(dr[i])) { string fieldname = dv.Table.Columns[i].ToString(); fieldContents = dr[i].ToString(); if (Session["EncryptedFields"] != null) { string encryptedfields = Session["EncryptedFields"].ToString(); string[] fieldListArray = encryptedfields.Split(','); string passPhrase = "whatevesfasdfasdfr23"; // can be any string string initVector = "Qt@&^SDF15F6g7H8"; // must be 16 bytes // Before encrypting data, we will append plain text to a random // salt value, which will be between 4 and 8 bytes long (implicitly // used defaults). RijndaelEnhanced rijndaelKey = new RijndaelEnhanced(passPhrase, initVector); foreach (string strField in fieldListArray) { if (fieldname.Trim() == strField.Trim()) { int index = dr.Table.Columns[strField.Trim()].Ordinal; string currentvalue = dr[index].ToString(); ActivityLogger.WriteAdminEntry(currentCampaign, "ExportDMData - Column and current text: '{0}'", strField + " " + currentvalue); if (currentvalue != " " && currentvalue != "") { fieldContents = rijndaelKey.Decrypt(currentvalue); break; } } } } // Remove commas fieldContents = fieldContents.Replace(",", " "); sw.Write(fieldContents); } if (i < iColCount - 1) { sw.Write(","); } } sw.Write(sw.NewLine); } sw.Close(); if (rdoDelete.Checked) { try { dsExportData.ConnectionString = currentCampaign.CampaignDBConnString; string uniqueKeySelectStmt = string.Format("SELECT UniqueKey FROM Campaign {0}", selectStatement.Substring(selectStatement.IndexOf("WHERE"), (selectStatement.Length - selectStatement.IndexOf("WHERE")))); dsExportData.SelectCommand = uniqueKeySelectStmt; DataView dv1 = new DataView(); dv1 = (DataView)dsExportData.Select(DataSourceSelectArguments.Empty); // Execute WS method to delete everything in the DB List <long> keyList = new List <long>(); foreach (DataRow dr in dv1.Table.Rows) { keyList.Add(Convert.ToInt64(dr[0])); } ActivityLogger.WriteAdminEntry(currentCampaign, "Key List complete, contains {0} keys.", keyList.Count); string deleteStatement = string.Format("DELETE {0}", selectStatement.Substring(selectStatement.IndexOf("FROM"), (selectStatement.Length - selectStatement.IndexOf("FROM")))); dsExportData.SelectCommand = deleteStatement; dv = (DataView)dsExportData.Select(DataSourceSelectArguments.Empty); ActivityLogger.WriteAdminEntry(currentCampaign, "Bulk delete complete."); long totalKeys = keyList.Count; if (keyList.Count > 0) { int chunkSize = 1000; try { chunkSize = Convert.ToInt32(ConfigurationManager.AppSettings["ChunkSize"]); } catch { } CampaignService campService = new CampaignService(); XmlDocument xDocKeysToDelete = new XmlDocument(); campService.Timeout = System.Threading.Timeout.Infinite; while (keyList.Count > 0) { if (keyList.Count < chunkSize) { xDocKeysToDelete.LoadXml(Serialize.SerializeObject(keyList, typeof(List <long>))); campService.DeleteExportedLeads(xDocKeysToDelete, currentCampaign.CampaignDBConnString); keyList.Clear(); } else { List <long> templist = keyList.GetRange(0, chunkSize); keyList.RemoveRange(0, chunkSize); xDocKeysToDelete.LoadXml(Serialize.SerializeObject(templist, typeof(List <long>))); campService.DeleteExportedLeads(xDocKeysToDelete, currentCampaign.CampaignDBConnString); templist.Clear(); } } } hdnDeleteConfirmed.Value = "False"; Session["ViewChanged"] = "yes"; } catch (Exception ex) { ActivityLogger.WriteException(ex, "Admin"); } } // Download file here Response.ContentType = "application/ms-excel"; Response.AddHeader("content-disposition", "attachment; filename=" + exportFileName); Response.TransmitFile(exportFilePath); Response.End(); //file.Delete(); } catch (Exception ex) { PageMessage = "Exception saving view: " + ex.Message; } }
public string Decrypt(string data, string key) { var rij = new RijndaelEnhanced(key); return(rij.Decrypt(data)); }