Ejemplo n.º 1
0
        public async Task <IActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await db.Users.FirstOrDefaultAsync(u => u.Email == model.Email);

                if (user == null)
                {
                    // добавляем пользователя в бд
                    User         newUser      = new User(model.NameAndSurname, model.Email, model.Password);
                    byte[]       result       = EncryptStringToBytes_Aes(newUser.Email, AesService.getInstance().Aes.Key, AesService.getInstance().Aes.IV);
                    EmailService emailService = new EmailService();
                    string       res          = DecryptStringFromBytes_Aes(result, AesService.getInstance().Aes.Key, AesService.getInstance().Aes.IV);
                    string       email        = $"<html>\n<body>\n<a href=\"{HttpContext.Request.Scheme + "://" + HttpContext.Request.Host + "/Account/Verification?email=" + Convert.ToBase64String(result)/*newUser.Email*/}\"" +
                                                $">{HttpContext.Request.Scheme + "://" + HttpContext.Request.Host + "/Account/Verification?email=" +Convert.ToBase64String(result)/*newUser.Email*/}</a>\n</body>\n</html>";
                    await emailService.SendEmailAsync(newUser.Email, "Регистрация", email);

                    db.Users.Add(newUser);
                    await db.SaveChangesAsync();

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Некорректные логин и(или) пароль");
                }
            }
            return(View(model));
        }
Ejemplo n.º 2
0
        public void DigitalSignatureTest()
        {
            var aesService = new AesService();

            (byte[] aesKey, byte[] aesIv) = aesService.CreateKey();

            const string messageData = "this is a test message";

            var messageBytes = Encoding.UTF8.GetBytes(messageData);
            var sender       = RsaService.Create();
            var receiver     = RsaService.Create();
            var hasher       = new Sha256BitHasher();


            var hashedMessageBytes = hasher.CreateHash(messageBytes);

            var digitalSignature = sender.EncryptPrivate(hashedMessageBytes);
            var cryptoBytes      = aesService.Encrypt(messageBytes, aesKey, aesIv);

            var hashMessageBytesFromSignature = receiver.DecryptPublic(digitalSignature, sender.PublicKey);
            var plainMessageBytes             = aesService.Decrypt(cryptoBytes, aesKey, aesIv);
            var hashedPlainMessageBytes       = hasher.CreateHash(plainMessageBytes);

            Assert.IsTrue(hashMessageBytesFromSignature.SequenceEqual(hashedPlainMessageBytes));
        }
Ejemplo n.º 3
0
        public void ToUserToDbDtov2_Test()
        {
            var user = new User
            {
                Id        = 1,
                FirstName = "John",
                LastName  = "Wick",
                Email     = "*****@*****.**",
                Password  = SecurePasswordHasher.Hash("Moynahan"),
                Token     = "very strong token",
                Role      = UserRole.MANAGER
            };

            var userToDbDto = user.ToUserToDbDto();

            Assert.Equal(user.Id, userToDbDto.Id);
            Assert.Equal(user.FirstName, AesService.DecryptStringFromBytes_Aes(userToDbDto.FirstName));
            Assert.Equal(user.LastName, AesService.DecryptStringFromBytes_Aes(userToDbDto.LastName));
            Assert.Equal(user.Email, AesService.DecryptStringFromBytes_Aes(userToDbDto.Email));
            Assert.Equal(user.Password, AesService.DecryptStringFromBytes_Aes(userToDbDto.Password));
            if (user.Token != null)
            {
                Assert.Equal(user.Token, AesService.DecryptStringFromBytes_Aes(userToDbDto.Token));
            }
            Assert.Equal(user.Role, userToDbDto.Role);
        }
