Ejemplo n.º 1
0
        static UdpConnectionProviderTests()
        {
            var crypto = new RSACrypto();
            serverKey = crypto.ExportKey (true);

            crypto = new RSACrypto();
            localKey = crypto.ExportKey (true);
        }
Ejemplo n.º 2
0
 private void buttonDecrypta_Click(object sender, EventArgs e)
 {
     try
     {
         var encryptedText = new RSACrypto().DecryptaData(textBoxText.Text, textBoxPrivateKey.Text);
         textBoxText.Text = encryptedText;
     }
     catch (Exception)
     {
         MessageBox.Show("Failed decrypting");
     }
 }
Ejemplo n.º 3
0
 public override void AddRecipes()
 {
     base.AddRecipes();
     if (Loaded)
     {
         return;
     }
     //_messageChecker = new MessageChecker();
     ShowTooltip       = "";
     _packetHandler    = new PacketHandler();
     _sscPacketHandler = new SSCPacketHandler();
     if (!Main.dedServ)
     {
         // 加载资源只有在非服务器端才会执行
         // MethodSwapper.SwapMethods();
         MainPlayerGroup       = new Group("default");
         ToolBarServiceManager = new ToolBarServiceManager();
         ResourceLoader.LoadAll();
         GuiManager        = new GUIManager(this);
         IsLoginClientSide = false;
         ClientUnion       = null;
         if (DEBUGMODE)
         {
             ClientUnion       = new Union("裙中世界");
             ClientUnion.Owner = "我不是裙子";
         }
     }
     else
     {
         // 生成玩家存档,这里用json文件存储玩家信息
         // 顺序一定不能错
         PlayerCollection = new PlayerCollection();
         PlayerDoc        = new PlayersDocument("players.json");
         PlayerDoc.ExtractPlayersData();
         GroupManager = new GroupManager();
         GroupManager.SetGroups();
         UnionManager  = new UnionManager();
         RegionManager = new RegionManager();
         MailManager   = new MailManager();
         // 服务器端生成RSA私钥
         RSACrypto.GenKey();
         ConfigLoader.Load();
         MarketManager  = new MarketManager();
         MatchingSystem = new MatchingSystem();
         AddUnionRegions();
     }
     Loaded = true;
     if (!Main.dedServ)
     {
         GuiManager.SetNPCDefaults();
     }
 }
Ejemplo n.º 4
0
        ///<summary>
        /// Authenticate using SteamKit2 and ISteamUserAuth.
        /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website.
        /// </summary>
        /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks>
        public bool Authenticate(string myUniqueId, SteamClient client, string myLoginKey)
        {
            Token     = TokenSecure = "";
            SessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(myUniqueId));
            _cookies  = new CookieContainer();

            using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                // generate an AES session key
                var sessionKey = CryptoHelper.GenerateRandomBlock(32);

                // rsa encrypt it with the public key for the universe we're on
                byte[] cryptedSessionKey = null;
                using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                byte[] loginKey = new byte[20];
                Array.Copy(Encoding.ASCII.GetBytes(myLoginKey), loginKey, myLoginKey.Length);

                // aes encrypt the loginkey with our session key
                byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                KeyValue authResult;

                try
                {
                    authResult = userAuth.AuthenticateUser(
                        steamid: client.SteamID.ConvertToUInt64(),
                        sessionkey: HttpUtility.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey),
                        method: "POST",
                        secure: true
                        );
                }
                catch (Exception)
                {
                    Token = TokenSecure = null;
                    return(false);
                }

                Token       = authResult["token"].AsString();
                TokenSecure = authResult["tokensecure"].AsString();

                _cookies.Add(new Cookie("sessionid", SessionId, String.Empty, SteamCommunityDomain));
                _cookies.Add(new Cookie("steamLogin", Token, String.Empty, SteamCommunityDomain));
                _cookies.Add(new Cookie("steamLoginSecure", TokenSecure, String.Empty, SteamCommunityDomain));

                return(true);
            }
        }
Ejemplo n.º 5
0
        protected override void Recycle()
        {
            if (AutoSizeSendBufferLimit)
            {
                Interlocked.Add(ref sendBufferLimit, AutoSizeFactor * -1);
            }

            this.serverEncryption        = null;
            this.serverEncryptionKey     = null;
            this.serverAuthenticationKey = null;

            base.Recycle();
        }
