コード例 #1
0
        public void InitializeParameters()
        {
            millerRabin = new MillerRabin();
            BigInteger p = millerRabin.GetRandomPrime(KeySize / 8);
            BigInteger q = millerRabin.GetRandomPrime(KeySize / 8);


            BigInteger fi = (p - 1) * (q - 1);
            BigInteger e  = millerRabin.GetRandomPrime(fi);

            BigInteger d        = BigIntegerExtensions.ModInverse(e, fi);
            BigInteger inverseQ = BigIntegerExtensions.ModInverse(q, p);
            BigInteger dp       = d % (p - 1);
            BigInteger dq       = d % (q - 1);

            rsaParameters = new RsaParameters
            {
                P        = p,
                Q        = q,
                Modulus  = (p * q),
                Exponent = e,
                Dp       = dp,
                Dq       = dq,
                InverseQ = inverseQ,
                D        = d
            };
        }
コード例 #2
0
        private static HttpWebResponse ProcessIncomingRequestToProtectedSite(HttpListenerContext context, SiteInf siteInf)
        {
            HttpListenerRequest incomingRequest  = context.Request;
            HttpWebResponse     incomingResponse = null;

            // GET - create session, or POST - download session
            if (incomingRequest.HttpMethod == "GET") // ! разобраться с HEAD
            {
                // Запросы типа GET могут быть к защищённому сайту (за ccs или js)
                // или могут быть к странице Login. Те которые к Login перехватываем
                // и отправляем ответ прямо из файлов которые есть на прокси. Кроме того, если
                // запрос без адреса или к странице Login, то создаём и регистрируем новую сессию.
                String      userAddress = null;
                NskdSession session     = null;
                switch (incomingRequest.Url.AbsolutePath)
                {
                case "/":
                case "/login/login.html":
                    userAddress = context.Request.RemoteEndPoint.Address.ToString();
                    session     = new NskdSession(userAddress);
                    RsaParameters ps          = session.Rsa.ExportParameters();
                    String        sessionId   = session.SessionId;
                    String        rsaModule   = Convert.ToBase64String(ps.Module);
                    String        rsaExponent = Convert.ToBase64String(ps.Exponent);
                    server.SendLoginPage(context, sessionId, rsaModule, rsaExponent);
                    break;

                case "/login/login.css":
                    server.SendFile(context, @"Login\Login.css");
                    break;

                case "/login/login.js":
                    server.SendFile(context, @"Login\Login.js");
                    break;

                case "/scripts/cryptico/cryptico.min.js":
                    server.SendFile(context, @"Scripts\Cryptico\cryptico.min.js");
                    break;

                case "/scripts/nskd/nskd.js":
                    server.SendFile(context, @"Scripts\Nskd\Nskd.js");
                    break;

                default:
                    // если запрос типа GET не перехвачен, то перенаправляем его клиенту
                    incomingResponse = siteInf.Client.GetResponse(context);
                    break;
                }
            }
            else if (incomingRequest.HttpMethod == "POST")
            {
                incomingResponse = ProcessPost(incomingRequest, context, siteInf);
            }
            else  // все остальные кроме GET и POST. ! разобраться с HEAD
            {
                incomingResponse = siteInf.Client.GetResponse(context);
            }
            return(incomingResponse);
        }
コード例 #3
0
    private string EncryptPassword(RsaParameters rsaParam)
    {
        // Convert the public keys to BigIntegers
        var modulus  = CreateBigInteger(rsaParam.Modulus);
        var exponent = CreateBigInteger(rsaParam.Exponent);
        // (modulus.ToByteArray().Length - 1) * 8
        //modulus has 256 bytes multiplied by 8 bits equals 2048
        var encryptedNumber = Pkcs1Pad2(rsaParam.Password, (2048 + 7) >> 3);

        // And now, the RSA encryption
        encryptedNumber = BigInteger.ModPow(encryptedNumber, exponent, modulus);

        //Reverse number and convert to base64
        var encryptedString = Convert.ToBase64String(encryptedNumber.ToByteArray().Reverse().ToArray());

        return(encryptedString);
    }
