コード例 #1
0
 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;
     }
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: ut786/EncryptedLegder
        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);
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        public void Decrypt_WhenTextIsValid_ReturnsCorrectDecryptedText()
        {
            // Arrange
            string text = "HZdioE5eNm2hgG98DRBqqA==";
            string correctDecryptedText = "Hello World!";

            // Act
            var result = _sut.Decrypt(text);

            // Assert
            result.Should()
            .Equals(correctDecryptedText);
        }
コード例 #5
0
        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;
            }
        }
コード例 #6
0
        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));
        }
コード例 #7
0
 public DecipherText(CipherText cipherText, string key, ICryptography decryptor)
 {
     CipherText     = cipherText;
     DecipheredText = decryptor.Decrypt(cipherText, key);
     Key            = key;
     Score          = new FrequencyAnalysis(DecipheredText).Score;
 }
コード例 #8
0
        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()));
            }
        }
コード例 #9
0
        public void Decrypt()
        {
            string value = @"12345678";

            string valueEncrypted = _customCrypto.Encrypt(value);
            string valueDecrypted = _customCrypto.Decrypt(valueEncrypted);

            Assert.IsTrue(valueDecrypted.Equals(value));
        }
コード例 #10
0
        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));
        }
コード例 #11
0
ファイル: WebDavManager.cs プロジェクト: pasamsin/SolidCP
        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);
        }
コード例 #12
0
        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);
        }
コード例 #13
0
        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)";
            }
        }
コード例 #14
0
        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));
            }
        }
コード例 #15
0
        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;
                }
            }
        }
コード例 #16
0
        //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!";
            }
        }
コード例 #17
0
ファイル: WSP.cs プロジェクト: vkuttyp/websitepanel
        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);
        }
コード例 #18
0
 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);
 }
コード例 #19
0
 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);
 }
コード例 #20
0
ファイル: HomeController.cs プロジェクト: TechnoHeap/4dscan
        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));
        }
コード例 #21
0
        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);
        }
コード例 #22
0
ファイル: Cryptography.cs プロジェクト: moto2002/Ganga-RTS
 public static string Decrypt(string value, SecurityMode securityMode, string password)
 {
     return(_cryptography.Decrypt(value, securityMode, password));
 }
コード例 #23
0
 public string Decrypt(ICryptography decryptor, string key)
 {
     return(decryptor.Decrypt(this, key));
 }
コード例 #24
0
 public bool VerifyEntry(EncryptedLedgerEntry <TransactioneeId> encryptedLedgerEntry)
 {
     cryptography.Decrypt <TransactioneeId>(encryptedLedgerEntry, out bool result);
     return(result);
 }