Ejemplo n.º 6
0
        private void DecryptButton_Click(object sender, RoutedEventArgs e)
        {
            if (ReceivedMessagesListView.SelectedItems.Count < 1)
            {
                MessageBox.Show("U have to select a message first!", "Warning!", MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }
            else if (ReceivedMessagesListView.SelectedItems.Count > 1)
            {
                MessageBox.Show("U can only read one message!", "Warning!", MessageBoxButton.OK,
                                MessageBoxImage.Information);
            }
            else
            {
                MessageTextBlock.Visibility = Visibility.Visible;
                this.Height = 600;
                Message msg         = (Message)ReceivedMessagesListView.SelectedItem;
                var     fromUserPuK = msg.From.PuK;
                var     currUserPvk = currUser.PvK;
                var     file1       = msg.File1;
                var     file2       = msg.File2;
                var     file3       = msg.File3;
                var     IV          = msg.IV;
                var     key         = RSACrypto.DecryptBytes(file2, currUserPvk);
                MessageTextBlock.Text = "\n\n########AES KEY DECRYPT ########\n\n";
                UnicodeEncoding _encoder = new UnicodeEncoding();
                MessageTextBlock.Text += _encoder.GetString(key);

                var message = AESCrypto.DecryptStringFromBytes(file1, key, IV);
                MessageTextBlock.Text += "\n\n######## MESSAGE ########\n\n";
                MessageTextBlock.Text += message;


                var oldHash = RSACrypto.DecryptBytes(file3, currUserPvk);

                string strOldHash = Encoding.UTF8.GetString(oldHash);

                MessageTextBlock.Text += "\n\n######## Decrypted hash ########\n\n";
                MessageTextBlock.Text += strOldHash;


                if (BCrypt.CheckPassword(message, strOldHash))
                {
                    MessageTextBlock.Text += "\n\n######## HASHES ARE EQUAL! ########\n\n";
                }
                else
                {
                    MessageTextBlock.Text += "\n\n######## HASHES ARE NOT EQUAL! ########\n\n";
                }
            }
        }
Ejemplo n.º 7
0
        internal UdpServerConnection(int connectionId, EndPoint remoteEndpoint, UdpConnectionProvider provider, RSACrypto remoteCrypto, RSACrypto localCrypto, RSAAsymmetricKey key)
            : base(provider.protocols.Values)
        {
            this.remoteCrypto = remoteCrypto;
            this.localCrypto = localCrypto;
            LocalKey = key;

            ConnectionId = connectionId;
            IPEndPoint = (IPEndPoint)remoteEndpoint;
            RemoteTarget = remoteEndpoint.ToTarget();
            this.provider = provider;

            this.socket = this.provider.GetSocket (remoteEndpoint);
        }
        private void file_keys_rsa_Click(object sender, EventArgs e)
        {
            OpenFileDialog get_file  = new OpenFileDialog();
            string         file_name = "";

            if (get_file.ShowDialog() == DialogResult.OK)
            {
                file_name = get_file.FileName;
            }
            string[] keys = new string[6];
            try
            {
                using (StreamReader sr = new StreamReader(file_name))
                {
                    string line;
                    int    count = 0;
                    while ((line = sr.ReadLine()) != null)
                    {
                        keys[count++] = line;
                    }
                    if (keys[3].Length <= 320)
                    {
                        key_size_rsa.Text = 1024.ToString();
                        size_rsa          = 1024;
                    }
                    else
                    {
                        key_size_rsa.Text = 2048.ToString();
                        size_rsa          = 2048;
                    }
                    P_RSA  = BigInteger.Parse(keys[0]);
                    Q_RSA  = BigInteger.Parse(keys[1]);
                    N      = BigInteger.Parse(keys[2]);
                    PHI_N  = BigInteger.Parse(keys[3]);
                    PK_RSA = BigInteger.Parse(keys[4]);
                    SK_RSA = BigInteger.Parse(keys[5]);
                }
                p_rsa.Text    = P_RSA.ToString();
                q_rsa.Text    = Q_RSA.ToString();
                n_rsa.Text    = N.ToString();
                phin_rsa.Text = PHI_N.ToString();
                pk_rsa.Text   = PK_RSA.ToString();
                sk_rsa.Text   = SK_RSA.ToString();
                rsa           = new RSACrypto(PK_RSA, N, PHI_N, SK_RSA, size_rsa);
            }
            catch
            {
                return;
            }
        }
Ejemplo n.º 9
0
        private static void TestHabboEncryption(bool consoleOutput, int dhBitLength, int rsaBitLength)
        {
            RSACrypto     serverRsa = new RSACrypto(RSACParameters.FromXmlFile(@"rsa.keys"));
            DiffieHellman serverDh  = DiffieHellman.CreateInstance(dhBitLength);

            string serverDhPrimeRsa = signDiffieHellmanKeys(serverDh.P, serverRsa);
            string serverDhGenRsa   = signDiffieHellmanKeys(serverDh.G, serverRsa);

            RSACrypto clientRsa = new RSACrypto(new RSACParameters(_modules, _exponent));

            BigInteger clientDhPrime = verifyDiffieHellmanKeys(serverDhPrimeRsa, clientRsa);
            BigInteger clientDhGen   = verifyDiffieHellmanKeys(serverDhGenRsa, clientRsa);

            DiffieHellman clientDh = new DiffieHellman(dhBitLength, clientDhPrime, clientDhGen);

            if (!clientDh.P.Equals(serverDh.P))
            {
                throw new Exception("HabboEncryption test FAILED, P keys are not equal!");
            }

            if (!clientDh.G.Equals(serverDh.G))
            {
                throw new Exception("HabboEncryption test FAILED, G keys are not equal!");
            }

            string serverDhPublicRsa = signDiffieHellmanKeys(serverDh.PublicKey, serverRsa);
            string clientDhPublicRsa = encryptDiffieHellmanKeys(clientDh.PublicKey, clientRsa);

            BigInteger serverDhClientPublic = decryptDiffieHellmanKeys(clientDhPublicRsa, serverRsa);
            BigInteger clientDhServerPublic = verifyDiffieHellmanKeys(serverDhPublicRsa, clientRsa);

            if (!clientDhServerPublic.Equals(serverDh.PublicKey))
            {
                throw new Exception("HabboEncryption test FAILED, server -> client public keys are not equal!");
            }

            if (!serverDhClientPublic.Equals(clientDh.PublicKey))
            {
                throw new Exception("HabboEncryption test FAILED, server <- client public keys are not equal!");
            }

            BigInteger serverDhShared = serverDh.CalculateSharedKey(serverDhClientPublic);
            BigInteger clientDhShared = clientDh.CalculateSharedKey(clientDhServerPublic);

            if (!serverDhShared.Equals(clientDhShared))
            {
                throw new Exception("HabboEncryption test FAILED, shared keys are not equal!");
            }
        }
Ejemplo n.º 10
0
        public SharePasswordController()
        {
            _repository = new PasswordJsonRepository(System.Web.HttpContext.Current);



            if (System.Web.HttpContext.Current.Session["rsa"] == null)
            {
                _rsaCrypto = new RSACrypto();
                System.Web.HttpContext.Current.Session["rsa"] = _rsaCrypto;
            }
            else
            {
                _rsaCrypto = (RSACrypto)System.Web.HttpContext.Current.Session["rsa"];
            }
        }
Ejemplo n.º 11
0
        public string[] GetPublicKey()
        {
            RSACrypto crypto = new RSACrypto();
            RSAItem   item = new RSAItem();
            string    privateKey = "", publicKey = "";

            crypto.CreateKeys(out privateKey, out publicKey);
            item.PrivateKey = privateKey;
            item.PublickKey = publicKey;
            item.Guid       = Guid.NewGuid().ToString();
            item.CreateTime = DateTime.Now;
            RedisHelper.Add(item.Guid, item);
            string[] arry = new string[2];
            arry[0] = item.Guid;
            arry[1] = RSAConvert.PemPublicKeyByXml(item.PrivateKey);
            return(arry);
        }
Ejemplo n.º 12
0
        public JsonResult Validate()
        {
            #region 公钥 私钥
            //-----BEGIN PUBLIC KEY-----
            //MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4mZ8DLLwSMETsoQTKdu4efwhd
            //fTY/rxhsGA5EittII0/SeDQlRC4IzpxzMTKQSMWvnRlvD7V4Z2u1KBGhE++i/T5K
            //RdNCBXdo/G0pUdP2Nf4DpMP30HF54GwP8iZoXWVLy/tWtdZx9DUvajCn6GmgnjqK
            //NPTiCQsARLvYAou18wIDAQAB
            //-----END PUBLIC KEY-----

            //-----BEGIN RSA PRIVATE KEY-----
            //MIICXAIBAAKBgQC4mZ8DLLwSMETsoQTKdu4efwhdfTY/rxhsGA5EittII0/SeDQl
            //RC4IzpxzMTKQSMWvnRlvD7V4Z2u1KBGhE++i/T5KRdNCBXdo/G0pUdP2Nf4DpMP3
            //0HF54GwP8iZoXWVLy/tWtdZx9DUvajCn6GmgnjqKNPTiCQsARLvYAou18wIDAQAB
            //AoGAHjwbDTwQebIqN8+Pp1GfYqNPzXAqqHeXOm0eOR+9Fq2h70j80XW/THX6retK
            //6tLgfgjvF3+tK1FVFNDBQm6veuzRQjUO5JE0uRs4LSlRECa0ENxPgxFtELtTzRdJ
            //u/KXY3DB+ke+RLG0azylcwGeCtNbijYEneCqpCK5Fpjh8yECQQC/YWl4VCbqAUKE
            //GBipUdg9C8l/Aq/0H1vnS9jepvi5lYmSMNY60/r9h89qNbTB5FOn6LZC0n/TDmFL
            //YSr1MTiZAkEA9u4e5i2lJUG4w5IQGRKDrAzmto9a0ooQatPKoW4XiEHmwnZWFTUD
            //3eUc0IDlh+WYGi41Bg1+dzn9h0blq+Q+awJAR5Lo3QWr4AxEkh5o6rofQwVrgELD
            //B2vK9T/ahbqwfse8QZ5eIHYzAiqOmcwoI/N+jedscqVDBO312Tkn1bdo0QJBAOQC
            //HpAGh96uIBCeN7UfDmx5ATSDjKaqC9zIset7/8i2qYDYykYMzQRBAelZjBh/HYLX
            //Nejf3u3yozMdeQfO2v8CQD/uSS5BeJerr4pnF4suTzaqpIW66D2HVI3JxssBJWwt
            //fdVFi1a6EbZc0mHTzY/zLVX/ApTXbQZSFF/rwG0P8Dk=
            //-----END RSA PRIVATE KEY-----
            #endregion

            string publicKey  = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4mZ8DLLwSMETsoQTKdu4efwhdfTY/rxhsGA5EittII0/SeDQlRC4IzpxzMTKQSMWvnRlvD7V4Z2u1KBGhE++i/T5KRdNCBXdo/G0pUdP2Nf4DpMP30HF54GwP8iZoXWVLy/tWtdZx9DUvajCn6GmgnjqKNPTiCQsARLvYAou18wIDAQAB";
            string privateKey = @"MIICXAIBAAKBgQC4mZ8DLLwSMETsoQTKdu4efwhdfTY/rxhsGA5EittII0/SeDQlRC4IzpxzMTKQSMWvnRlvD7V4Z2u1KBGhE++i/T5KRdNCBXdo/G0pUdP2Nf4DpMP30HF54GwP8iZoXWVLy/tWtdZx9DUvajCn6GmgnjqKNPTiCQsARLvYAou18wIDAQABAoGAHjwbDTwQebIqN8+Pp1GfYqNPzXAqqHeXOm0eOR+9Fq2h70j80XW/THX6retK6tLgfgjvF3+tK1FVFNDBQm6veuzRQjUO5JE0uRs4LSlRECa0ENxPgxFtELtTzRdJu/KXY3DB+ke+RLG0azylcwGeCtNbijYEneCqpCK5Fpjh8yECQQC/YWl4VCbqAUKEGBipUdg9C8l/Aq/0H1vnS9jepvi5lYmSMNY60/r9h89qNbTB5FOn6LZC0n/TDmFLYSr1MTiZAkEA9u4e5i2lJUG4w5IQGRKDrAzmto9a0ooQatPKoW4XiEHmwnZWFTUD3eUc0IDlh+WYGi41Bg1+dzn9h0blq+Q+awJAR5Lo3QWr4AxEkh5o6rofQwVrgELDB2vK9T/ahbqwfse8QZ5eIHYzAiqOmcwoI/N+jedscqVDBO312Tkn1bdo0QJBAOQCHpAGh96uIBCeN7UfDmx5ATSDjKaqC9zIset7/8i2qYDYykYMzQRBAelZjBh/HYLXNejf3u3yozMdeQfO2v8CQD/uSS5BeJerr4pnF4suTzaqpIW66D2HVI3JxssBJWwtfdVFi1a6EbZc0mHTzY/zLVX/ApTXbQZSFF/rwG0P8Dk=";

            RSACrypto rsaCrypto = new RSACrypto(privateKey, publicKey);
            //获取参数
            string usernameEncode = Request["username"];
            string pwdEncode      = Request["passwd"];

            string name1 = CommonHelper.GetPostValue("username", 100, true, true, true);
            string pwd2  = CommonHelper.GetPostValue("passwd", 100, true, true, true);

            //解密 RSA
            string username = rsaCrypto.Decrypt(usernameEncode);
            string pwd      = rsaCrypto.Decrypt(pwdEncode);

            string username3 = rsaCrypto.Decrypt(name1);
            string pwd3      = rsaCrypto.Decrypt(pwd2);
            return(null);
        }
Ejemplo n.º 13
0
        public void Test()
        {
            using (var rsaCrypto = new RSACrypto())
            {
                rsaCrypto.Initialize(new Dictionary <string, object>
                {
                    { "Algorithm", "RSA" },
                    { "PublicKey", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD2KXcCt30MrOOt4F1vhtfNViBGapFRmxaOnSVK9FMPV63Pr8Y3EzFpLFH58TzbNtwoB5aWRy4zjImbwsy5S2eqmSkJQWbWZiyxMLEYy1+dQDr27SihLp7BvrDUj8uy+LIO6fwCDMKJ2sQtXh+Uk6AO9meqdpA5riUEDVQKbpw6IQIDAQAB" },
                    { "PrivateKey", "MIICXQIBAAKBgQD2KXcCt30MrOOt4F1vhtfNViBGapFRmxaOnSVK9FMPV63Pr8Y3EzFpLFH58TzbNtwoB5aWRy4zjImbwsy5S2eqmSkJQWbWZiyxMLEYy1+dQDr27SihLp7BvrDUj8uy+LIO6fwCDMKJ2sQtXh+Uk6AO9meqdpA5riUEDVQKbpw6IQIDAQABAoGBAL0EW+kPIgtgmjdCaByiKwT11DSd0dYawzhg/GjQsRK/3avzKb3SlAdRS+UjUvp05poqMXxVTemxSVz8OJ0zhHYePa+wE0E31sBfnMxpOo5LIraTQuKGhE5IXNgUB0xYyAkG4vLLmoGDFCUHWPHYw5591C66eNyhJMSkPcqSCbMNAkEA+8HXhp3Ut1LVqBFnSpUIoRkUfXotWvfJjat6GGtmyglSRqTcUkVwIlBabVEMDyoMS9/LQcXM2QQ3bJiTKpDY3wJBAPpPe8Tfjm2o1Oxz8aGjnt+u2b4SZ9WXXkbZY1qsMNAkrP7ZFF5MTIm9L18V+yrvZ0mU7YC5Mck+F5eEbIxOTP8CQQDf0X1i2H58XNBGEvLZg5WgY0OsKiqYbSJrKL/rZdCEXbUfyQF2wvTmDLnX5e3qrV8xNUzmtIthhDYh/aMYfJ3RAkAMy39SIvNO27B2nb6eOpTmbjOnKZ2xJ1mkWXxgqCiemyFUrZgC8fd/mvIO9DqwiShIdJpnWBAZb1kZX6WEzoPVAkAz0CHiCH5JGdf71zCifbfFfcXA9+IXqQxvU9+3yGLAQW1S7xd94f8uOX+CsWsUchOpwmgzXYpvMLEtu822WqfF" }
                });
                var plainText = "SmartSql";

                var cipherText  = rsaCrypto.Encrypt(plainText);
                var decryptText = rsaCrypto.Decrypt(cipherText);
                Assert.Equal(plainText, decryptText);
            }
        }
        public async Task <IVRConfig> GetItemAsync()
        {
            IVRConfig config = await DataProvider.GetAsync(KEY);

            if (config == null)
            {
                config = new IVRConfig();

                string publicKey, privateKey;
                RSACrypto.MakeNewKeys(out publicKey, out privateKey);
                config.PrivateKey = privateKey;
                config.PublicKey  = publicKey;

                await AddConfigAsync(config);
            }
            return(config);
        }
        public byte[] EnPwd_UTF8(List <byte[]> data)
        {
            string input_str  = Encoding.UTF8.GetString(data[0]);
            string public_key = Encoding.UTF8.GetString(data[1]);

            try
            {
                RSACrypto rsaCrypto = new RSACrypto("", public_key);

                // StartWith -----BEGIN PUBLIC KEY-----  216  EndWith -----END PUBLIC KEY-----
                return(Encoding.UTF8.GetBytes(rsaCrypto.Encrypt(input_str)));
            }
            catch (Exception)
            {
                return(Encoding.UTF8.GetBytes(""));
            }
        }
Ejemplo n.º 16
0
        ///<summary>
        /// Authenticate using SteamKit2 and ISteamUserAuth.
        /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website.
        /// </summary>
        /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks>
        public static bool Authenticate(SteamUser.LoginKeyCallback callback, SteamClient client, out string sessionId, out string token)
        {
            sessionId = Convert.ToBase64String(Encoding.UTF8.GetBytes(callback.UniqueID.ToString()));

            using (dynamic userAuth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                // generate an AES session key
                var sessionKey = CryptoHelper.GenerateRandomBlock(32);

                // rsa encrypt it with the public key for the universe we're on
                byte[] cryptedSessionKey = null;
                using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.ConnectedUniverse)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }


                byte[] loginKey = new byte[20];
                Array.Copy(Encoding.ASCII.GetBytes(callback.LoginKey), loginKey, callback.LoginKey.Length);

                // aes encrypt the loginkey with our session key
                byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                KeyValue authResult;

                try
                {
                    authResult = userAuth.AuthenticateUser(
                        steamid: client.SteamID.ConvertToUInt64(),
                        sessionkey: HttpUtility.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey),
                        method: "POST"
                        );
                }
                catch (Exception)
                {
                    token = null;
                    return(false);
                }

                token = authResult ["token"].AsString();

                return(true);
            }
        }