コード例 #4
0
        public static NskdSession GetById(String sessionId)
        {
            NskdSession session = new NskdSession();

            session.SessionId = sessionId;
            // загружаем данные сессии
            DataSet sessionDataSet = Data.Db.Session.Get(sessionId);

            //Console.WriteLine(sessionDataSet.Tables.Count.ToString());
            session.Csp = new CryptServiceProvider();
            if (sessionDataSet.Tables.Count > 0)
            {
                DataTable dt0 = sessionDataSet.Tables[0];
                if (dt0.Rows.Count > 0)
                {
                    DataRow dr = dt0.Rows[0];
                    session.UserId = (dr["user_id"] != DBNull.Value) ? (Int32)dr["user_id"] : 0;
                    if (dr["crypt_key"] != DBNull.Value)
                    {
                        session.CryptKey = Convert.FromBase64String((String)dr["crypt_key"]);
                    }
                    else // Это первый запрос с зашифрованным ключом. Надо восстановить параметры RSA.
                    {
                        if (sessionDataSet.Tables.Count > 1)
                        {
                            DataTable dt1 = sessionDataSet.Tables[1];
                            if (dt1.Rows.Count > 0)
                            {
                                dr = dt1.Rows[0];
                                RsaParameters ps = new RsaParameters();
                                ps.P        = Convert.FromBase64String(dr["p"] as String);
                                ps.Q        = Convert.FromBase64String(dr["q"] as String);
                                ps.Module   = Convert.FromBase64String(dr["module"] as String);
                                ps.Exponent = Convert.FromBase64String(dr["exponent"] as String);
                                ps.D        = Convert.FromBase64String(dr["d"] as String);
                                session.Rsa = new Rsa();
                                session.Rsa.ImportParameters(ps);
                            }
                        }
                    }
                }
            }
            return(session);
        }
コード例 #5
0
 public RSAProvider(RsaParameters parameters)
 {
     rsaParameters = parameters;
 }
コード例 #6
0
    public async Task Login(string pUsername, string pPassword)
    {
        Console.WriteLine("Steamcommunity Login");
        //Get RSA
        Dictionary <string, string> data = new Dictionary <string, string>();
        var request = await m_HttpClient.GetAsync(STEAM_COMMUNITY_GETRSA + "?username="******"Unsuccessfull RSA Key request.");
            return;
        }
        RsaParameters rsaParam = new RsaParameters
        {
            Exponent = rsaKey.publickey_exp,
            Modulus  = rsaKey.publickey_mod,
            Password = pPassword
        };
        var encrypted = string.Empty;

        while (encrypted.Length < 2 || encrypted.Substring(encrypted.Length - 2) != "==")
        {
            encrypted = EncryptPassword(rsaParam);
        }

        data.Add("username", pUsername);
        data.Add("password", encrypted);
        data.Add("twofactorcode", "");
        data.Add("emailauth", "");
        data.Add("loginfriendlyname", "");
        data.Add("captchagid", "-1");
        data.Add("captcha_text", "");
        data.Add("emailsteamid", "");
        data.Add("rsatimestamp", rsaKey.timestamp);
        data.Add("remember_login", "false");
        request = await m_HttpClient.PostAsync(STEAM_COMMUNITY_LOGIN, new FormUrlEncodedContent(data));

        result = await request.Content.ReadAsStringAsync();

        LoginResult loginResult = JsonConvert.DeserializeObject <LoginResult>(result);

        if (loginResult.success)
        {
            IEnumerable <Cookie> responseCookies = m_CookieContainer.GetCookies(new Uri(STEAM_COMMUNITY)).Cast <Cookie>();
            foreach (var cookie in responseCookies)
            {
                Console.WriteLine("Name {0}, {1}", cookie.Name, cookie.Value);
            }
            Console.WriteLine("Successfully logged in.");
            //SendCookies
        }
        else
        {
            Console.WriteLine("Couldn't login...");
            Console.WriteLine(result);
        }
    }
