public static InstructorValidationData GetVFromByteArray(string encryptedFile, string instructorPassword) { try { var decrypted = AESGCM.SimpleDecryptWithPassword(encryptedFile, instructorPassword); //unzip // var unzippedFile = Framework_Project.Compression.CompressionHelper.Unzip(decrypted); var unzippedFile = decrypted; if (unzippedFile.Substring(0, 3) != "FCT") { throw new InvalidInstructorPasswordException("In GetVFromByteArray"); } unzippedFile = unzippedFile.Substring(3, unzippedFile.Length - 3); try { var exmp = Framework_Project.Serialization.SerializationHelper.Deserialize <InstructorValidationData>(unzippedFile); return(exmp); } catch (Exception ex) { throw new Exception("in GetVFromByteArray, cannot cast the XML to Exam Class. "); } } catch (Exception ex) { MessageBox.Show("L5:::" + ex.ToString()); throw ex; } }
public void DecryptDetails(string examKey) { StudentName = AESGCM.SimpleDecryptWithPassword(StudentName, examKey); StudentID = AESGCM.SimpleDecryptWithPassword(StudentID, examKey); SequenceNumber = AESGCM.SimpleDecryptWithPassword(SequenceNumber, examKey); ExamKey = AESGCM.SimpleDecryptWithPassword(ExamKey, examKey); }
private static void GradeExamQuestion(ref RichTextBox rtb, bool addLogs, string studentPass, string instructorPassword, Exam anExam) { var id = AESGCM.SimpleDecryptWithPassword(anExam.RequiredStudentDetails.StudentID, studentPass); var name = AESGCM.SimpleDecryptWithPassword(anExam.RequiredStudentDetails.StudentName, studentPass); rtb.AppendText($"{anExam.ExamDescription}\n", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold)); rtb.AppendText($"Student Name: {name}\n", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold)); rtb.AppendText($"Student ID: {id}\n", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold)); rtb.AppendText($"Grade: {anExam.GetExamGrade(instructorPassword)}\n", new System.Drawing.Font("Courier New", 18, System.Drawing.FontStyle.Underline)); // rtb.AppendText($"Exam Sent to Student Date and Comment:{list[i].weSentHimExamDateAndDetails}", new System.Drawing.Font("Courier New", 12, System.Drawing.FontStyle.Italic)); // rtb.AppendText($"Student Exam Submission Date And Comment:{list[i].weSentHimExamDateAndDetails}", new System.Drawing.Font("Courier New", 12, System.Drawing.FontStyle.Italic)); foreach (var q in anExam.QuestionsList) { QuizHelper.AddGradedQuestionToRtb(ref rtb, q.QuestionNumber, q, instructorPassword, true, true); } if (addLogs) { rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"***** Student Exam Logs *****\n", new System.Drawing.Font("Courier New", 18, System.Drawing.FontStyle.Italic)); foreach (var s in anExam?.ExamLog) { rtb.AppendText($"{s}\n", new System.Drawing.Font("Courier New", 8, System.Drawing.FontStyle.Regular)); } } rtb.AppendText($"***** END OF STUDENT {name} EXAM *****\n", new System.Drawing.Font("Courier New", 18, System.Drawing.FontStyle.Italic)); rtb.AddNewPage(); }
public void DecryptSharedKey(string sharedKeyIS) { if (SharedKeyIS != "" && sharedKeyIS != "" && SharedKeyIS != null && sharedKeyIS != null) { SharedKeyIS = AESGCM.SimpleDecryptWithPassword(SharedKeyIS, sharedKeyIS); } }
public void Get(string paramOne) { if (paramOne.ToLower() == "reset") { Log.Append("GET - Reset Email Sync Parameters"); Global.isSyncing = false; Readiness.DeleteBlockerFile(); } //if (!Permissions.ValidAPIKey(APIKey)) return new Email[] {}; paramOne = AESGCM.SimpleDecryptWithPassword(paramOne.Replace("_", "/").Replace("-", "+"), AESGCM.AES256Key); if (paramOne.ToLower() == "sync") { Log.Append("GET - Sync PST Files"); PSTImporter.SyncPSTFiles(); } if (paramOne.ToLower() == "validate") { Log.Append("GET - Validating email and file integrity"); Task.Run(() => Global.ValidateMessages()); } if (paramOne.ToLower() == "refresh") { Log.Append("GET - Refresh Email List requested"); // Reload settings before getting emails Global.LoadSettings(); EmailRepository.CacheInfo(Global.GetAllEmails().ToArray()); } //return new Email[] { }; }
public static void AddGradedQuestionToRtb(ref RichTextBox rtb, int counter, Question aQuestion, string instructorPassword, bool addAnswer = true, bool addExplanation = true) { bool correctAnswer = false; int padright = 30; // rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"Question. {counter} [{aQuestion.Grades} " + ((aQuestion.Grades == 1) ? "Point" : "Points") + $"]:", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold)); if (aQuestion.StudentAnsweredCorrectly(instructorPassword)) { correctAnswer = true; rtb.AppendText($"(Correct)", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold), Color.Green); } else { rtb.AppendText($"(Wrong)", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold), Color.Red); } rtb.AppendText(System.Environment.NewLine); rtb.AppendText(aQuestion.ToString(), new System.Drawing.Font("Courier New", 12, FontStyle.Bold)); rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"{aQuestion.QuestionAltenativesDescription}".PadRight(padright)); var cA = AESGCM.SimpleDecryptWithPassword(aQuestion.Answer, instructorPassword); var studentAns = ""; if (aQuestion.GetType() == typeof(TrueFalseQuestion)) { int option = ((TrueFalseQuestion)aQuestion).RandomChoice; var correctAnsTrueFalse = (aQuestion.Choices[option] != cA).ToString(); studentAns = (aQuestion.StudentAnswer == correctAnsTrueFalse).ToString(); rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"[Student Answer:] {studentAns} ", new System.Drawing.Font("Courier New", 12, FontStyle.Bold), (correctAnswer ? Color.Green : Color.Red)); } else { rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"[Student Answer:] {aQuestion.StudentAnswer} ", new System.Drawing.Font("Courier New", 12, FontStyle.Bold), (correctAnswer ? Color.Green : Color.Red)); } if (addAnswer && !correctAnswer) { rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"[Correct Answer:] {AESGCM.SimpleDecryptWithPassword(aQuestion.Answer,instructorPassword)} ", System.Drawing.Color.Green); } if (addExplanation && !correctAnswer) { rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"[Explanation:] {AESGCM.SimpleDecryptWithPassword(aQuestion.AnswerExplanation, instructorPassword)}", Color.Green); } rtb.AppendText(System.Environment.NewLine); }
public IActionResult GetLogs(string routineIdE, string entityIdE) { var entityId = Convert.ToInt32(AESGCM.SimpleDecryptWithPassword(entityIdE, AppConfiguration.EncryptionSalt)); var routineId = Convert.ToInt32(AESGCM.SimpleDecryptWithPassword(routineIdE, AppConfiguration.EncryptionSalt)); var model = _routine2Repository.GetLogs(routineId, entityId); ViewBag.RoutineId = routineId; return(View(model)); }
/// <summary> /// Load the current sync file if available /// </summary> public static void ReadShoppingSyncFile() { string syncText = ""; string emailAddress = GetSettingsValue("SYNC_EMAIL"); Debug.WriteLine("Reading Cloud Shopping file...."); try { if (Debugger.IsAttached || Global.isOnWifi()) // only try on WiFi (most data will block this) { Debug.WriteLine("WIFI DETECTED!"); List <string> lines = new List <string>(); // Copy local repository to FTP Server if (Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.iOS) { // Read from FTP File //string[] lines = GetFileContent(emailAddress + SyncFileName) lines = AESGCM .SimpleDecryptWithPassword( DependencyService.Get <IFtpWebRequest>().FTPRead(emailAddress + ShoppingListFileName), AESGCMKey) .Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); } // Only load orders foreach (string line in lines) { Debug.WriteLine("line: " + line); // if is already synced, append "[ISSYNCED]=1" if contains this in sync file (the desktop application will append this AFTER it syncs) if (line.Length > 5 && line.Contains("[SI_NA_]=")) { string name = Parse_Line_Information(line, "SI_NA_"); string category = Parse_Line_Information(line, "SI_CA_"); if (!ShoppingList.Any(x => x.Name == name && x.Category == category)) // only add items that are not already there { ShoppingList.Add(new ShopItem(name, category)); } } } } } catch (Exception Ex) { Debug.WriteLine("No file found: " + Ex); } Debug.WriteLine("Done reading...."); }
public static void LoadSettings() { if (!File.Exists(settingsFilePath)) { return; } var text = File.ReadAllText(settingsFilePath); string[] lines = AESGCM.SimpleDecryptWithPassword(text, AESGCM.AES256Key).Split(new[] { Environment.NewLine }, StringSplitOptions.None); // Initialize settings dictionary Settings.SettingsDictionary = new Dictionary <string, string>(); UserList = new List <User>(); // Load user information foreach (string line in lines) { if (line.Contains("[US_NA_]=")) { User user = new User() { Name = Parser.Parse(line, "US_NA_"), Department = Permissions.GetGroup(Parser.Parse(line, "US_DE_")), UserID = Parser.Parse(line, "US_ID_"), LoginPassword = Parser.Parse(line, "US_LP_"), SyncEmails = Parser.Parse(line, "US_SE_") == "1", Privilege = Parser.Parse(line, "US_PR_"), LastUpdateTime = Convert.ToDateTime(Parser.Parse(line, "US_LU_")), ReceivingProtocol = Parser.Parse(line, "US_PT_"), ReceivingPort = Parser.Parse(line, "US_PO_"), Email = Parser.Parse(line, "US_EM_"), Password = Parser.Parse(line, "US_PW_"), InternalID = UserList.Count == 0 ? 0 : UserList.Max(x => x.InternalID) + 1 }; UserList.Add(user); } else if (line.StartsWith("#SETVAL||[ST_NAME_]=")) { Settings.LoadSettingsStr(line); } } SaveSettings(); }
/// <summary> /// read files and sets fileText to file content /// </summary> /// <param name="fileName"></param> public static async void ReadFileContent(string fileName) { string filePath = Path.Combine(_fileSystem.LocalStorage.Path, fileName); //IFile file = await rootFolder.GetFileAsync(filePath).ConfigureAwait(false); // fileText = await file.ReadAllTextAsync(); try { IFile file = rootFolder.GetFileAsync(filePath).Result; fileText = AESGCM.SimpleDecryptWithPassword(file.ReadAllTextAsync().Result, AESGCMKey); //decrypt } catch (Exception e) { Debug.WriteLine(e.ToString()); } }
/// <summary> /// Load the current sync file if available /// </summary> public static async Task <bool> LoadSyncFile() { string syncText = ""; string emailAddress = GetSettingsValue("SYNC_EMAIL"); try { if (Global.isOnWifi()) // only try on WiFi (most data will block this) { if (Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.iOS) { // Copy local repository to FTP Server // Read from FTP File //string[] lines = GetFileContent(emailAddress + SyncFileName) Task <string> ftpLine = Task.Run(() => DependencyService.Get <IFtpWebRequest>() .FTPRead(emailAddress + SyncFileName)); List <string> lines = AESGCM.SimpleDecryptWithPassword(await ftpLine, AESGCMKey).Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); // Only load orders foreach (string line in lines) { // if is already synced, append "[ISSYNCED]=1" if contains this in sync file (the desktop application will append this AFTER it syncs) if (line.Length > 5 && line.Contains("[OR_LO_]=")) { SyncList.Add(Parse_Line_Information(line, "OR_ID_") + (line.Contains("[OR_SY_]=1") ? "[OR_SY_]=1" : "")); // append only order id to list } } // Remove duplication SyncList.Distinct(); } } } catch (Exception Ex) { Debug.WriteLine("No file found: " + Ex); } return(true); //complete }
public virtual bool StudentAnsweredCorrectly(string intructorPassword) { var correctAnswer = AESGCM.SimpleDecryptWithPassword(Answer, intructorPassword); if (this.GetType() == typeof(TrueFalseQuestion)) { int option = ((TrueFalseQuestion)this).RandomChoice; if (Choices[option] == correctAnswer) { return(StudentAnswer == true.ToString()); } else { return(StudentAnswer == false.ToString()); } } // else if (this.GetType() == typeof(MultipleChoiceQuestion)) { return(correctAnswer == StudentAnswer); } }
public static Exam GetExamFromByteArray(string encryptedFile, string examKey, string sharedKeyIS, FilterationSecurityLevel secLevel) { string decrypted; if (secLevel == FilterationSecurityLevel.Moderate) { decrypted = AESGCM.SimpleDecryptWithPassword(encryptedFile, examKey); } else { decrypted = AESGCM.SimpleDecryptWithPassword(encryptedFile, sharedKeyIS); } //unzip if (decrypted == null) { int x = 10; } var unzippedFile = Framework_Project.Compression.CompressionHelper.Unzip(decrypted); if (unzippedFile.Substring(0, 3) != "FCT") { throw new InvalidStudentPasswordException("In GetExamFromFile"); } unzippedFile = unzippedFile.Substring(3, unzippedFile.Length - 3); try { var exmp = Framework_Project.Serialization.SerializationHelper.Deserialize <Exam>(unzippedFile); return(exmp); } catch (Exception ex) { throw new Exception("in GetExamFromFile, cannot cast the XML to Exam Class. "); } }
public static string Decrypt(string content, SecureString password) { return(AESGCM.SimpleDecryptWithPassword(content, ConvertToUnSecureString(password))); }
private static void TestLibraries(bool testCompression = true, bool testEncryption = true) { var myOrgMsg = "123456"; var encryptedx = AESGCM.SimpleEncryptWithPassword(myOrgMsg, "123456"); var decryptedx = AESGCM.SimpleDecryptWithPassword(encryptedx, "1234567"); try { Parallel.For(0, 1000000, i => { var v = new InstructorValidationData($"Std{i}", DateTime.Now, 10, 11); var serialized = SerializationHelper.Serialize <InstructorValidationData>(v); if (serialized == null) { throw new Exception("serialized==null"); } string compressedString = Framework_Project.Compression.CompressionHelper.Zip(serialized); if (compressedString == null) { throw new Exception("compressed==null"); } // string decompressed = Framework_Project.Compression.CompressionHelper.Unzip(compressedString); string encrypted = AESGCM.SimpleEncryptWithPassword(compressedString, $"Keyyy{i}"); if (encrypted == null) { throw new Exception("encrypted==null"); } string decrypted = AESGCM.SimpleDecryptWithPassword(encrypted, $"Keyyy{i}"); if (decrypted == null) { throw new Exception("decrypted==null"); } if (decrypted != compressedString) { throw new Exception("decrypted!=compressedString"); } if (!StructuralComparisons.StructuralEqualityComparer.Equals(decrypted, compressedString)) { throw new Exception("decryptedBytes!=compressed"); } string decompressed = Framework_Project.Compression.CompressionHelper.Unzip(decrypted); if (decompressed == null) { throw new Exception("decompressed==null"); } if (decompressed != serialized) { throw new Exception("decompressed != serialized"); } var deserialized = SerializationHelper.Deserialize <InstructorValidationData>(serialized); }); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Takes the given encrypted text and decrypts it /// using the given password. /// </summary> /// <param name="encryptedText">Encrypted text.</param> /// <param name="encryptionPassword">Encryption password.</param> /// <returns>The decrypted text.</returns> public static string Decrypt( string encryptedText, string encryptionPassword) { return(AESGCM.SimpleDecryptWithPassword( encryptedText, encryptionPassword)); }
public static void ImportEmailFile() { Log.Append("Application initialized"); TimeSpan startTime = DateTime.Now.TimeOfDay; Log.Append("Caching email list..."); try { string[] emailFiles = Directory.GetFiles(cacheDirectoryPath, "*.cfg*"); if (emailFiles.Length <= 0) { RegenerateCacheFile(); } foreach (string filePath in emailFiles) { var text = File.ReadAllText(filePath); string[] lines = AESGCM.SimpleDecryptWithPassword(text, AESGCM.AES256Key) .Split(new[] { Environment.NewLine }, StringSplitOptions.None); // Load email information foreach (string line in lines) { if (line.Contains("[EM_ID_]=")) { Email email = new Email() { ID = Parser.Parse(line, "EM_ID_"), UID = Parser.Parse(line, "EM_UI_"), To = Parser.Parse(line, "EM_TO_"), From = Parser.Parse(line, "EM_FR_"), Subject = Parser.Parse(line, "EM_SU_"), EmailMessage = "", // prevent nullification MailDate = Convert.ToDateTime(Parser.Parse(line, "EM_MD_")) }; // For testing, local does not read emails //email.RetrieveMsg(); EmailList.Add(email); email.MapNameFromEmail(); } } } } catch (Exception e) { RegenerateCacheFile(); } // Retrieve all messages in background Task.Run(() => ReadAllEmailMessages()); // Sort by date EmailList = EmailList.OrderByDescending(x => x.MailDate).ToList(); Log.Append(String.Format("Cached {1} emails! Process took {0}", Arithmetic.GetStopWatchStr((DateTime.Now.TimeOfDay - startTime).TotalMilliseconds), EmailList.Count)); GetEmailCounts(); }
//=========================== SYNC SYSTEM ============================= /// <summary> /// Upload entire information item/order list from FTP/Cloud_Sync/FullSync directory /// </summary> public static void DownloadAllInformation() { string syncText = ""; string emailAddress = GetSettingsValue("SYNC_EMAIL"); try { if (Global.isOnWifi()) // only try on WiFi (most data will block this) { List <string> lines = new List <string>(); // Copy local repository to FTP Server if (Device.OS == TargetPlatform.Android || Device.OS == TargetPlatform.iOS) { // Read from FTP File //string[] lines = GetFileContent(emailAddress + SyncFileName) lines = AESGCM .SimpleDecryptWithPassword( DependencyService.Get <IFtpWebRequest>().FTPRead(emailAddress + FullSyncFileName), AESGCMKey) .Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); } // Load items and orders from downloaded file foreach (string line in lines) { // Load items if (line.Contains("||[IT_LO]=")) { Item New_Item = new Item(); New_Item.Name = Parse_Line_Information(line, "IT_DE_"); New_Item.Status = Parse_Line_Information(line, "IT_ST_") == "" ? "0" : Parse_Line_Information(line, "IT_ST_"); New_Item.RefundAlert = Parse_Line_Information(line, "IT_RE_") == "1" ? true : false; New_Item.consumedStatus = Convert.ToInt32(Parse_Line_Information(line, "IT_CO_", "||", "2")); New_Item.Location = Parse_Line_Information(line, "IT_LO"); New_Item.Payment_Type = Parse_Line_Information(line, "IT_PA_"); New_Item.Category = Parse_Line_Information(line, "IT_CA_"); New_Item.Discount_Amt = Convert.ToDouble(Parse_Line_Information(line, "IT_DI_", "||", "0")); New_Item.Price = Convert.ToDouble(Parse_Line_Information(line, "IT_PR_")); New_Item.Quantity = Convert.ToInt32(Parse_Line_Information(line, "IT_QU_")); New_Item.Date = Convert.ToDateTime(Parse_Line_Information(line, "IT_DA_")); New_Item.Refund_Date = Parse_Line_Information(line, "IT_RD_").Length > 0 ? Convert.ToDateTime(Parse_Line_Information(line, "IT_RD_")) : DateTime.Now; New_Item.Memo = Parse_Line_Information(line, "IT_ME_"); New_Item.OrderID = Parse_Line_Information(line, "IT_ID_"); GlobalItemList.Add(New_Item); } // Load orders else if (line.Contains("||[OR_QU_]=")) { Order New_Order = new Order(); New_Order.Location = Parse_Line_Information(line, "OR_LO_"); New_Order.OrderMemo = Parse_Line_Information(line, "OR_ME_"); New_Order.Payment = Parse_Line_Information(line, "OR_PA_"); New_Order.Tax_Overridden = (Parse_Line_Information(line, "OR_TO_") == "1"); New_Order.Order_Total_Pre_Tax = Convert.ToDouble(Parse_Line_Information(line, "OR_PP_")); New_Order.GC_Amount = Convert.ToDouble(Parse_Line_Information(line, "OR_GC_", "||", "0")); New_Order.Order_Taxes = Convert.ToDouble(Parse_Line_Information(line, "OR_TA_")); New_Order.Order_Discount_Amt = Convert.ToDouble(Parse_Line_Information(line, "OR_DI_", "||", "0")); New_Order.Order_Quantity = Convert.ToInt32(Parse_Line_Information(line, "OR_QU_")); New_Order.Date = Convert.ToDateTime(Parse_Line_Information(line, "OR_DA_")); New_Order.OrderID = Parse_Line_Information(line, "OR_ID_"); GlobalOrderList.Add(New_Order); } } foreach (Item item in GlobalItemList) { Debug.WriteLine(item.ToString()); } } } catch (Exception Ex) { Debug.WriteLine("No file found: " + Ex); } }