Ejemplo n.º 17
0
    void Start()
    {
        RSACrypto.GenKey();

        //Create a UnicodeEncoder to convert between byte array and string.
        UnicodeEncoding ByteConverter = new UnicodeEncoding();

        //Create byte arrays to hold original, encrypted, and decrypted data.
        byte[] dataBytes = ByteConverter.GetBytes("Data to Encrypt,hahaha");
        byte[] encryptedData;
        byte[] decryptedData;

        encryptedData = RSACrypto.RSAEncrypt(dataBytes, RSACrypto.m_publickey, false);

        decryptedData = RSACrypto.RSADecrypt(encryptedData, RSACrypto.m_privateKey, false);

        Debug.Log("message:" + ByteConverter.GetString(decryptedData));
    }
Ejemplo n.º 18
0
        public ActionResult Encrypt(string passwd)
        {
            string PrivateKey = @"-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCZoXqoJktTWSTolirHAFpLdK3w1eaawiKu9q7VQeqghF7S90IJ
FKlawmuLhiEmrOLOqG0AYQOSdX0WSEcRlGH/VKwz5XNOsLutQWSfG2xt4bXT+nAm
qp/nWpeSlNuFYhsCWSjFydAtoUjLBXi0gusaBDpwfgq4zBGXAA7M3uVmTwIDAQAB
AoGBAIZ0khHJ+hDHKws4KdYik+QICReHTRzSnWI9WUQhPYQgdZDzf2LNJ27cSx1A
VZEwrAur0kILpgGvO7udpD1ZfO2Lg3lcBN+CVjp97oJPFCYQdD1yuRRjpvCsrLLu
zzfuSNatYbgS8lCh6HloSB7XThck8W6GbmNJsiYscn6GztUJAkEAvCeDzQKjZxvc
1+VS+dPzOAq8nBVuQES9V5PZM0tHfNuA1J04l0Y4c9mMWsh6YOBsTz46vs5yuCKk
Ptwg6pLlNQJBANEHGdCZJOgKWUg6Xraz38RBM1cPHKzYEmOu1HiNl30wGCuM1b61
8xsDntaHXYHJxYgiudVwzH5Sj2iRVn2CIfMCQALAGR8gEL9rGtlVEtdwD7gcABHQ
BmKOHq5vDNfBG/RpSQLSoYckkaKv5WtWTuOnpC2sXTN41Rh3+SqqERkcuJkCQAFW
HUkjIYRGRKncjax3W+/iRtTAqPtF6mAuxvb6WMSZIR5uKROuEB7VGBfhB60DwDqN
lkiSDwyjtH0DqNzmjxcCQQCvIhCkietd1YSG1Jl7zSmuT3NksNwj4HGYSfMLdkBV
ag8pleWkHqBf9Z1d/qbOkealNgmmiE8JO/vGuM7T0uDw
-----END RSA PRIVATE KEY-----
";


            string PublicKey = @"-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZoXqoJktTWSTolirHAFpLdK3w
1eaawiKu9q7VQeqghF7S90IJFKlawmuLhiEmrOLOqG0AYQOSdX0WSEcRlGH/VKwz
5XNOsLutQWSfG2xt4bXT+nAmqp/nWpeSlNuFYhsCWSjFydAtoUjLBXi0gusaBDpw
fgq4zBGXAA7M3uVmTwIDAQAB
-----END PUBLIC KEY-----";


            PrivateKey = PrivateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "")
                         .Replace("-----END RSA PRIVATE KEY-----", "");

            PublicKey = PublicKey.Replace("-----BEGIN PUBLIC KEY-----", "")
                        .Replace("-----END PUBLIC KEY-----", "");
            RSACrypto rsaCrypto = new RSACrypto(PrivateKey, PublicKey);



            //解密 RSA

            string pwd = rsaCrypto.Decrypt(passwd);

            return(Json(pwd));
        }