Ejemplo n.º 4
0
        public void KeyDeliveryTest()
        {
            //const string plainText = "this is the test plain data";
            var aesService = new AesService();

            (byte[] aesKey, byte[] aesIv) = aesService.CreateKey();
            var combinedBytes = aesKey.Concat(aesIv).ToArray();
            var client        = RsaService.Create();
            var server        = RsaService.Create();

            //send client aes encryption data from client to server
            var cryptoBytes           = client.Encrypt(combinedBytes, server.PublicKey);
            var receivedClientAesData = server.Decrypt(cryptoBytes);
            var receivedClientAesKey  = receivedClientAesData.Take(32).ToArray();
            var receivedClientAesIv   = receivedClientAesData.Reverse().Take(16).Reverse().ToArray();

            Assert.IsTrue(aesKey.SequenceEqual(receivedClientAesKey));
            Assert.IsTrue(aesIv.SequenceEqual(receivedClientAesIv));

            //send client aes encrypted message using received key and iv
            const string responseToClientMessage          = "I got your key thanks";
            var          responseToClientBytes            = Encoding.UTF8.GetBytes(responseToClientMessage);
            var          responseToClientBytesCryptoBytes = aesService.Encrypt(responseToClientBytes, receivedClientAesKey, receivedClientAesIv);

            //client decrypts server's response message
            var messageToClientBytes = aesService.Decrypt(responseToClientBytesCryptoBytes, aesKey, aesIv);
            var messageToClientText  = Encoding.UTF8.GetString(messageToClientBytes);

            Assert.IsTrue(responseToClientBytes.SequenceEqual(messageToClientBytes));
            Assert.AreEqual(responseToClientMessage, messageToClientText);
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> Verification(byte[] email)
        {
            string result = DecryptStringFromBytes_Aes(email, AesService.getInstance().Aes.Key, AesService.getInstance().Aes.IV);
            User   user   = await db.Users.FirstOrDefaultAsync(u => u.Email == result);

            if (user != null)
            {
                user.IsVerified = true;
                await db.SaveChangesAsync();
                await Authenticate(result);

                return(RedirectToAction("Index", "Home"));
            }
            ModelState.AddModelError("", "Не зарегистрированный пользователь");
            return(RedirectToAction("Registration", "Account"));
        }
        public void EncryptAndDecrypt_Test()
        {
            var str = "Should be encrypted and decrypted";

            try
            {
                var enc1 = AesService.EncryptStringToBytes_Aes(str);
                var dec1 = AesService.DecryptStringFromBytes_Aes(enc1);

                Assert.Equal(dec1, str);
            }
            catch (Exception e)
            {
                Assert.True(false, e.ToString());
            }
        }
        public void EncryptStringToBytes_Aes_TwoTimesTheSame_Test()
        {
            var str = "Should be encrypted two times the same way";

            try
            {
                var enc1 = AesService.EncryptStringToBytes_Aes(str);
                var enc2 = AesService.EncryptStringToBytes_Aes(str);

                Assert.Equal(enc1, enc2);
            }
            catch (Exception e)
            {
                Assert.True(false, e.ToString());
            }
        }
        public PaymentInfoResponse Pay(PaymentInfoCommand paymentInfoCommand)
        {
            var decryptedPaymentInfo = new AesService().Decrypt(paymentInfoCommand.EncyptedBody, paymentInfoCommand.Key);

            PaymentInfo paymentInfo  = JsonConvert.DeserializeObject <PaymentInfo>(decryptedPaymentInfo);
            string      approvalCode = createApprovalCode(paymentInfo);

            var response = new PaymentInfoResponse()
            {
                ApprovalCode = approvalCode,
                DateTime     = DateTime.Now,
                Message      = "SUCCESS",
                ResponseCode = ResponseCode.SUCCESS.ToString()
            };

            return(response);
        }
 public void EncryptStringToBytes_Aes_NullException_PlainText_Test()
 {
     // encrypt null
     try
     {
         AesService.EncryptStringToBytes_Aes(null);
         Assert.True(false, "Should throw NullException");
     }
     catch (ArgumentNullException)
     {
         Assert.True(true);
     }
     catch (Exception e)
     {
         Assert.True(false, e.ToString());
     }
 }
        public User ToUser()
        {
            var user = new User
            {
                FirstName = AesService.DecryptStringFromBytes_Aes(FirstName),
                LastName  = AesService.DecryptStringFromBytes_Aes(LastName),
                Email     = AesService.DecryptStringFromBytes_Aes(Email),
                Password  = AesService.DecryptStringFromBytes_Aes(Password)
            };

            if (Token != null)
            {
                user.Token = AesService.DecryptStringFromBytes_Aes(Token);
            }

            user.Id   = Id;
            user.Role = Role;
            return(user);
        }
Ejemplo n.º 11
0
        public UserToDbDto ToUserToDbDto()
        {
            var userToDb = new UserToDbDto
            {
                FirstName = AesService.EncryptStringToBytes_Aes(FirstName),
                LastName  = AesService.EncryptStringToBytes_Aes(LastName),
                Email     = AesService.EncryptStringToBytes_Aes(Email),
                Password  = AesService.EncryptStringToBytes_Aes(Password)
            };

            if (Token != null)
            {
                userToDb.Token = AesService.EncryptStringToBytes_Aes(Token);
            }

            userToDb.Id   = Id;
            userToDb.Role = Role;
            return(userToDb);
        }
Ejemplo n.º 12
0
        public void EncryptAndDecryptWorks()
        {
            //Arrange
            var optionsMock = new Mock <IOptions <EncryptionOptions> >();

            optionsMock.SetupGet(x => x.Value).Returns(new EncryptionOptions()
            {
                IV = "5D5F9A8EB43FDBB9", Key = "AD784C94ABFE8176"
            });
            var sut = new AesService(optionsMock.Object);

            //Act
            var want      = "sample string";
            var encrypted = sut.Encrypt(want);
            var got       = sut.Decrypt(encrypted);

            //Assert
            Assert.Equal(want, got);
        }
Ejemplo n.º 13
0
 public AesServiceTests()
 {
     _aesService = new AesService(_keyHasher, _ivHasher);
 }
Ejemplo n.º 14
0
 public void Decrypt()
 {
     ICryptoService fooBar = new AesService();
     string         result = fooBar.Decrypt("K7J0X3dpNzGY2LBd/f++Slswx0VRX042jTn6EO7R5ith8ltDieJ8KfxcARl8h1Fy", key);
 }
Ejemplo n.º 15
0
 public void Encrypt()
 {
     ICryptoService fooBar = new AesService();
     string         result = fooBar.Encrypt("TestString", key);
 }
Ejemplo n.º 16
0
 public async Task <User> GetUserByEmail(string email)
 {
     return((await FindByCondition(u => AesService.DecryptStringFromBytes_Aes(u.Email).Equals(email))).DefaultIfEmpty(null).FirstOrDefault()?.ToUser());
 }