コード例 #1
0
ファイル: TestController.cs プロジェクト: cloud3g/WebApi
        public ActionResult PostProduct()
        {
            var productsUrl = Url.RouteUrl("DefaultApi", new
            {
                httproute  = "",
                controller =
                    "products"
            }, "http");

            using (var client = new HttpClient())
            {
                var token = RSAClass.Encrypt("john");
                client.DefaultRequestHeaders.Add("Authorization-Token", token);
                var product = new Product
                {
                    Id   = 1,
                    Name = "test product"
                };
                var result = client
                             .PostAsync <Product>(productsUrl, product, new JsonMediaTypeFormatter())
                             .Result;
                if (result.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return(Content("Sorry you are not authorized to perform this operation"));
                }

                return(Json(true, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #2
0
        public IHttpActionResult Post(UserLogin userLogin)
        {
            // Get user from database using username
            var user = UserRepository.GetByUsername(userLogin.username);

            if (user == null || !user.Active)
            {
                return(Unauthorized());
            }
            else
            {
                // Check the entered password against stored user password
                var passwordValid = user.Authenticate(userLogin.password);
                if (passwordValid)
                {
                    // Generate and return the encrypted token
                    var clientAuthorisation = new ClientAuthorisation(user.Id, DateTime.Now);
                    var encryptedUser       = RSAClass.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(clientAuthorisation));
                    return(Ok(encryptedUser));
                }
                else
                {
                    return(Unauthorized());
                }
            }
        }
コード例 #3
0
        public IHttpActionResult UserLogin(UserLoginModel objUserLoginModel)
        {
            try
            {
                User objUser = UserFactory.Instance.GetUserData(objUserLoginModel.UserName);
                if (objUser.Password == objUserLoginModel.Password)
                {
                    var token = RSAClass.Encrypt(Convert.ToString(objUserLoginModel.UserName));

                    objUserLoginModel.Id          = objUser.Id;
                    objUserLoginModel.FirstName   = objUser.FirstName;
                    objUserLoginModel.LastName    = objUser.LastName;
                    objUserLoginModel.LoginStatus = "Login Success";
                    objUserLoginModel.Token       = token;
                    objUserLoginModel.ValidDate   = DateTime.Now.AddDays(1);
                }
                else
                {
                    objUserLoginModel.LoginStatus = "Login Failed!";
                }
            }
            catch (Exception ex)
            {
                _olog.LogException(ex, "UserLogin", "v1Controller");
            }

            return(Ok(objUserLoginModel));
        }
コード例 #4
0
        public void RSAParameters()
        {
            var token     = "abundatrade";
            var encrypted = RSAClass.Encrypt(token);
            var decrypted = RSAClass.Decrypt(encrypted);

            Assert.AreEqual(token, decrypted);
        }
コード例 #5
0
        public void VerifyToken()
        {
            var token          = "User1";
            var encryptedToken = RSAClass.Encrypt(token);
            var decryptedToken = RSAClass.Decrypt(encryptedToken);

            Console.WriteLine(encryptedToken);
            Assert.Equal(token, decryptedToken);
        }
コード例 #6
0
 // При нажатии на кнопку send отсылается сообщение и закодированный текст из textContent
 private void clickSend(object sender, EventArgs e)
 {
     try
     {
         SendToStream(new MessageClass(codes.ENCRYPTED_MESSAGE, rs.Encrypt(textContent.Text, serverKey)), ref client);
     }
     catch (Exception ex)
     {
         MessageBox.Show("In clickSend: " + ex.Message);
     }
 }
コード例 #7
0
ファイル: UnitTest.cs プロジェクト: yar00001/SimpleEncrypt
        public void RSATest()
        {
            var message = "this is a test";

            RSAClass.GenerateKey();

            byte[] rsaEncrypted = RSAClass.Encrypt(Encoding.UTF8.GetBytes(message));
            byte[] rsaDecrypted = RSAClass.Decrypt(rsaEncrypted);

            Console.WriteLine("Original: " + message + "\n");
            Console.WriteLine("Encrypted: " + BitConverter.ToString(rsaEncrypted) + "\n");
            Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(rsaDecrypted));
        }
コード例 #8
0
        // Обработка запросов от пользователя. При получении пакета с кодом disconnect прекращаем
        private void Process_User(ref TcpClient client, int id)
        {
            bool connected = true;

            try
            {
                MessageClass message;
                while (connected)
                {
                    message = GetFromStream(ref client);
                    switch (message.code)
                    {
                    // При получении публичного ключа отсылаем свой.
                    case codes.PUBLIC_KEY:
                        connectedUsers[id] = JsonConvert.DeserializeObject <RSAParameters>(message.info);
                        // Вывод значений в textbox-формы
                        textDecrypt.BeginInvoke(new Action(() => textDecrypt.Text = "Sent to user " + id));
                        textStatus.BeginInvoke(new Action(() => textStatus.Text   = message.info));
                        SendToStream(new MessageClass(codes.PUBLIC_KEY, rs.PublicKeyString()), ref client);
                        break;

                    // При получении зашифрованного сообщения расшифровываем своим приватным ключом, добавляем текст,
                    // шифруем и отсылаем
                    case codes.ENCRYPTED_MESSAGE:
                        textDecrypt.Text = message.info;
                        SendToStream(new MessageClass(codes.ENCRYPTED_MESSAGE, rs.Encrypt("Пажилое сообщение: " +
                                                                                          rs.Decrypt(message.info), connectedUsers[id])), ref client);
                        break;

                    // Удаляем пользователя, захотевшего уйти
                    case codes.DISCONNECT_MESSAGE:
                        connectedUsers.Remove(id);
                        connected = false;
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("In Process_User: " + e.Message);
            }
        }
コード例 #9
0
ファイル: TestController.cs プロジェクト: cloud3g/WebApi
        public ActionResult GetProducts()
        {
            var productsUrl = Url.RouteUrl("DefaultApi", new
            {
                httproute  = "",
                controller =
                    "products"
            }, "http");

            using (var client = new HttpClient())
            {
                var token = RSAClass.Encrypt("john");
                client.DefaultRequestHeaders.Add("Authorization-Token", token);
                var products = client
                               .GetAsync(productsUrl)
                               .Result
                               .Content
                               .ReadAsAsync <IEnumerable <Product> >()
                               .Result;
                return(Json(products, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #10
0
ファイル: HttpClientHelper.cs プロジェクト: zz110/WKT2015
        public T GetAuth <T>(string url)
        {
            T returnResult;

            using (var client = new HttpClient())
            {
                try
                {
                    client.DefaultRequestHeaders.Add(RQUESTHEADERTOKENKEY, RSAClass.Encrypt(GetToken()));
                    client.DefaultRequestHeaders.Add(AUTHSITEID, ConfigurationManager.AppSettings["SiteID"]);
                    client.DefaultRequestHeaders.Add(AUTHSITE, ConfigurationManager.AppSettings["SiteDomain"]);
                    HttpResponseMessage response = null;
                    client.GetAsync(url).ContinueWith(
                        (requestTask) =>
                    {
                        response = requestTask.Result;
                    }).Wait(60000);
                    if (response.IsSuccessStatusCode)
                    {
                        returnResult = response.Content.ReadAsAsync <T>().Result;
                    }
                    else
                    {
                        throw new Exception(response.ReasonPhrase);
                        //returnResult = default(T);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    client.Dispose();
                }
            }
            return(returnResult);
        }