Ejemplo n.º 19
0
        public UdpConnectionProvider(int port, Protocol protocol, RSAAsymmetricKey authKey)
            : base(new[] { protocol }, port)
        {
            if (protocol == null)
                throw new ArgumentNullException ("protocol");
            if (authKey == null)
                throw new ArgumentNullException ("authKey");
            if (port <= 0)
                throw new ArgumentOutOfRangeException ("port");

            this.crypto = new RSACrypto();
            this.crypto.ImportKey (authKey);

            this.pkEncryption = new RSACrypto();
            this.pkEncryption.ImportKey (authKey);

            this.authKey = authKey;

            ValidateProtocols (this.protocols.Values);
        }
Ejemplo n.º 20
0
        static void Test1()
        {
            var rsa        = new RSACryptoServiceProvider(2048);
            var pubKey     = rsa.ExportCspBlob(false);
            var privateKey = rsa.ExportCspBlob(true);

            var    b = new RSACrypto().Encrypt(pubKey, System.Text.Encoding.UTF8.GetBytes("hello."));
            var    c = new RSACrypto().Decrypt(privateKey, b);
            string s = string.Empty;



            //var rsa1 = new RSACryptoServiceProvider(1024);
            //rsa1.ImportCspBlob(pubKey);
            //var secret = rsa1.Encrypt(System.Text.Encoding.UTF8.GetBytes("hello."), false);

            //var rsa2 = new RSACryptoServiceProvider(1024);
            //rsa2.ImportCspBlob(privateKey);
            //var plain = rsa2.Decrypt(secret, false);
        }
Ejemplo n.º 21
0
        public RequestManager(ServerClass serverClass)
        {
            this.serverClass = serverClass;

            utf8 = new UTF8Encoding();

            Log.Write("Starting to generate public/private key pair.");
            waitForKeyGeneration = new EventWaitHandle(false, EventResetMode.ManualReset);
            rsa = new RSACrypto();
            rsa.OnKeysGenerated += new RSACrypto.KeysGenerated(KeyGenerated);
            rsa.GenerateKeys(2048);

            aes = new AesManaged();

            listener = new HttpListener();
            listener.Prefixes.Add("http://*:80/");
            alive = false;

            Log.Write("Request manager created, and ready to start server.");
        }
