private void CreatePaymentDataModel(ref PaymentData paymentData, string fieldName, string value, bool isEncrypted) { if (fieldName == ValidationConsts.Instance.CardNumber) { paymentData.CardNumber = isEncrypted ? cryptography.Decrypt(value) : value; } if (fieldName == ValidationConsts.Instance.Name) { paymentData.Name = value; } if (fieldName == ValidationConsts.Instance.Amount) { paymentData.Amount = Convert.ToDecimal(value); } if (fieldName == ValidationConsts.Instance.Expiry) { paymentData.Expiry = value; } if (fieldName == ValidationConsts.Instance.Currency) { paymentData.Currency = value; } if (fieldName == ValidationConsts.Instance.Security) { paymentData.Security = isEncrypted ? cryptography.Decrypt(value) : value; } }
public List <LedgerEntry <int> > ExecuteQuery(ILedgerQuery query, out bool isVerified) { isVerified = false; var result = DbContext.Table.FromSqlRaw(query.GetCommand()).ToList(); List <LedgerEntry <int> > ledgerEntries = new List <LedgerEntry <int> >(); foreach (var item in result) { ledgerEntries.Add(cryptography.Decrypt(Map(item), out isVerified)); } return(ledgerEntries); }
public void Decrypt_WhenTextIsCorrect_ReturnsCorrectDecryptedText() { // Arrange string text = @"Mjqqt \twqi&"; string correctDecryptedText = "Hello World!"; // Act var result = _sut.Decrypt(text); // Assert result.Should() .Equals(correctDecryptedText); }
public void Decrypt_WhenTextIsValid_ReturnsCorrectDecryptedText() { // Arrange string text = "HZdioE5eNm2hgG98DRBqqA=="; string correctDecryptedText = "Hello World!"; // Act var result = _sut.Decrypt(text); // Assert result.Should() .Equals(correctDecryptedText); }
public bool IsChangePasswordTokenValid(string token, string usernameOrEmail) { try { string plain = DesCryptography.Decrypt(token); string[] flats = plain.Split('#'); string changePasswordToken = flats[0]; double timeout = double.Parse(flats[1]); DateTime oDate = DateTime.Parse(flats[2]); if (changePasswordToken != usernameOrEmail) { return(false); } DateTime datetimeout = oDate.AddMinutes(timeout); if (datetimeout.CompareTo(DateTime.Now) < 0) { return(false); } return(true); } catch (CryptographicException ex) { _logger.LogCritical(ex, ex.Message); throw ex; } }
public async Task <IActionResult> Index([FromQuery] int page, [FromQuery] string sortColumn, [FromQuery] int sortType, [FromQuery] string search) { if (page == 0) { page = 1; } search = search == null ? string.Empty : HttpUtility.UrlDecode(search).Trim(); if (string.IsNullOrEmpty(sortColumn)) { sortColumn = "date"; } if (sortType == 0) { sortType = 2; } ViewBag.PageSize = 10; ViewBag.SortColumn = sortColumn; ViewBag.Search = search; ViewBag.SortType = sortType; ViewBag.CurrentPage = page; (int totalRows, IList <ScanCenterProfileModel> list) = await _scanCenterProfileQuery.GetAllProfiles(page, (int)ViewBag.PageSize, search, sortColumn, sortType); list.ToList().ForEach(f => f.Password = _cryptography.Decrypt(f.Password, _appSettings).ConfigureAwait(false).GetAwaiter().GetResult()); return(View(list)); }
public DecipherText(CipherText cipherText, string key, ICryptography decryptor) { CipherText = cipherText; DecipheredText = decryptor.Decrypt(cipherText, key); Key = key; Score = new FrequencyAnalysis(DecipheredText).Score; }
public async Task <ActionResult> RegistrationCodeConfirmation([FromQuery] string id) { string registrationToken = _cryptography.Decrypt(id); try { if (!registrationToken.IsSet()) { return(BadRequest("Code is missing!")); } int? userId; string registrationCode; try { List <string> codeKeys = registrationToken.Split("#").ToList(); codeKeys.RemoveAll(x => !x.IsSet()); userId = codeKeys.Count != 0 ? int.Parse(codeKeys.FirstOrDefault()) : throw new ArgumentNullException(); registrationCode = codeKeys.LastOrDefault(); } catch { return(BadRequest("Invalid link!")); } User user = await UnitOfWork.UserRepository.GetByIdAsync(userId.GetValueOrDefault()); if (!user.RegistrationCode.Equals(registrationCode)) { return(BadRequest("Invalid registration code!")); } await UnitOfWork.ExecuteTransactionAsync(async (transaction, timeout) => { user.RegistrationConfirmed = true; UnitOfWork.UserRepository.Update(user); Inbox inbox = new Inbox { Name = "Personal", Active = true, AdminId = user.Id }; UnitOfWork.InboxRepository.Add(inbox); await UnitOfWork.SaveChangesAsync(); }, null, null); return(Ok()); } catch (Exception ex) { return(InternalServerError(ex.InnerExceptionMessage())); } }
public void Decrypt() { string value = @"12345678"; string valueEncrypted = _customCrypto.Encrypt(value); string valueDecrypted = _customCrypto.Decrypt(valueEncrypted); Assert.IsTrue(valueDecrypted.Equals(value)); }
public Task Receive(string message) { logger.LogInformation("Decrypting message"); var messageDecrypted = cryptography.Decrypt(message); logger.LogInformation("Deserializing message"); var value = serializer.Deserialize <T>(messageDecrypted); logger.LogInformation("Executing callback"); return(consumer.Consume(value)); }
public IEnumerable <IHierarchyItem> OpenFolder(string pathPart) { IHierarchyItem[] children; if (string.IsNullOrWhiteSpace(pathPart)) { children = ConnectToWebDavServer().Select(x => new WebDavResource { Href = new Uri(x.Url), ItemType = ItemType.Folder, ContentLength = x.Size * 1024 * 1024, AllocatedSpace = (long)x.FRSMQuotaMB * 1024 * 1024, IsRootItem = true }).ToArray(); } else { if (_currentFolder == null || _currentFolder.Path.ToString() != pathPart) { _webDavSession.Credentials = new NetworkCredential(ScpContext.User.Login, _cryptography.Decrypt(ScpContext.User.EncryptedPassword), WebDavAppConfigManager.Instance.UserDomain); _currentFolder = _webDavSession.OpenFolder(string.Format("{0}{1}/{2}", WebDavAppConfigManager.Instance.WebdavRoot, ScpContext.User.OrganizationId, pathPart.TrimStart('/'))); } children = FilterResult(_currentFolder.GetChildren()).ToArray(); } List <IHierarchyItem> sortedChildren = children.Where(x => x.ItemType == ItemType.Folder).OrderBy(x => x.DisplayName).ToList(); sortedChildren.AddRange(children.Where(x => x.ItemType != ItemType.Folder).OrderBy(x => x.DisplayName)); return(sortedChildren); }
public async Task <IEnumerable <MessageViewModel> > MessageHistory([FromBody] string destinataryId) { var auth0Id = _helper.GetCurrentUserProfile(User); var messages = await _profileRepository.GetMessages(auth0Id, destinataryId); foreach (var message in messages) { message.Message = _cryptography.Decrypt(message.Message); } return(messages); }
public void Validate(string dataToValidate, bool isEncrypted, ICryptography cryptography, out string errorMessage) { var dtaToValidate = dataToValidate; if (isEncrypted) { dtaToValidate = cryptography.Decrypt(dataToValidate); } errorMessage = string.Empty; if (!dtaToValidate.All(char.IsDigit) || dtaToValidate.Trim().Length != 3) { errorMessage = "Security (CVV) is not valid! (3 digits)"; } }
public async Task <IActionResult> ChangePassword([FromBody] ChangePasswordModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Select(x => x.Value).ToList())); } var email = HttpContext.GetEmail(); var appUser = await userManager.FindByEmailAsync(email); var result = await userManager.ChangePasswordAsync(appUser, cryptography.Decrypt(model.CurrentPassword), cryptography.Decrypt(model.NewPassword)); if (result.Succeeded) { return(Ok()); } else { return(BadRequest(result.Errors)); } }
public async Task <IActionResult> Register([FromBody] UserModel userModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Select(x => x.Value))); } using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { try { var password = cryptography.Decrypt(userModel.Password); var user = new IdentityUser { Email = userModel.Email, UserName = userModel.Email }; var result = await userManager.CreateAsync(user, password); if (result.Succeeded) { var roles = roleManager.Roles.ToList(); var role = roles.First(x => x.Name.Equals("RegularUser")); await userManager.AddToRoleAsync(user, role.Name); queueService.SendMessage(new RegistrationMessage { Email = userModel.Email, Language = userModel.Language.IsEmpty() ? GetBrowserLanguage() : userModel.Language }); scope.Complete(); return(Ok()); } else { scope.Dispose(); return(BadRequest(result.Errors)); } } catch (System.Exception ex) { scope.Dispose(); throw ex; } } }
//This is not a proper data validation and this should be improved. If we use data annotaion, we can use its built in attribute //to validate a payment card number public void Validate(string dataToValidate, bool isEncrypted, ICryptography cryptography, out string errorMessage) { var dtaToValidate = dataToValidate; if (isEncrypted) { dtaToValidate = cryptography.Decrypt(dataToValidate); } errorMessage = string.Empty; //Replace all white space var dta = Regex.Replace(dtaToValidate, @"\s+", ""); if (dta.Length > 16 || dta.Length < 13 || !dta.All(char.IsDigit) || dta.Trim() == string.Empty) { errorMessage = "Credit card number is invalid!"; } }
public void ConfigureEnterpriseServerProxy(WebServicesClientProtocol proxy, bool applyPolicy) { // load ES properties string serverUrl = WebDavAppConfigManager.Instance.EnterpriseServerUrl; EnterpriseServerProxyConfigurator cnfg = new EnterpriseServerProxyConfigurator(); cnfg.EnterpriseServerUrl = serverUrl; // create assertion if (applyPolicy) { cnfg.Username = WebDavAppConfigManager.Instance.WebsitePanelConstantUserParameters.Login; cnfg.Password = _cryptography.Decrypt(WebDavAppConfigManager.Instance.WebsitePanelConstantUserParameters.Password); } cnfg.Configure(proxy); }
public override Document Rethink(Document document) { if (!string.IsNullOrEmpty(document?.Content)) { if (document.IsProtected) { var documentCryptography = _cryptographyRepository.GetByDocumentId(document.Id); var decrypted = _cryptography.Decrypt(new EncryptedData { CipherText = Convert.FromBase64String(document.Content), Iv = documentCryptography.Iv }, _configuration); document.Content = decrypted; } } if (_successor != null) { return(_successor.Rethink(document)); } return(document); }
public static byte[] Decrypt(short protocal, byte[] oldBytes, string key) { byte[] newBytes = null; // 解密 if (protocal == Protocal.ContractTypes.ResultLogin)//AES { ICryptography item = GetService(ServiceType.AES, aes); if (item != null) { newBytes = item.Decrypt(oldBytes); } else { newBytes = oldBytes; Debug.LogError("Encryption failed! With no encryption to send!"); } } else { if (key == null || key.Equals("")) { newBytes = oldBytes; Debug.LogError("key == null or key == ''"); } else { ICryptography item = GetService(ServiceType.DES, key); if (item != null) { newBytes = item.Decrypt(oldBytes); } else { newBytes = oldBytes; Debug.LogError("Encryption failed! With no encryption to send!"); } } } return(newBytes); }
public async Task <IActionResult> Index(string name, [FromQuery] string refer) { var profile = await _scanCenterProfileQuery.GetByUniqueName(name); ViewData["ProfileId"] = 0; if (profile != null) { var fields = await _scanCenterCustomFieldQuery.GetAllFields(profile.Id); ViewData["UniqueName"] = profile.UniqueName; ViewData["ProfileId"] = profile.Id; int appid = 0; if (!string.IsNullOrEmpty(refer)) { try { refer = HttpUtility.UrlDecode(refer).Replace(" ", "+"); appid = int.Parse(await _cryptography.Decrypt(refer, _appSettings)); } catch { } } ClientMotherModel appointment = await _scanCenterAppointmentQuery.GetById(appid); var list = await _scanCenterProductQuery.GetByScanCenterId(profile.Id); string[] allCat = list.Select(s => s.Category).Distinct().ToArray(); var tupleModel = new Tuple <ScanCenterProfileModel, IList <ScanCenterCustomFieldModel>, string[], ClientMotherModel>(profile, fields, allCat, appointment); return(View(tupleModel)); } var tupleModel1 = new Tuple <ScanCenterProfileModel, IList <ScanCenterCustomFieldModel>, string[], ClientMotherModel>(profile, null, null, null); return(View(tupleModel1)); }
public bool Decrypt(string password, string inputFile, string outFilePath) { try { var encryptionKey = cryptography.HashPassword(password); var fileContent = fileSystem.File.ReadAllBytes(inputFile); var decryptedContent = cryptography.Decrypt(encryptionKey, fileContent); int fileNameSize = BitConverter.ToInt32(decryptedContent, 0); string filename = Encoding.ASCII.GetString(decryptedContent, sizeof(int), fileNameSize); byte[] content = new byte[decryptedContent.Length - fileNameSize - sizeof(int)]; Array.Copy(decryptedContent, fileNameSize + sizeof(int), content, 0, content.Length); if (!fileSystem.Directory.Exists(outFilePath)) { fileSystem.Directory.CreateDirectory(outFilePath); } fileSystem.File.WriteAllBytes(fileSystem.Path.Combine(outFilePath, filename), content); } catch (Exception e) { Console.Write($"Failed to decrypt file {inputFile}. " + e); return(false); } return(true); }
public static string Decrypt(string value, SecurityMode securityMode, string password) { return(_cryptography.Decrypt(value, securityMode, password)); }
public string Decrypt(ICryptography decryptor, string key) { return(decryptor.Decrypt(this, key)); }
public bool VerifyEntry(EncryptedLedgerEntry <TransactioneeId> encryptedLedgerEntry) { cryptography.Decrypt <TransactioneeId>(encryptedLedgerEntry, out bool result); return(result); }