コード例 #7
0
        public async Task <ELoginResult> Login(string twoFactor = null, string emailAuth = null, string captchaGid = null, string captchaText = null)
        {
            var rsaInfo = GetRsaKey();

            var rsaParam = new RsaParameters
            {
                Exponent = rsaInfo.Exponent,
                Modulus  = rsaInfo.Modulus,
                Password = _password
            };

            var encrypted = string.Empty;

            while (encrypted.Length < 2 || encrypted.Substring(encrypted.Length - 2) != "==")
            {
                encrypted = Utilities.EncryptPassword(rsaParam);
            }

#if DEBUG
            Console.WriteLine("[Steam DoLogin] -> Done Encrypting Password");
            Console.WriteLine("[Steam DoLogin] -> Sending Request");
#endif

            var cookieContainer = new CookieContainer();
            var msgHandler      = new HttpClientHandler {
                CookieContainer = cookieContainer
            };
            var httpClient = new HttpClient(msgHandler);

            if (cookieContainer.Count == 0)
            {
                cookieContainer.Add(new Cookie("mobileClientVersion", "2.0.10", "/", ".steamcommunity.com"));
                cookieContainer.Add(new Cookie("mobileClient", "ios", "/", ".steamcommunity.com"));
                cookieContainer.Add(new Cookie("Steam_Language", "english", "/", ".steamcommunity.com"));
            }

            var data = new Dictionary <string, string>
            {
                { "username", _username },
                { "password", encrypted },
                { "twofactorcode", twoFactor ?? "" },
                { "emailauth", emailAuth ?? "" },
                { "loginfriendlyname", "" },
                { "captchagid", captchaGid ?? "-1" },
                { "captcha_text", captchaText ?? "" },
                { "emailsteamid", "" },
                { "rsatimestamp", rsaInfo.Timestamp },
                { "remember_login", "false" },
                { "oauth_client_id", "3638BFB1" }
            };

            httpClient.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
            httpClient.DefaultRequestHeaders.Add("Referer", "https://steamcommunity.com/mobilelogin?oauth_client_id=3638BFB1&oauth_scope=read_profile%20write_profile%20read_client%20write_client");

            var request = await httpClient.PostAsync(ApiEndpoints.SteamBaseUrl + ApiEndpoints.Login, new FormUrlEncodedContent(data));

            var result = await request.Content.ReadAsStringAsync();

            var loginResponse = JsonConvert.DeserializeObject <LoginResponse>(result);

            if (!loginResponse.Success)
            {
                if (loginResponse.Message.Contains("incorrect"))
                {
                    return(ELoginResult.BadCredentials);
                }

                if (loginResponse.Message.Contains("too many"))
                {
                    return(ELoginResult.TooManyFailedLogins);
                }
            }

            if (loginResponse.TwoFactorNeeded)
            {
                Console.Write("Please enter your 2FA code: ");
                var twoF = Console.ReadLine();

                await Login(twoF);

                return(ELoginResult.NeedCaptcha);
            }

            if (loginResponse.CaptchaNeeded)
            {
                _captchaGid = loginResponse.CaptchaGID;

                Process.Start($"https://store.steampowered.com/login/rendercaptcha?gid={_captchaGid}");

                Console.Write($"Please enter the captcha: ");
                var captchaInput = Console.ReadLine();

                await Login(null, null, captchaGid, captchaInput);

                return(ELoginResult.NeedCaptcha);
            }

            if (loginResponse.EmailAuthNeeded)
            {
                return(ELoginResult.NeedEmail);
            }
            if (loginResponse.TwoFactorNeeded)
            {
                return(ELoginResult.Need2Fa);
            }


            Console.WriteLine($"[Steam DoLogin] -> Received OAuth: {loginResponse.OAuthData.OAuthToken}");

            return(ELoginResult.Ok);
        }