Ejemplo n.º 22
0
        public QuarterServer(ServerConfig config)
        {
            DefaultAllow = config.DefaultAllow;
            Flags        = config.Flags;
            Host         = config.Host;
            Port         = config.Port;
            RSACrypto    = new RSACrypto();
            LatestClient = null;
            Clients      = new List <QuarterClient>();
            ClientCount  = 1;

            try
            {
                Listener = new TcpListener(Host, Port);
                Listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
                Listener.Start();
            } catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 23
0
        private void ParseResponse(byte[] result)
        {
            string message = Encoding.Default.GetString(result);

            Operation msg = JsonConvert.DeserializeObject <Operation>(message);

            switch (msg.op)
            {
            case "auth":
                rsa = new RSACrypto(File.ReadAllText("pri.key"), true);
                break;

            case "list_file":
                lvFileBrowser.Items.Clear();
                int id = 1;
                foreach (string i in msg.param)
                {
                    ListViewItem tmp = new ListViewItem(new string[] { id.ToString(), i, "Not Download" });
                    lvFileBrowser.Items.Add(tmp);
                    id++;
                }
                break;

            case "send_file":
                string path = "data/" + msg.param[0];
                File.WriteAllBytes(path, rsa.DecodeOrNull(RSA_Unit.Base64DecodeBytes(msg.param[1])));
                if (HashTool.SHA256File(new FileStream(path, FileMode.Open)) == msg.param[2])
                {
                    lvFileBrowser.SelectedItems[0].SubItems[2].Text = "Verified";
                }
                else
                {
                    lvFileBrowser.SelectedItems[0].SubItems[2].Text = "Error";
                }
                break;

            default:
                break;
            }
        }
Ejemplo n.º 24
0
        private string CommonLogin(HttpContext context)
        {
            RSACrypto rsaCrypto = new RSACrypto(ConstValue.AES_KEY_PRIVATE, ConstValue.AES_KEY_PUBLIC);
            var       username  = rsaCrypto.Decrypt(context.Request["username"]);
            var       password  = rsaCrypto.Decrypt(context.Request["password"]);

            var login_result = sso_facade.DoLogin(username, password);

            //登录成功

            if (login_result.IsSucess)
            {
                var cookie = new HttpCookie(ConstValue.COOKIE_KEY_CURRENT_LOGIN_USER, username);
                cookie.Expires = DateTime.Now.AddMinutes(60 * 8);
                HttpContext.Current.Response.Cookies.Add(cookie);
                var ret_model = login_result.Datas as DZAFCPortal.ViewModel.Client.SSOModel.LoginResult_VM;
                //FormsAuthentication..SetAuthCookie(username, false);
                HttpContext.Current.Session.Add($"{ConstValue.SSO.APPLICATION_AUTH_PREFIX_URL}{username}", ret_model.applicationAuths);
            }

            return(JsonConvert.SerializeObject(login_result));
        }
Ejemplo n.º 25
0
        public void Handle(BinaryReader reader, int playerNumber)
        {
            // 服务器端
            if (Main.netMode == 2)
            {
                var    encrypted = reader.ReadString();
                var    player    = Main.player[playerNumber];
                var    splayer   = player.GetServerPlayer();
                string res;
                if (!RSACrypto.DecryptWithTag(encrypted, "ddl", out res))
                {
                    CommandBoardcast.ConsoleError($"玩家 {player.name} 发来的封包 数据异常,可能已被篡改");
                    return;
                }
                long amount;
                long.TryParse(res, out amount);

                if (splayer.Union == null)
                {
                    splayer.SendMessageBox("你没有加入任何一个公会", 120, Color.Yellow);
                    return;
                }
                if (amount <= 0)
                {
                    splayer.SendMessageBox("捐献数量不合法", 120, Color.Red);
                    CommandBoardcast.ConsoleError($"玩家 {player.name} 发来的封包 数据异常,可能已被篡改");
                    return;
                }
                if (amount > splayer.GuCoin)
                {
                    splayer.SendMessageBox("你没有足够的咕币进行捐献", 120, Color.Red);
                    return;
                }
                var union = splayer.Union;
                union.Donate(splayer, amount);
                CommandBoardcast.ConsoleMessage($"玩家 {splayer.Name} 给公会 {union.Name} 捐献了 {amount} 财富");
            }
        }
Ejemplo n.º 26
0
        void HandleEncryptRequest(IPacketMsg packetMsg)
        {
            var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg);

            EUniverse eUniv        = encRequest.Body.Universe;
            uint      protoVersion = encRequest.Body.ProtocolVersion;

            DebugLog.WriteLine("CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
            DebugLog.Assert(protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!");

            byte[] pubKey = KeyDictionary.GetPublicKey(eUniv);

            if (pubKey == null)
            {
                DebugLog.WriteLine("CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
                return;
            }

            ConnectedUniverse = eUniv;

            var encResp = new Msg <MsgChannelEncryptResponse>();

            tempSessionKey = CryptoHelper.GenerateRandomBlock(32);
            byte[] cryptedSessKey = null;

            using (var rsa = new RSACrypto(pubKey))
            {
                cryptedSessKey = rsa.Encrypt(tempSessionKey);
            }

            byte[] keyCrc = CryptoHelper.CRCHash(cryptedSessKey);

            encResp.Write(cryptedSessKey);
            encResp.Write(keyCrc);
            encResp.Write(( uint )0);

            this.Send(encResp);
        }
Ejemplo n.º 27
0
        private static RSAAsymmetricKey GetKey(string keypath)
        {
            if (!File.Exists(keypath))
            {
                var           rsa        = new RSACrypto();
                RSAParameters parameters = rsa.ExportKey(true);

                using (var stream = File.OpenWrite(keypath)) {
                    var writer = new StreamValueWriter(stream);
                    RSAParametersSerializer.Serialize(writer, parameters);
                }
            }

            RSAAsymmetricKey key;

            using (var stream = File.OpenRead(keypath)) {
                var           reader     = new StreamValueReader(stream);
                RSAParameters parameters = RSAParametersSerializer.Deserialize(reader);
                key = new RSAAsymmetricKey(parameters);
            }

            return(key);
        }
Ejemplo n.º 28
0
        public static Task <RSAAsymmetricKey> GetCryptoKeyAsync(CancellationToken cancelToken = default(CancellationToken))
        {
            return(Task.Run(() => {
                RSAAsymmetricKey key = null;
                if (KeyFile.Exists)
                {
                    try {
                        using (var stream = File.OpenRead(KeyFile.FullName)) {
                            var reader = new StreamValueReader(stream);
                            RSAParameters parameters = RSAParametersSerializer.Deserialize(reader);
                            key = new RSAAsymmetricKey(parameters);
                        }
                    } catch (Exception ex) {
                        Trace.TraceWarning("Failed to read key: {0}", ex);
                        KeyFile.Delete();
                    }
                }

                cancelToken.ThrowIfCancellationRequested();

                if (!KeyFile.Exists)
                {
                    var rsa = new RSACrypto();
                    RSAParameters parameters = rsa.ExportKey(true);
                    key = new RSAAsymmetricKey(parameters);

                    cancelToken.ThrowIfCancellationRequested();

                    using (var stream = File.OpenWrite(KeyFile.FullName)) {
                        var writer = new StreamValueWriter(stream);
                        RSAParametersSerializer.Serialize(writer, parameters);
                    }
                }

                return key;
            }, cancelToken));
        }
Ejemplo n.º 29
0
        private string CommonLoginBeta(HttpContext context)
        {
            RSACrypto rsaCrypto = new RSACrypto(ConstValue.AES_KEY_PRIVATE, ConstValue.AES_KEY_PUBLIC);
            var       username  = rsaCrypto.Decrypt(context.Request["username"]);
            var       password  = rsaCrypto.Decrypt(context.Request["password"]);

            var model = sso_facade.DoLoginBeta(username, password);

            //登录成功
            if (model.errorNumber == 0 && model.errors.Count == 0)
            {
                var cookie = new HttpCookie(ConstValue.COOKIE_KEY_CURRENT_LOGIN_USER, username);
                cookie.Expires = DateTime.Now.AddMinutes(60 * 8);
                HttpContext.Current.Response.Cookies.Add(cookie);
                //FormsAuthentication..SetAuthCookie(username, false);
                HttpContext.Current.Session.Add($"{ConstValue.SSO.APPLICATION_AUTH_PREFIX_URL}{username}", model.applicationAuths);

                return(JsonConvert.SerializeObject(new { IsSucess = true }));
            }
            else
            {
                return(JsonConvert.SerializeObject(new { IsSucess = false, Message = $"[{model.errorNumber}]{string.Join(";", model.errors)}" }));
            }
        }
Ejemplo n.º 30
0
        public void EncryptDecryptTests()
        {
            // Arrange
            var sectionText = $@"{{
                ""RSA"": {{
                    ""PublicKey"": ""{publicKey}"",
                    ""PrivateKey"": ""{privateKey}""
                }}
            }}";

            using var stream = new MemoryStream(Encoding.UTF8.GetBytes(sectionText));
            var section = new ConfigurationBuilder().AddJsonStream(stream).Build().GetSection("RSA");

            var crypto = new RSACrypto(section);

            var input = "Hello, Etsoo";

            // Act
            var result        = crypto.Encrypt(input);
            var decryptResult = Encoding.UTF8.GetString(crypto.Decrypt(result));

            // Assert
            Assert.AreEqual(input, decryptResult);
        }
Ejemplo n.º 31
0
        bool HandleEncryptRequest( IPacketMsg packetMsg )
        {
            var encRequest = new Msg<MsgChannelEncryptRequest>( packetMsg );

            EUniverse eUniv = encRequest.Body.Universe;
            uint protoVersion = encRequest.Body.ProtocolVersion;

            DebugLog.WriteLine( "CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion );
            DebugLog.Assert( protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!" );

            byte[] randomChallenge;
            if ( encRequest.Payload.Length >= 16 )
            {
                randomChallenge = encRequest.Payload.ToArray();
            }
            else
            {
                randomChallenge = null;
            }

            byte[] pubKey = KeyDictionary.GetPublicKey( eUniv );

            if ( pubKey == null )
            {
                connection.Disconnect();

                DebugLog.WriteLine( "CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion );
                return false;
            }

            ConnectedUniverse = eUniv;

            var encResp = new Msg<MsgChannelEncryptResponse>();
            
            var tempSessionKey = CryptoHelper.GenerateRandomBlock( 32 );
            byte[] encryptedHandshakeBlob = null;
            
            using ( var rsa = new RSACrypto( pubKey ) )
            {
                if ( randomChallenge != null )
                {
                    var blobToEncrypt = new byte[ tempSessionKey.Length + randomChallenge.Length ];
                    Array.Copy( tempSessionKey, blobToEncrypt, tempSessionKey.Length );
                    Array.Copy( randomChallenge, 0, blobToEncrypt, tempSessionKey.Length, randomChallenge.Length );

                    encryptedHandshakeBlob = rsa.Encrypt( blobToEncrypt );
                }
                else
                {
                    encryptedHandshakeBlob = rsa.Encrypt( tempSessionKey );
                }
            }

            var keyCrc = CryptoHelper.CRCHash( encryptedHandshakeBlob );

            encResp.Write( encryptedHandshakeBlob );
            encResp.Write( keyCrc );
            encResp.Write( ( uint )0 );
            
            if (randomChallenge != null)
            {
                pendingNetFilterEncryption = new NetFilterEncryptionWithHMAC( tempSessionKey );
            }
            else
            {
                pendingNetFilterEncryption = new NetFilterEncryption( tempSessionKey );
            }

            this.Send( encResp );
            return true;
        }
Ejemplo n.º 32
0
 public void Serialize(IValueWriter writer, RSACrypto crypto, bool includePrivate)
 {
 }
Ejemplo n.º 33
0
        bool HandleEncryptRequest(IPacketMsg packetMsg)
        {
            var encRequest = new Msg <MsgChannelEncryptRequest>(packetMsg);

            EUniverse eUniv        = encRequest.Body.Universe;
            uint      protoVersion = encRequest.Body.ProtocolVersion;

            DebugLog.WriteLine("CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
            DebugLog.Assert(protoVersion == 1, "CMClient", "Encryption handshake protocol version mismatch!");

            byte[] randomChallenge;
            if (encRequest.Payload.Length >= 16)
            {
                randomChallenge = encRequest.Payload.ToArray();
            }
            else
            {
                randomChallenge = null;
            }

            byte[] pubKey = KeyDictionary.GetPublicKey(eUniv);

            if (pubKey == null)
            {
                connection.Disconnect();

                DebugLog.WriteLine("CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion);
                return(false);
            }

            ConnectedUniverse = eUniv;

            var encResp = new Msg <MsgChannelEncryptResponse>();

            var tempSessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] encryptedHandshakeBlob = null;

            using (var rsa = new RSACrypto(pubKey))
            {
                if (randomChallenge != null)
                {
                    var blobToEncrypt = new byte[tempSessionKey.Length + randomChallenge.Length];
                    Array.Copy(tempSessionKey, blobToEncrypt, tempSessionKey.Length);
                    Array.Copy(randomChallenge, 0, blobToEncrypt, tempSessionKey.Length, randomChallenge.Length);

                    encryptedHandshakeBlob = rsa.Encrypt(blobToEncrypt);
                }
                else
                {
                    encryptedHandshakeBlob = rsa.Encrypt(tempSessionKey);
                }
            }

            var keyCrc = CryptoHelper.CRCHash(encryptedHandshakeBlob);

            encResp.Write(encryptedHandshakeBlob);
            encResp.Write(keyCrc);
            encResp.Write(( uint )0);

            if (randomChallenge != null)
            {
                pendingNetFilterEncryption = new NetFilterEncryptionWithHMAC(tempSessionKey);
            }
            else
            {
                pendingNetFilterEncryption = new NetFilterEncryption(tempSessionKey);
            }

            this.Send(encResp);
            return(true);
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Encrypts a string with the server's public key and convert it to base64.
 /// </summary>
 /// <param name="s">The string to be encrypted.</param>
 /// <returns>The encrypted string in base64 format.</returns>
 private String PpEncryptAndBase64(String s)
 {
     Contract.Requires(!ReferenceEquals(s, null));
     RSACrypto rsa = new RSACrypto();
     rsa.ImportCspBlob(_publicKey);
     byte[] sEncrypted = rsa.Encrypt(_utf8.GetBytes(s));
     return Convert.ToBase64String(sEncrypted);
 }
Ejemplo n.º 35
0
 public void Deserialize(IValueReader reader, RSACrypto crypto)
 {
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NetworkConnectionProvider" /> class.
        /// </summary>
        /// <param name="target">The target to listen to.</param>
        /// <param name="maxConnections">Maximum number of connections to allow.</param>
        /// <param name="protocols">The protocols to accept.</param>
        /// <param name="enabledHashAlgs">
        /// The signature hash algorithms (in order of preference) to enable.
        /// <c>null</c> or an empty collection will enable all of the signature hash algorithms.
        /// </param>
        /// <exception cref="ArgumentNullException"><paramref name="target"/> or <paramref name="protocols" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="maxConnections"/> is &lt;= 0</exception>
        public NetworkConnectionProvider(IEnumerable<Protocol> protocols, Target target, int maxConnections, IEnumerable<string> enabledHashAlgs = null)
        {
            if (protocols == null)
                throw new ArgumentNullException ("protocols");
            if (target == null)
                throw new ArgumentNullException ("target");
            if (maxConnections <= 0)
                throw new ArgumentOutOfRangeException ("maxConnections");

            this.protocols = protocols;
            this.target = target;
            MaxConnections = maxConnections;
            this.serverConnections = new List<NetworkServerConnection> (maxConnections);

            if (protocols.Any (p => p != null && p.RequiresHandshake))
            {
                ThreadPool.QueueUserWorkItem (s =>
                {
                    Task encryptKeyGen = Task.Factory.StartNew (() =>
                    {
                        this.pkEncryption = new RSACrypto();
                        this.publicEncryptionKey = this.pkEncryption.ExportKey (false);
                    });

                    Task authKeyGen = Task.Factory.StartNew (() =>
                    {
                        this.authentication = new RSACrypto();
                        if (this.authenticationKey == null)
                            this.authenticationKey = this.authentication.ExportKey (true);
                        else
                            this.authentication.ImportKey (this.authenticationKey);

                        this.publicAuthenticationKey = this.authentication.ExportKey (false);

                        if (enabledHashAlgs == null || !enabledHashAlgs.Any())
                            this.enabledHashAlgorithms.AddRange (this.authentication.SupportedHashAlgs);
                        else // Need to maintain preference order
                            this.enabledHashAlgorithms.AddRange (enabledHashAlgs.Where (a => this.authentication.SupportedHashAlgs.Contains (a)));
                    });

                    authKeyGen.Wait();
                    encryptKeyGen.Wait();

                    this.keyWait.Set();
                });
            }
            else
                this.keyWait.Set();
        }
Ejemplo n.º 37
0
        protected override void OnTempestMessageReceived(MessageEventArgs e)
        {
            switch (e.Message.MessageType)
            {
                case (ushort)TempestMessageType.Ping:
                    var ping = (PingMessage)e.Message;
                    if (PingFrequency == 0 || this.activityTimer == null)
                    {
                        if (this.activityTimer != null)
                            this.activityTimer.Dispose();

                        if (ping.Interval != 0)
                        {
                            this.activityTimer = new Tempest.Timer (100);
                            this.activityTimer.TimesUp += OnActivityTimer;
                            this.activityTimer.Start();
                        }
                    }
                    else if (ping.Interval != PingFrequency)
                        this.activityTimer.Interval = ping.Interval;

                    base.OnTempestMessageReceived (e);
                    break;

                case (ushort)TempestMessageType.AcknowledgeConnect:
                    var msg = (AcknowledgeConnectMessage)e.Message;

                    this.protocols = this.protocols.Values.Intersect (msg.EnabledProtocols).ToDictionary (pr => pr.id);
                    ConnectionId = msg.ConnectionId;

                    this.serverEncryption = new RSACrypto();
                    this.serverEncryption.ImportKey (msg.PublicEncryptionKey);
                    this.serverEncryptionKey = msg.PublicEncryptionKey;

                    var encryption = new AesManaged { KeySize = 256 };
                    encryption.GenerateKey();

                    BufferValueWriter authKeyWriter = new BufferValueWriter (new byte[1600]);
                    this.publicAuthenticationKey.Serialize (authKeyWriter, this.serverEncryption);

                    this.serializer.AES = encryption;
                    this.serializer.HMAC = new HMACSHA256 (encryption.Key);

                    SendAsync (new FinalConnectMessage
                    {
                        AESKey = this.serverEncryption.Encrypt (encryption.Key),
                        PublicAuthenticationKeyType = this.publicAuthenticationKey.GetType(),
                        PublicAuthenticationKey = authKeyWriter.ToArray()
                    });

                    break;

                case (ushort)TempestMessageType.Connected:
                    var connected = (ConnectedMessage) e.Message;
                    ConnectionId = connected.ConnectionId;

                    OnConnected (new ClientConnectionEventArgs (this));

                    var tcs = Interlocked.Exchange (ref this.connectCompletion, null);
                    if (tcs != null)
                        tcs.TrySetResult (new ClientConnectionResult (ConnectionResult.Success, this.serverAuthenticationKey));

                    break;

                default:
                    base.OnTempestMessageReceived(e);
                    break;
            }
        }
Ejemplo n.º 38
0
        ////////////////////////////////////////////////////
        // STEAM WEB INTERFACE
        ////////////////////////////////////////////////////

        // Copied this shit straight from ArchisSteamFarm, credit to him
        public override async void LoginWebInterface(ulong steamID)
        {
            if (!IsAuthenticated)
            {
                SteamUser.WebAPIUserNonceCallback callback;

                try
                {
                    callback = await _steamUser.RequestWebAPIUserNonce();
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Unable to request Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                if (string.IsNullOrWhiteSpace(callback?.Nonce))
                {
                    _log.Error("Received empty Web API Nonce. Titan won't be able to execute Web API actions.");
                    return;
                }

                var    sessionID  = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));
                var    sessionKey = CryptoHelper.GenerateRandomBlock(32);
                byte[] cryptedSessionKey;

                using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(_steamClient.Universe)))
                {
                    cryptedSessionKey = rsa.Encrypt(sessionKey);
                }

                var loginKey = new byte[callback.Nonce.Length];
                Array.Copy(Encoding.ASCII.GetBytes(callback.Nonce), loginKey, callback.Nonce.Length);

                // AES encrypt the login key with our session key
                var cryptedLoginKey = CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

                if (!Titan.Instance.WebHandle.AuthentificateUser(
                        steamID, cryptedLoginKey, cryptedSessionKey, out var result
                        ))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                var token       = result["token"].Value;
                var secureToken = result["tokensecure"].Value;

                if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(secureToken))
                {
                    _log.Error("Failed to authentificate with Web API Nonce. " +
                               "Titan won't be able to execute Web API actions.");
                    return;
                }

                Cookies.Add("sessionid", sessionID);
                Cookies.Add("steamLogin", token);
                Cookies.Add("steamLoginSecure", secureToken);

                if (!Titan.Instance.Options.Secure)
                {
                    _log.Debug("Authorized with Steam Web API. Session ID: {id}", sessionID);
                }

                _log.Information("Successfully authorized with Steam Web API.");

                IsAuthenticated = true;
            }
        }
Ejemplo n.º 39
0
        internal async Task <bool> Init(ulong steamID, EUniverse universe, string webAPIUserNonce, string parentalPin)
        {
            if ((steamID == 0) || (universe == EUniverse.Invalid) || string.IsNullOrEmpty(webAPIUserNonce) || string.IsNullOrEmpty(parentalPin))
            {
                Logging.LogNullError(nameof(steamID) + " || " + nameof(universe) + " || " + nameof(webAPIUserNonce) + " || " + nameof(parentalPin), Bot.BotName);
                return(false);
            }

            SteamID = steamID;

            string sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(steamID.ToString()));

            // Generate an AES session key
            byte[] sessionKey = SteamKit2.CryptoHelper.GenerateRandomBlock(32);

            // RSA encrypt it with the public key for the universe we're on
            byte[] cryptedSessionKey;
            using (RSACrypto rsa = new RSACrypto(KeyDictionary.GetPublicKey(universe))) {
                cryptedSessionKey = rsa.Encrypt(sessionKey);
            }

            // Copy our login key
            byte[] loginKey = new byte[webAPIUserNonce.Length];
            Array.Copy(Encoding.ASCII.GetBytes(webAPIUserNonce), loginKey, webAPIUserNonce.Length);

            // AES encrypt the loginkey with our session key
            byte[] cryptedLoginKey = SteamKit2.CryptoHelper.SymmetricEncrypt(loginKey, sessionKey);

            // Do the magic
            Logging.LogGenericInfo("Logging in to ISteamUserAuth...", Bot.BotName);

            KeyValue authResult;

            using (dynamic iSteamUserAuth = WebAPI.GetInterface("ISteamUserAuth")) {
                iSteamUserAuth.Timeout = Timeout;

                try {
                    authResult = iSteamUserAuth.AuthenticateUser(
                        steamid: steamID,
                        sessionkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedSessionKey, 0, cryptedSessionKey.Length)),
                        encrypted_loginkey: Encoding.ASCII.GetString(WebUtility.UrlEncodeToBytes(cryptedLoginKey, 0, cryptedLoginKey.Length)),
                        method: WebRequestMethods.Http.Post,
                        secure: !Program.GlobalConfig.ForceHttp
                        );
                } catch (Exception e) {
                    Logging.LogGenericException(e, Bot.BotName);
                    return(false);
                }
            }

            if (authResult == null)
            {
                Logging.LogNullError(nameof(authResult), Bot.BotName);
                return(false);
            }

            string steamLogin = authResult["token"].Value;

            if (string.IsNullOrEmpty(steamLogin))
            {
                Logging.LogNullError(nameof(steamLogin), Bot.BotName);
                return(false);
            }

            string steamLoginSecure = authResult["tokensecure"].Value;

            if (string.IsNullOrEmpty(steamLoginSecure))
            {
                Logging.LogNullError(nameof(steamLoginSecure), Bot.BotName);
                return(false);
            }

            WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHost));
            WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHost));
            WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHost));

            Logging.LogGenericInfo("Success!", Bot.BotName);

            // Unlock Steam Parental if needed
            if (!parentalPin.Equals("0"))
            {
                if (!await UnlockParentalAccount(parentalPin).ConfigureAwait(false))
                {
                    return(false);
                }
            }

            Ready = true;
            LastSessionRefreshCheck = DateTime.Now;
            return(true);
        }
Ejemplo n.º 40
0
        public UdpConnectionProvider(int port, IEnumerable<Protocol> protocols, RSAAsymmetricKey authKey)
            : base(protocols, port)
        {
            if (protocols == null)
                throw new ArgumentNullException ("protocols");
            if (authKey == null)
                throw new ArgumentNullException ("authKey");
            if (port <= 0)
                throw new ArgumentOutOfRangeException ("port");

            this.crypto = new RSACrypto();
            this.crypto.ImportKey (authKey);
            this.authKey = authKey;

            ValidateProtocols (this.protocols.Values);
        }
Ejemplo n.º 41
0
        void HandleEncryptRequest( IPacketMsg packetMsg )
        {
            var encRequest = new Msg<MsgChannelEncryptRequest>( packetMsg );

            EUniverse eUniv = encRequest.Body.Universe;
            uint protoVersion = encRequest.Body.ProtocolVersion;

            DebugLog.WriteLine( "CMClient", "Got encryption request. Universe: {0} Protocol ver: {1}", eUniv, protoVersion );

            byte[] pubKey = KeyDictionary.GetPublicKey( eUniv );

            if ( pubKey == null )
            {
                DebugLog.WriteLine( "CMClient", "HandleEncryptionRequest got request for invalid universe! Universe: {0} Protocol ver: {1}", eUniv, protoVersion );
                return;
            }

            ConnectedUniverse = eUniv;

            var encResp = new Msg<MsgChannelEncryptResponse>();

            tempSessionKey = CryptoHelper.GenerateRandomBlock( 32 );
            byte[] cryptedSessKey = null;

            using ( var rsa = new RSACrypto( pubKey ) )
            {
                cryptedSessKey = rsa.Encrypt( tempSessionKey );
            }

            byte[] keyCrc = CryptoHelper.CRCHash( cryptedSessKey );

            encResp.Write( cryptedSessKey );
            encResp.Write( keyCrc );
            encResp.Write( ( uint )0 );

            this.Send( encResp );
        }
Ejemplo n.º 42
0
 static NetworkProviderTests()
 {
     var rsa = new RSACrypto();
     key = rsa.ExportKey (true);
 }
Ejemplo n.º 43
0
        protected override void Recycle()
        {
            if (AutoSizeSendBufferLimit)
                Interlocked.Add (ref sendBufferLimit, AutoSizeFactor * -1);

            this.serverEncryption = null;
            this.serverEncryptionKey = null;
            this.serverAuthenticationKey = null;

            base.Recycle();
        }
Ejemplo n.º 44
0
        public static async Task <bool> AuthenticateUser()
        {
            SteamUser.WebAPIUserNonceCallback nonce;

            try
            {
                nonce = await Steam.Instance.User.RequestWebAPIUserNonce();
            }
            catch (Exception e)
            {
                IsAuthorized = false;

                Log.WriteWarn("WebAuth", "Failed to get nonce: {0}", e.Message);

                return(false);
            }

            // 32 byte random blob of data
            var sessionKey = CryptoHelper.GenerateRandomBlock(32);

            byte[] encryptedSessionKey;

            // ... which is then encrypted with RSA using the Steam system's public key
            using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(Steam.Instance.Client.Universe)))
            {
                encryptedSessionKey = rsa.Encrypt(sessionKey);
            }

            // users hashed loginkey, AES encrypted with the sessionkey
            var encryptedLoginKey = CryptoHelper.SymmetricEncrypt(Encoding.ASCII.GetBytes(nonce.Nonce), sessionKey);

            using (dynamic userAuth = WebAPI.GetAsyncInterface("ISteamUserAuth"))
            {
                KeyValue result;

                try
                {
                    result = await userAuth.AuthenticateUser(
                        steamid : Steam.Instance.Client.SteamID.ConvertToUInt64(),
                        sessionkey : WebHelpers.UrlEncode(encryptedSessionKey),
                        encrypted_loginkey : WebHelpers.UrlEncode(encryptedLoginKey),
                        method : "POST",
                        secure : true
                        );
                }
                catch (HttpRequestException e)
                {
                    IsAuthorized = false;

                    Log.WriteWarn("WebAuth", "Failed to authenticate: {0}", e.Message);

                    return(false);
                }

                File.WriteAllText(Path.Combine(Application.Path, "files", ".support", "cookie.txt"), $"steamLogin={result["token"].AsString()}; steamLoginSecure={result["tokensecure"].AsString()}");

                Cookies = new CookieContainer();
                Cookies.Add(new Cookie("steamLogin", result["token"].AsString(), "/", "store.steampowered.com"));
                Cookies.Add(new Cookie("steamLoginSecure", result["tokensecure"].AsString(), "/", "store.steampowered.com"));
            }

            IsAuthorized = true;

            Log.WriteInfo("WebAuth", "Authenticated");

            if (!Settings.IsFullRun)
            {
                await AccountInfo.RefreshAppsToIdle();
            }

            return(true);
        }