Example #1
0
    /// <summary>
    ///     A string extension method that encrypts the string.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="key">The key.</param>
    /// <returns>The encrypted string.</returns>
    /// <example>
    ///     <code>
    ///           using Microsoft.VisualStudio.TestTools.UnitTesting;
    ///           using Z.ExtensionMethods;
    ///           
    ///           namespace ExtensionMethods.Examples
    ///           {
    ///               [TestClass]
    ///               public class System_String_EncryptRSA
    ///               {
    ///                   [TestMethod]
    ///                   public void EncryptRSA()
    ///                   {
    ///                       // Type
    ///                       string @this = &quot;Fizz&quot;;
    ///           
    ///                       // Examples
    ///                       string value = @this.EncryptRSA(&quot;Buzz&quot;); // return Encrypted string;
    ///           
    ///                       // Unit Test
    ///                       Assert.AreEqual(&quot;Fizz&quot;, value.DecryptRSA(&quot;Buzz&quot;));
    ///                   }
    ///               }
    ///           }
    ///     </code>
    /// </example>
    public static string EncryptRSA(this string @this, string key) {
        var cspp = new CspParameters {KeyContainerName = key};
        var rsa = new RSACryptoServiceProvider(cspp) {PersistKeyInCsp = true};
        byte[] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(@this), true);

        return BitConverter.ToString(bytes);
    }
Example #2
0
 private static byte[] Encrypt(string publicKeyXml, byte[] bytes, RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048)
 {
     byte[] encryptedBytes;
     using (var RSA = new RSACryptoServiceProvider((int) rsaKeyLength))
     {
         RSA.FromXmlString(publicKeyXml);
         encryptedBytes = RSA.Encrypt(bytes, DoOAEPPadding);
     }
     return encryptedBytes;
 }
Example #3
0
 public static string RSAEncrypt(string plaintext)
 {
     CspParameters param = new CspParameters();
     param.KeyContainerName = "PowerGridIndia";
     using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
     {
         byte[] plaindata = System.Text.Encoding.Default.GetBytes(plaintext);
         byte[] encryptdata = rsa.Encrypt(plaindata, false);
         string encryptstring = Convert.ToBase64String(encryptdata);
         return encryptstring;
     }
 }
Example #4
0
    public static void Main(String[] args) {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RijndaelManaged aes = new RijndaelManaged();
        aes.KeySize = 128; //  192;
        aes.Key = new byte[] {0xC7, 0x42, 0xD1, 0x37, 0x4B, 0xAC, 0xFE, 0x94,
                              0x9D, 0x59, 0x79, 0x92, 0x71, 0x48, 0xD6, 0x8E};
//                              ,1,2,3,4,5,6,7,8};

        byte[] aesKey = aes.Key;
        if (args.Length > 0) {
            FileStream fs = new FileStream(args[0], FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            String xmlString = sr.ReadToEnd();
            rsa.FromXmlString(xmlString);
        } else {
            FileStream fs = new FileStream("rsa.xml", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(rsa.ToXmlString(true));
            sw.Close();
        }
        Console.WriteLine("RSA Key is:\n"+rsa.ToXmlString(true));

        Console.WriteLine("AES Key is:");
        PrintByteArray(aesKey);
        byte[] encryptedKey1 = rsa.Encrypt(aesKey, true);
        Console.WriteLine("Encrypted AES Key is:");
        PrintByteArray(encryptedKey1);
        byte[] decryptedKey1 = rsa.Decrypt(encryptedKey1, true);
        Console.WriteLine("Decrypted AES Key is:");
        PrintByteArray(decryptedKey1);

        byte[] encryptedKey2 = rsa.Encrypt(aesKey, false);
        Console.WriteLine("Encrypted2 AES Key is:");
        PrintByteArray(encryptedKey2);
        byte[] decryptedKey2 = rsa.Decrypt(encryptedKey2, false);
        Console.WriteLine("Decrypted AES Key is:");
        PrintByteArray(decryptedKey2);

    }
Example #5
0
        public static void RsaCryptRoundtrip()
        {
            byte[] crypt;
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                crypt = rsa.Encrypt(TestData.HelloBytes, true);
                output = rsa.Decrypt(crypt, true);
            }

            Assert.NotEqual(crypt, output);
            Assert.Equal(TestData.HelloBytes, output);
        }
Example #6
0
        public static void RsaDecryptAfterExport()
        {
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true);

                // Export the key, this should not clear/destroy the key.
                RSAParameters ignored = rsa.ExportParameters(true);
                output = rsa.Decrypt(crypt, true);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
Example #7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var code = Request.QueryString["code"];


        //send request to github server to get access token
        HttpWebRequest req = WebRequest.Create("https://github.com/login/oauth/access_token?client_id=TODO:<your own client id>&client_secret=TODO:<your own client secret>&code=" + code) as HttpWebRequest;
        req.Method = "POST";
        HttpWebResponse rsps = req.GetResponse() as HttpWebResponse;
        var str = new StreamReader(rsps.GetResponseStream()).ReadToEnd();
        Match m = Regex.Match(str, "access_token=([^&]+)&token_type=([^&]+)");


        //RSA encrypt access token with public key from browser side
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RSAParameters publicKey = new RSAParameters();
        publicKey.Modulus = literal2bytes(Request.Cookies["modulus"].Value);
        publicKey.Exponent = literal2bytes(Request.Cookies["exponent"].Value);
        rsa.ImportParameters(publicKey);
        byte[] result = rsa.Encrypt(Encoding.UTF8.GetBytes(m.Groups[1].ToString()), false);
        StringBuilder access_token = new StringBuilder();
        for (var i = 0; i < result.Length; i++)
        {
            access_token.Append(result[i].ToString("x2"));
        }

        //write encrypted access_token back into cookie
        HttpCookie cookie = new HttpCookie("access_token");
        DateTime dt = DateTime.Now;
        TimeSpan ts = new TimeSpan(0, 0, 0, 0);
        cookie.Expires = dt.Add(ts);
        cookie.Value = access_token.ToString();
        Response.AppendCookie(cookie);


        cookie = new HttpCookie("token_type");
        dt = DateTime.Now;
        ts = new TimeSpan(0, 0, 0, 0);
        cookie.Expires = dt.Add(ts);
        cookie.Value = m.Groups[2].ToString();
        Response.AppendCookie(cookie);

        //now jump back, only the browser side could decrypt the access_token from cookie
        Response.Redirect("TODO:<your own address>");
    }
Example #8
0
 /// <summary>
 /// 字符串加密
 /// </summary>
 /// <param name="source">源字符串 明文</param>
 /// <param name="publicKey">公匙或私匙</param>
 /// <returns>加密遇到错误将会返回原字符串</returns>
 public static string EncryptString(string source, string key)
 {
     string encryptString = string.Empty;
     try
     {
         if (!CheckSourceValidate(source))
         {
             throw new Exception("source string too long");
         }
         RSACryptoServiceProvider.UseMachineKeyStore = true;
         RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
         rsaProvider.FromXmlString(FromBase64Key(key));
         byte[] data = rsaProvider.Encrypt(System.Text.Encoding.ASCII.GetBytes(source), false);
         encryptString = BytesToHexString(data);
     }
     catch{ }
     return encryptString;
 }
Example #9
0
    public static byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo)
    {
        try
        {
            byte[] encryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.ImportParameters(RSAKeyInfo);
                encryptedData = RSA.Encrypt(DataToEncrypt, false);
            }
            return encryptedData;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }
    }
Example #10
0
 internal static byte[] Encrypt(this RSACryptoServiceProvider rsa, byte[] data)
 {
     return(rsa.Encrypt(data, true));
 }
Example #11
0
        public static void LargeKeyCryptRoundtrip()
        {
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                try
                {
                    rsa.ImportParameters(TestData.RSA16384Params);
                }
                catch (CryptographicException)
                {
                    // The key is pretty big, perhaps it was refused.
                    return;
                }

                byte[] crypt = rsa.Encrypt(TestData.HelloBytes, true);

                Assert.Equal(rsa.KeySize, crypt.Length * 8);

                output = rsa.Decrypt(crypt, true);
            }

            Assert.Equal(TestData.HelloBytes, output);
        }
Example #12
0
        /// <summary>
        /// Executes the login by using the Steam Website.
        /// </summary>
        public static CookieCollection DoLogin(string username, string password)
        {
            var data = new NameValueCollection();

            data.Add("username", username);
            string    response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, null, false);
            GetRsaKey rsaJSON  = JsonConvert.DeserializeObject <GetRsaKey> (response);


            // Validate
            if (rsaJSON.success != true)
            {
                return(null);
            }

            //RSA Encryption
            RSACryptoServiceProvider rsa           = new RSACryptoServiceProvider();
            RSAParameters            rsaParameters = new RSAParameters();

            rsaParameters.Exponent = HexToByte(rsaJSON.publickey_exp);
            rsaParameters.Modulus  = HexToByte(rsaJSON.publickey_mod);

            rsa.ImportParameters(rsaParameters);

            byte[] bytePassword            = Encoding.ASCII.GetBytes(password);
            byte[] encodedPassword         = rsa.Encrypt(bytePassword, false);
            string encryptedBase64Password = Convert.ToBase64String(encodedPassword);


            SteamResult      loginJson = null;
            CookieCollection cookies;
            string           steamGuardText = "";
            string           steamGuardId   = "";

            do
            {
                Console.WriteLine("SteamWeb: Logging In...");

                bool captcha    = loginJson != null && loginJson.captcha_needed == true;
                bool steamGuard = loginJson != null && loginJson.emailauth_needed == true;

                string time   = Uri.EscapeDataString(rsaJSON.timestamp);
                string capGID = loginJson == null ? null : Uri.EscapeDataString(loginJson.captcha_gid);

                data = new NameValueCollection();
                data.Add("password", encryptedBase64Password);
                data.Add("username", username);

                // Captcha
                string capText = "";
                if (captcha)
                {
                    Console.WriteLine("SteamWeb: Captcha is needed.");
                    System.Diagnostics.Process.Start("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid);
                    Console.WriteLine("SteamWeb: Type the captcha:");
                    capText = Uri.EscapeDataString(Console.ReadLine());
                }

                data.Add("captchagid", captcha ? capGID : "");
                data.Add("captcha_text", captcha ? capText : "");
                // Captcha end

                // SteamGuard
                if (steamGuard)
                {
                    Console.WriteLine("SteamWeb: SteamGuard is needed.");
                    Console.WriteLine("SteamWeb: Type the code:");
                    steamGuardText = Uri.EscapeDataString(Console.ReadLine());
                    steamGuardId   = loginJson.emailsteamid;
                }

                data.Add("emailauth", steamGuardText);
                data.Add("emailsteamid", steamGuardId);
                // SteamGuard end

                data.Add("rsatimestamp", time);

                HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, null, false);

                StreamReader reader = new StreamReader(webResponse.GetResponseStream());
                string       json   = reader.ReadToEnd();

                loginJson = JsonConvert.DeserializeObject <SteamResult> (json);

                cookies = webResponse.Cookies;
            } while (loginJson.captcha_needed == true || loginJson.emailauth_needed == true);


            if (loginJson.success == true)
            {
                CookieContainer c = new CookieContainer();
                foreach (Cookie cookie in cookies)
                {
                    c.Add(cookie);
                }
                SubmitCookies(c);
                return(cookies);
            }
            else
            {
                Console.WriteLine("SteamWeb Error: " + loginJson.message);
                return(null);
            }
        }
Example #13
0
        private void ThreadHandler()
        {
            networkStream = client.GetStream();

            protocolSI = new ProtocolSI();

            // Repete ate receber a mensagem de fim de transmissao
            while (protocolSI.GetCmdType() != ProtocolSICmdType.EOT)
            {
                try
                {
                    // Recebe as mensagens do cliente
                    int bytesRead = networkStream.Read(protocolSI.Buffer, 0, protocolSI.Buffer.Length);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Erro: " + ex);
                    return;
                }

                byte[] ack;

                // Verifica o tipo de mensagem
                switch (protocolSI.GetCmdType())
                {
                // Se for uma mensagem do chat
                case ProtocolSICmdType.DATA:
                {
                    byte[] msgBytes = null;

                    try
                    {
                        msgBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    string msgRecebida = Decifra(msgBytes);

                    string hash = msgRecebida.Substring(0, msgRecebida.IndexOf(" "));
                    msgRecebida = msgRecebida.Substring(msgRecebida.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(msgRecebida, hash))
                    {
                        string msg = user.Username + ": " + msgRecebida;
                        Console.WriteLine("    Cliente " + msg);

                        // Guarda os dados no ficheiro
                        FileHandler.SaveData(currentRoom.ToString(), msg);

                        try
                        {
                            // Envia o ACK para o cliente
                            ack = protocolSI.Make(ProtocolSICmdType.ACK);
                            networkStream.Write(ack, 0, ack.Length);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Erro: " + ex);
                            return;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                // Se for para fechar a comunicacao
                case ProtocolSICmdType.EOT:
                {
                    try
                    {
                        // Envia o ACK para o cliente
                        ack = protocolSI.Make(ProtocolSICmdType.ACK);
                        networkStream.Write(ack, 0, ack.Length);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }
                } break;

                // Envia log do chat
                case ProtocolSICmdType.USER_OPTION_1:
                {
                    string log = FileHandler.LoadData(currentRoom.ToString());

                    // Variavel auxiliar
                    string stringChunk = "";

                    // Tamanho da resposta
                    int stringLenght = log.Length;

                    for (int i = 0; i < log.Length; i = i + CHUNKSIZE)
                    {
                        if (CHUNKSIZE > stringLenght)
                        {
                            stringChunk = log.Substring(i);
                        }
                        else
                        {
                            stringLenght = stringLenght - CHUNKSIZE;
                            stringChunk  = log.Substring(i, CHUNKSIZE);
                        }

                        // Cifra a mensagem
                        byte[] msgCifrada = Cifra(stringChunk);

                        Thread.Sleep(100);

                        Send(msgCifrada, ProtocolSICmdType.DATA);
                    }
                    Thread.Sleep(100);

                    try
                    {
                        // Envia EOF
                        byte[] eof = protocolSI.Make(ProtocolSICmdType.EOF);
                        networkStream.Write(eof, 0, eof.Length);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }
                } break;

                // Troca de chaves
                case ProtocolSICmdType.USER_OPTION_2:
                {
                    string pk = "";
                    try
                    {
                        // Recebe a chave publica do cliente
                        pk = protocolSI.GetStringFromData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    string hash = pk.Substring(0, pk.IndexOf(" "));
                    pk = pk.Substring(pk.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(pk, hash))
                    {
                        // Cria uma chave simétrica
                        aes = new AesCryptoServiceProvider();

                        // Guarda a chave simetrica
                        key = aes.Key;
                        iv  = aes.IV;

                        // Cria chave publica do cliente para poder encriptar
                        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                        rsa.FromXmlString(pk);

                        // Cria um array com as duas keys
                        byte[] keys = Encoding.UTF8.GetBytes(Convert.ToBase64String(key) + " " + Convert.ToBase64String(iv));

                        // Encripta a key e o iv
                        byte[] keyEnc = rsa.Encrypt(keys, true);

                        Send(keyEnc, ProtocolSICmdType.USER_OPTION_2);
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                } break;

                // Login
                case ProtocolSICmdType.USER_OPTION_3:
                {
                    // Recebe os dados do cliente
                    byte[] credenciaisBytes = protocolSI.GetData();

                    string credenciais = Decifra(credenciaisBytes);

                    string hash = credenciais.Substring(0, credenciais.IndexOf(" "));
                    credenciais = credenciais.Substring(credenciais.IndexOf(" ") + 1);
                    string username = credenciais.Substring(0, credenciais.IndexOf(" "));
                    string password = credenciais.Substring(credenciais.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(username + " " + password, hash))
                    {
                        // Verifica se o utilizador existe na base de dados
                        User utilizador = (from User in spksContainer.Users
                                           where User.Username.Equals(username)
                                           select User).FirstOrDefault();

                        int state;

                        // Utilizador nao existe ou nome de utilizador errado
                        if (utilizador == null)
                        {
                            state = 2;
                        }
                        // Password errada
                        else if (utilizador.Password != Common.HashPassword(password, utilizador.Salt))
                        {
                            state = 1;
                        }
                        // Utilizador existe e passowrd está certa
                        else
                        {
                            user  = utilizador;
                            state = 0;
                        }

                        byte[] msgCifrada = Cifra(state.ToString());

                        Send(msgCifrada, ProtocolSICmdType.USER_OPTION_3);
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                // Cria conta
                case ProtocolSICmdType.USER_OPTION_4:
                {
                    byte[] credenciaisBytes;
                    try
                    {
                        // Recebe os dados do cliente
                        credenciaisBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    // Decifra e guarda as credenciais
                    string credenciais = Decifra(credenciaisBytes);

                    string hash = credenciais.Substring(0, credenciais.IndexOf(" "));
                    credenciais = credenciais.Substring(credenciais.IndexOf(" ") + 1);
                    string username = credenciais.Substring(0, credenciais.IndexOf(" "));
                    string password = credenciais.Substring(credenciais.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(username + " " + password, hash))
                    {
                        User newUser = new User(username, password);
                        spksContainer.Users.Add(newUser);
                        spksContainer.SaveChanges();

                        Console.WriteLine("Utilizador " + username + " criado");
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                // Jogo
                case ProtocolSICmdType.USER_OPTION_5:
                {
                    byte[] msgBytes = null;

                    try
                    {
                        msgBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    // Decifra e guarda jogada
                    string jogada = Decifra(msgBytes);

                    string hash = jogada.Substring(0, jogada.IndexOf(" "));
                    jogada = jogada.Substring(jogada.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(jogada, hash))
                    {
                        Console.WriteLine("    Cliente " + user.Username + " jogou: " + jogada);

                        if (currentRoom.GetPlayer1Name() == user.Username)
                        {
                            currentRoom.Player1Play = jogada;
                        }
                        else
                        {
                            currentRoom.Player2Play = jogada;
                        }

                        try
                        {
                            // Envia o ACK para o cliente
                            ack = protocolSI.Make(ProtocolSICmdType.ACK);
                            networkStream.Write(ack, 0, ack.Length);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Erro: " + ex);
                            return;
                        }

                        while (true)
                        {
                            if (lastState != currentRoom.GameState)
                            {
                                string msg = currentRoom.Player1Pontos.ToString() + " " + currentRoom.Player2Pontos.ToString() + " " + currentRoom.GameState;
                                // BUG: Inserir breakpoint na linha de baixo para o jogo funcionar
                                Send(Cifra(msg), ProtocolSICmdType.USER_OPTION_5);
                                lastState = currentRoom.GameState;
                                break;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                } break;

                // Adiciona o jogador a sala
                case ProtocolSICmdType.USER_OPTION_6:
                {
                    byte[] msgBytes = null;

                    try
                    {
                        msgBytes = protocolSI.GetData();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Erro: " + ex);
                        return;
                    }

                    // Decifra e guarda sala
                    string sala = Decifra(msgBytes);

                    string hash = sala.Substring(0, sala.IndexOf(" "));
                    sala = sala.Substring(sala.IndexOf(" ") + 1);

                    if (Common.ValidacaoDados(sala, hash))
                    {
                        // Verifica existem salas
                        if (Game.rooms.Count == 0)
                        {
                            CriaSala(sala);
                        }
                        else
                        {
                            try
                            {
                                foreach (Room room in Game.rooms)
                                {
                                    if (room.ToString() == sala)
                                    {
                                        JuntaSala(room);
                                    }
                                    else if (room == Game.rooms.Last() && room.ToString() == sala)
                                    {
                                        JuntaSala(room);
                                        break;
                                    }
                                    else if (room == Game.rooms.Last())
                                    {
                                        CriaSala(sala);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine("Hash não é igual");
                    }
                }
                break;

                default:
                    break;
                }
            }

            // Fecha as conecoes
            networkStream.Close();
            client.Close();

            Console.WriteLine("O Cliente {0} desconnectou-se", clientId);
        }
Example #14
0
        /// <summary>
        /// Executes the login by using the Steam Website.
        /// This Method is not used by Steambot repository, but it could be very helpful if you want to build a own Steambot or want to login into steam services like backpack.tf/csgolounge.com.
        /// Updated: 10-02-2015.
        /// </summary>
        /// <param name="username">Your Steam username.</param>
        /// <param name="password">Your Steam password.</param>
        /// <returns>A bool containing a value, if the login was successful.</returns>
        public bool DoLogin(string username, string password)
        {
            var data = new NameValueCollection {
                { "username", username }
            };
            // First get the RSA key with which we will encrypt our password.
            string    response = Fetch("https://steamcommunity.com/login/getrsakey", "POST", data, false);
            GetRsaKey rsaJson  = JsonConvert.DeserializeObject <GetRsaKey>(response);

            Console.WriteLine(rsaJson.publickey_exp);
            Console.WriteLine(rsaJson.publickey_mod);

            // Validate, if we could get the rsa key.
            if (!rsaJson.success)
            {
                return(false);
            }

            // RSA Encryption.
            RSACryptoServiceProvider rsa           = new RSACryptoServiceProvider();
            RSAParameters            rsaParameters = new RSAParameters
            {
                Exponent = HexToByte(rsaJson.publickey_exp),
                Modulus  = HexToByte(rsaJson.publickey_mod)
            };

            rsa.ImportParameters(rsaParameters);

            // Encrypt the password and convert it.
            byte[] bytePassword            = Encoding.ASCII.GetBytes(password);
            byte[] encodedPassword         = rsa.Encrypt(bytePassword, false);
            string encryptedBase64Password = Convert.ToBase64String(encodedPassword);

            SteamResult      loginJson = null;
            CookieCollection cookieCollection;
            string           steamGuardText = "";
            string           steamGuardId   = "";

            // Do this while we need a captcha or need email authentification. Probably you have misstyped the captcha or the SteamGaurd code if this comes multiple times.
            do
            {
                Console.WriteLine("SteamWeb: Logging In...");

                bool captcha    = loginJson != null && loginJson.captcha_needed;
                bool steamGuard = loginJson != null && loginJson.emailauth_needed;

                string time = Uri.EscapeDataString(rsaJson.timestamp);

                string capGid = string.Empty;
                // Response does not need to send if captcha is needed or not.
                // ReSharper disable once MergeSequentialChecks
                if (loginJson != null && loginJson.captcha_gid != null)
                {
                    capGid = Uri.EscapeDataString(loginJson.captcha_gid);
                }

                data = new NameValueCollection {
                    { "password", encryptedBase64Password }, { "username", username }
                };

                // Captcha Check.
                string capText = "";
                if (captcha)
                {
                    Console.WriteLine("SteamWeb: Captcha is needed.");
                    System.Diagnostics.Process.Start("firefox.exe", "https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid);
                    Console.WriteLine("SteamWeb: Type the captcha:");
                    string consoleText = Console.ReadLine();
                    if (!string.IsNullOrEmpty(consoleText))
                    {
                        capText = Uri.EscapeDataString(consoleText);
                    }
                }

                data.Add("captchagid", captcha ? capGid : "");
                data.Add("captcha_text", captcha ? capText : "");
                // Captcha end.
                // Added Header for two factor code.
                data.Add("twofactorcode", "");

                // Added Header for remember login. It can also set to true.
                data.Add("remember_login", "false");

                // SteamGuard check. If SteamGuard is enabled you need to enter it. Care probably you need to wait 7 days to trade.
                // For further information about SteamGuard see: https://support.steampowered.com/kb_article.php?ref=4020-ALZM-5519&l=english.
                if (steamGuard)
                {
                    Console.WriteLine("SteamWeb: SteamGuard is needed.");
                    Console.WriteLine("SteamWeb: Type the code:");
                    string consoleText = Console.ReadLine();
                    if (!string.IsNullOrEmpty(consoleText))
                    {
                        steamGuardText = Uri.EscapeDataString(consoleText);
                    }
                    steamGuardId = loginJson.emailsteamid;

                    // Adding the machine name to the NameValueCollection, because it is requested by steam.
                    Console.WriteLine("SteamWeb: Type your machine name:");
                    consoleText = Console.ReadLine();
                    var machineName = string.IsNullOrEmpty(consoleText) ? "" : Uri.EscapeDataString(consoleText);
                    data.Add("loginfriendlyname", machineName != "" ? machineName : "defaultSteamBotMachine");
                }

                data.Add("emailauth", steamGuardText);
                data.Add("emailsteamid", steamGuardId);
                // SteamGuard end.

                // Added unixTimestamp. It is included in the request normally.
                var unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                // Added three "0"'s because Steam has a weird unix timestamp interpretation.
                data.Add("donotcache", unixTimestamp + "000");

                data.Add("rsatimestamp", time);

                // Sending the actual login.
                using (HttpWebResponse webResponse = Request("https://steamcommunity.com/login/dologin/", "POST", data, false))
                {
                    var stream = webResponse.GetResponseStream();
                    if (stream == null)
                    {
                        return(false);
                    }
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        string json = reader.ReadToEnd();
                        loginJson        = JsonConvert.DeserializeObject <SteamResult>(json);
                        cookieCollection = webResponse.Cookies;
                    }
                }
            } while (loginJson.captcha_needed || loginJson.emailauth_needed);

            // If the login was successful, we need to enter the cookies to steam.
            if (loginJson.success)
            {
                _cookies = new CookieContainer();
                foreach (Cookie cookie in cookieCollection)
                {
                    _cookies.Add(cookie);
                }
                SubmitCookies(_cookies);
                return(true);
            }
            else
            {
                Console.WriteLine("SteamWeb Error: " + loginJson.message);
                return(false);
            }
        }
Example #15
0
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[16000];

        IPHostEntry ipHostInfo    = Dns.Resolve(Dns.GetHostName());
        IPAddress   ipAddress     = ipHostInfo.AddressList[0];
        IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Stream, ProtocolType.Tcp);

        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
        // Console.ReadLine();
        string answer = null;

        byte[] aesKey = null;
        answer = Console.ReadLine();
        if (answer == "gen")
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
            string rsaKey = rsa.ToXmlString(true);
            File.WriteAllText("c:\\private.txt", rsaKey);
            Console.Write("Ключи RSA были успешно сгенерированы и сохранены.\n\n");
        }
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
        answer = Console.ReadLine();
        if (answer == "enc")
        {
            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Ожидание соединения...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;
                    Console.Write("Нажмите Enter, чтобы выбрать файл для отправки");
                    Console.Read();
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.AddExtension = true;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                        {
                            myAes.KeySize = 256;
                            myAes.GenerateKey();
                            // myAes.Padding = PaddingMode.None;
                            aesKey = myAes.Key;
                            Console.WriteLine(dlg.FileName);
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                            rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
                            byte[] df  = rsa.Encrypt(myAes.Key, false);
                            byte[] mes = Encoding.ASCII.GetBytes("{Key}");

                            byte[] newArray = new byte[df.Length + mes.Length];
                            Array.Copy(mes, 0, newArray, 0, mes.Length);
                            Array.Copy(df, 0, newArray, mes.Length, df.Length);
                            handler.Send(newArray);
                        }
                    }
                    Thread.Sleep(1000);
                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);

                        data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("Ключ") > -1)
                        {
                            Console.Write("\nКлюч был успешно отправлен!\n");
                            byte[] encMes = EncryptFile(dlg.FileName, aesKey);
                            handler.Send(encMes);
                            Console.Write("\nФайл был успешно зашифрован и отправлен!\n");
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            break;
                        }
                    }
                    //Thread.Sleep(1000);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        Console.WriteLine("\nНажмите Enter для продолжения\n");
        Console.Read();
    }
Example #16
0
        // This is the only method about exchange data between this software and AirVPN infrastructure.
        // We don't use SSL. Useless layer in our case, and we need to fetch hostname and direct IP that don't permit common-name match.

        // 'S' is the AES 256 bit one-time session key, crypted with a RSA 4096 public-key.
        // 'D' is the data from the client to our server, crypted with the AES.
        // The server answer is XML decrypted with the same AES session.
        public static XmlDocument FetchUrl(string authPublicKey, string url, Dictionary <string, string> parameters)
        {
            // AES
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.KeySize = 256;
                rijAlg.GenerateKey();
                rijAlg.GenerateIV();

                // Generate S

                // Bug workaround: Xamarin 6.1.2 macOS throw an 'Default constructor not found for type System.Diagnostics.FilterElement' error.
                // in 'new System.Xml.Serialization.XmlSerializer', so i avoid that.

                /*
                 * StringReader sr = new System.IO.StringReader(authPublicKey);
                 * System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                 * RSAParameters publicKey = (RSAParameters)xs.Deserialize(sr);
                 */
                RSAParameters publicKey        = new RSAParameters();
                XmlDocument   docAuthPublicKey = new XmlDocument();
                docAuthPublicKey.LoadXml(authPublicKey);
                publicKey.Modulus  = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Modulus"].InnerText);
                publicKey.Exponent = Convert.FromBase64String(docAuthPublicKey.DocumentElement["Exponent"].InnerText);

                Dictionary <string, byte[]> assocParamS = new Dictionary <string, byte[]>();
                assocParamS["key"] = rijAlg.Key;
                assocParamS["iv"]  = rijAlg.IV;

                byte[] bytesParamS = null;
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    csp.ImportParameters(publicKey);
                    bytesParamS = csp.Encrypt(UtilsCore.AssocToUtf8Bytes(assocParamS), false);
                }

                // Generate D

                byte[] aesDataIn   = UtilsCore.AssocToUtf8Bytes(parameters);
                byte[] bytesParamD = null;

                {
                    MemoryStream aesCryptStream  = null;
                    CryptoStream aesCryptStream2 = null;

                    try
                    {
                        aesCryptStream = new MemoryStream();
                        using (ICryptoTransform aesEncryptor = rijAlg.CreateEncryptor())
                        {
                            aesCryptStream2 = new CryptoStream(aesCryptStream, aesEncryptor, CryptoStreamMode.Write);
                            aesCryptStream2.Write(aesDataIn, 0, aesDataIn.Length);
                            aesCryptStream2.FlushFinalBlock();

                            bytesParamD = aesCryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesCryptStream2 != null)
                        {
                            aesCryptStream2.Dispose();
                        }
                        else if (aesCryptStream != null)
                        {
                            aesCryptStream.Dispose();
                        }
                    }
                }

                // HTTP Fetch
                HttpRequest request = new HttpRequest();
                request.Url             = url;
                request.Parameters["s"] = UtilsString.Base64Encode(bytesParamS);
                request.Parameters["d"] = UtilsString.Base64Encode(bytesParamD);

                HttpResponse response = Engine.Instance.FetchUrl(request);

                try
                {
                    byte[] fetchResponse      = response.BufferData;
                    byte[] fetchResponsePlain = null;

                    MemoryStream aesDecryptStream  = null;
                    CryptoStream aesDecryptStream2 = null;

                    // Decrypt answer

                    try
                    {
                        aesDecryptStream = new MemoryStream();
                        using (ICryptoTransform aesDecryptor = rijAlg.CreateDecryptor())
                        {
                            aesDecryptStream2 = new CryptoStream(aesDecryptStream, aesDecryptor, CryptoStreamMode.Write);
                            aesDecryptStream2.Write(fetchResponse, 0, fetchResponse.Length);
                            aesDecryptStream2.FlushFinalBlock();

                            fetchResponsePlain = aesDecryptStream.ToArray();
                        }
                    }
                    finally
                    {
                        if (aesDecryptStream2 != null)
                        {
                            aesDecryptStream2.Dispose();
                        }
                        else if (aesDecryptStream != null)
                        {
                            aesDecryptStream.Dispose();
                        }
                    }

                    string finalData = System.Text.Encoding.UTF8.GetString(fetchResponsePlain);

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(finalData);
                    return(doc);
                }
                catch (Exception ex)
                {
                    string message = "";
                    if (response.GetHeader("location") != "")
                    {
                        message = MessagesFormatter.Format(Messages.ManifestFailedUnexpected302, response.GetHeader("location"));
                    }
                    else
                    {
                        message = ex.Message + " - " + response.GetLineReport();
                    }
                    throw new Exception(message);
                }
            }
        }
Example #17
0
        static async Task RunAsync(string consoleInput)
        {
            try
            {
                string[] splitInput = consoleInput.Split(' ');

                Task <string> task;

                switch (splitInput[0])
                {
                default: Console.WriteLine("Invalid Input"); break;

                case "TalkBack":
                    switch (splitInput[1])
                    {
                    case "Hello":

                        task = GetStringAsync("/api/TalkBack/hello");

                        if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                        {
                            Console.WriteLine(task.Result);
                        }

                        else
                        {
                            Console.WriteLine("Request Timed Out");
                        }
                        break;

                    case "Sort":

                        string trim = splitInput[2].TrimStart('[').TrimEnd(']');

                        string[] splitSort = trim.Split(',');

                        string integer = "";

                        for (int i = 0; i < splitSort.Length; i++)
                        {
                            integer += "integers=" + splitSort[i] + "&";
                        }

                        integer = integer.TrimEnd('&');

                        task = GetStringAsync("/api/talkback/sort?" + integer);

                        if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                        {
                            Console.WriteLine(task.Result);
                        }

                        else
                        {
                            Console.WriteLine("Request Timed Out");
                        }
                        break;
                    }

                    break;

                case "User":

                    switch (splitInput[1])
                    {
                    case "Get":

                        task = GetStringAsync("/api/user/new?username="******"Request Timed Out");
                        }

                        break;

                    case "Post":

                        task = PostStringAsync("/api/user/new", splitInput[2]);

                        if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                        {
                            Console.WriteLine(task.Result);
                        }

                        else
                        {
                            Console.WriteLine("Request Timed Out");
                        }

                        break;

                    case "Set":

                        username = splitInput[2];
                        APIKey   = splitInput[3];

                        Console.WriteLine("Stored");

                        break;

                    case "Delete":

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else
                        {
                            task = DeleteStringAsync("/api/user/removeuser?username="******"Request Timed Out");
                            }
                        }

                        break;

                    case "Role":

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else
                        {
                            task = PutStringAsync("/api/user/changerole", splitInput[2], splitInput[3]);

                            if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                            {
                                Console.WriteLine(task.Result);
                            }

                            else
                            {
                                Console.WriteLine("Request Timed Out");
                            }
                        }

                        break;
                    }
                    break;

                case "Protected":

                    switch (splitInput[1])
                    {
                    case "Hello":

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else
                        {
                            task = ProtectedGetStringAsync("/api/protected/hello", false);

                            if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                            {
                                Console.WriteLine(task.Result);
                            }

                            else
                            {
                                Console.WriteLine("Request Timed Out");
                            }
                        }

                        break;

                    case "SHA1":

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else
                        {
                            task = ProtectedGetStringAsync("/api/protected/sha1?message=" + splitInput[2], false);

                            if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                            {
                                Console.WriteLine(task.Result);
                            }

                            else
                            {
                                Console.WriteLine("Request Timed Out");
                            }
                        }

                        break;

                    case "SHA256":

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else
                        {
                            task = ProtectedGetStringAsync("/api/protected/sha256?message=" + splitInput[2], false);

                            if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                            {
                                Console.WriteLine(task.Result);
                            }

                            else
                            {
                                Console.WriteLine("Request Timed Out");
                            }
                        }

                        break;

                    case "Get":

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else
                        {
                            task = ProtectedGetStringAsync("/api/protected/getpublickey", true);

                            if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                            {
                                Console.WriteLine(task.Result);
                            }

                            else
                            {
                                Console.WriteLine("Request Timed Out");
                            }
                        }

                        break;

                    case "Sign":

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else if (publicKey == null)
                        {
                            Console.WriteLine("Client doesn't yet have the public key");
                        }

                        else
                        {
                            task = ProtectedSignStringAsync("/api/protected/sign?message=" + splitInput[2], splitInput[2]);

                            if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                            {
                                Console.WriteLine(task.Result);
                            }

                            else
                            {
                                Console.WriteLine("Request Timed Out");
                            }
                        }

                        break;

                    case "AddFifty":

                        try
                        {
                            int.Parse(splitInput[2]);
                        }

                        catch
                        {
                            Console.WriteLine("A valid integer must be given!");
                            break;
                        }

                        if (username == null || APIKey == null)
                        {
                            Console.WriteLine("You need to do a User Post or User Set first");
                        }

                        else if (publicKey == null)
                        {
                            Console.WriteLine("Client doesn't yet have the public key");
                        }

                        else
                        {
                            byte[] asciiByteMessage = System.Text.Encoding.ASCII.GetBytes(splitInput[2]);

                            RSA.FromXmlString(publicKey);

                            string encryptedinteger = BitConverter.ToString(RSA.Encrypt(asciiByteMessage, false));


                            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

                            aes.GenerateKey();
                            aes.GenerateIV();

                            string encryptedkey = BitConverter.ToString(RSA.Encrypt(aes.Key, false));
                            string encryptediv  = BitConverter.ToString(RSA.Encrypt(aes.IV, false));

                            task = ProtectedAddFiftyStringAsync("/api/protected/addfifty?encryptedInteger=" + encryptedinteger + "&encryptedSymKey=" + encryptedkey + "&encryptedIV=" + encryptediv);

                            string responseString = task.Result;

                            responseString = responseString.TrimStart('"').TrimEnd('"');;

                            string[] split    = responseString.Split('-');
                            byte[]   addFifty = new byte[split.Length];
                            for (int i = 0; i < split.Length; i++)
                            {
                                addFifty[i] = Convert.ToByte(split[i], 16);
                            }

                            ICryptoTransform decryptor = aes.CreateDecryptor();

                            string result;

                            using (MemoryStream ms = new MemoryStream(addFifty))
                            {
                                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                                {
                                    using (StreamReader sr = new StreamReader(cs))
                                    {
                                        result = sr.ReadToEnd();
                                    }
                                }
                            }

                            if (await Task.WhenAny(task, Task.Delay(20000)) == task)
                            {
                                Console.WriteLine(result);
                            }

                            else
                            {
                                Console.WriteLine("Request Timed Out");
                            }
                        }
                        break;
                    }
                    break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.GetBaseException().Message);
            }
        }
Example #18
0
        /// <summary>
        /// Encrypt an arbitrary string of data under the supplied public key
        /// </summary>
        /// <param name="publicKey">The public key to encrypt under</param>
        /// <param name="data">The data to encrypt</param>
        /// <param name="length">The bit length or strength of the public key: 1024, 2048 or 4096 bits. This must match the 
        /// value actually used to create the publicKey</param>
        /// <returns></returns>
        public static string Encrypt(string publicKey, string data, RsaKeyLengths length = RsaKeyLengths.Bit2048)
        {
            // full array of bytes to encrypt
            byte[] bytesToEncrypt;

            // worker byte array
            byte[] block;

            // encrypted bytes
            byte[] encryptedBytes;

            // length of bytesToEncrypt
            var dataLength = 0;

            // number of bytes in key                
            var keySize = 0;

            // maximum block length to encrypt          
            var maxLength = 0;

            // how many blocks must we encrypt to encrypt entire message?
            var iterations = 0;

            // the encrypted data
            var encryptedData = new StringBuilder();

            // instantiate the crypto provider with the correct key length
            var rsaCryptoServiceProvider = new RSACryptoServiceProvider((int)length);

            // initialize the RSA object from the given public key
            rsaCryptoServiceProvider.FromXmlString(publicKey);

            // convert data to byte array
            bytesToEncrypt = Encoding.Unicode.GetBytes(data);

            // get length of byte array
            dataLength = bytesToEncrypt.Length;

            // convert length of key from bits to bytes
            keySize = (int)length / 8;

            // .NET RSACryptoServiceProvider uses SHA1 Hash function
            // use this to work out the maximum length to encrypt per block
            maxLength = ((keySize - 2) - (2 * SHA1.Create().ComputeHash(bytesToEncrypt).Length));

            // how many blocks do we need to encrypt?
            iterations = dataLength / maxLength;

            // encrypt block by block
            for (int index = 0; index <= iterations; index++)
            {
                // is there more than one full block of data left to encrypt?
                if ((dataLength - maxLength * index) > maxLength)
                {
                    block = new byte[maxLength];
                }
                else
                {
                    block = new byte[dataLength - maxLength * index];
                }

                // copy the required number of bytes from the array of bytes to encrypt to our worker array
                Buffer.BlockCopy(bytesToEncrypt, maxLength * index, block, 0, block.Length);

                // encrypt the current worker array block of bytes
                encryptedBytes = rsaCryptoServiceProvider.Encrypt(block, true);

                // RSACryptoServiceProvider reverses the order of encrypted bytesToEncrypt after encryption and before decryption.
                // Undo this reversal for compatibility with other implementations
                Array.Reverse(encryptedBytes);

                // convert to base 64 string
                encryptedData.Append(Convert.ToBase64String(encryptedBytes));
            }

            return encryptedData.ToString();
        }
Example #19
0
 public byte[] Encrypt(byte[] pData)
 {
     //pData = new byte[12];
     return(pServerPublicKey.Encrypt(pData, true));
 }
Example #20
0
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[16000];

        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
           // Console.ReadLine();
        string answer = null;
        byte[] aesKey = null;
        answer = Console.ReadLine();
        if (answer == "gen")
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
            string rsaKey = rsa.ToXmlString(true);
            File.WriteAllText("c:\\private.txt", rsaKey);
            Console.Write("Ключи RSA были успешно сгенерированы и сохранены.\n\n");
        }
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
        answer = Console.ReadLine();
        if (answer == "enc")
        {
            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Ожидание соединения...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;
                    Console.Write("Нажмите Enter, чтобы выбрать файл для отправки");
                    Console.Read();
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.AddExtension = true;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                        {
                            myAes.KeySize = 256;
                            myAes.GenerateKey();
                           // myAes.Padding = PaddingMode.None;
                            aesKey = myAes.Key;
                            Console.WriteLine(dlg.FileName);
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                            rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
                            byte[] df = rsa.Encrypt(myAes.Key, false);
                            byte[] mes = Encoding.ASCII.GetBytes("{Key}");

                            byte[] newArray = new byte[df.Length + mes.Length];
                            Array.Copy(mes, 0, newArray, 0, mes.Length);
                            Array.Copy(df, 0, newArray, mes.Length, df.Length);
                            handler.Send(newArray);
                        }
                    }
                    Thread.Sleep(1000);
                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);

                        data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("Ключ") > -1)
                        {
                            Console.Write("\nКлюч был успешно отправлен!\n");
                            byte[] encMes = EncryptFile(dlg.FileName, aesKey);
                            handler.Send(encMes);
                            Console.Write("\nФайл был успешно зашифрован и отправлен!\n");
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            break;
                        }
                    }
                    //Thread.Sleep(1000);

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }
        Console.WriteLine("\nНажмите Enter для продолжения\n");
        Console.Read();
    }
Example #21
0
            public static byte[] RSAEncrypt(byte[] dataToEncrypt, RSAParameters pars, bool padding)
            {
                try
                {
                    byte[] encryptedData;
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSA.ImportParameters(pars);
                        encryptedData = RSA.Encrypt(dataToEncrypt, padding);
                    }
                    return encryptedData;
                }
                catch (Exception)
                {

                    return null;

                }
            }
	public static byte[] encrypt(string PEMPublicKey, byte[] data) {
		byte[] encrData = null;
		
		if ((data != null) && (PEMPublicKey != null)) {
			RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
			
			string publicKeyXml = opensslkey.DecodePEMKey(PEMPublicKey);
			if (publicKeyXml != null) {
				rsa.FromXmlString(publicKeyXml);
				
				encrData = rsa.Encrypt(data, false);
			}
			else {
				Console.WriteLine("incorrect PEM key. " + PEMPublicKey);
			}
		}
		
		return encrData;
	}
Example #23
0
    /// <summary>
    /// 通过公钥加密
    /// </summary>
    /// <param name="dataStr">待加密字符串</param>
    /// <returns>加密结果</returns>
    public static string EncryptByPublicKey(string dataStr)
    {
        //取得公钥参数
        RSAParameters rsaparameters = ConvertFromPemPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8eWx4ZoUw3IOnVJ3Uu7N2fnj/CCoBNsMy7rXkwgpzkWM6apBEmZWaTkG888s8vJ16e0dUvTroQ6jc3kHZrnY9C+caIQWDwG9Msty/o8YZqvtmPQvSUPXg+I4KTSY7Gt53Rjpr5C8XaH8KTEXPWddg4xTWzWM4vRyNH4cP8K8kgQIDAQAB");
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
        RSA.ImportParameters(rsaparameters);
        byte[] bytes = new UnicodeEncoding().GetBytes(dataStr);

        string str2 = Convert.ToBase64String(RSA.Encrypt(bytes, false));
        return HttpUtility.UrlEncode(str2);
    }
Example #24
0
 public static byte[] Encrypt(byte[] bytes, RSAParameters publicKey, RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048)
 {
     using (var rsa = new RSACryptoServiceProvider((int)rsaKeyLength))
     {
         rsa.ImportParameters(publicKey);
         return rsa.Encrypt(bytes, DoOAEPPadding);
     }
 }
Example #25
0
        public void Login(string Email, string Password, string verifierToken)
        {
            _email = Email;
            //Sets the email var for possible future reference, not required atm

            //Create the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL.Key);

            //It's a post and we're going to send data
            request.Method = "POST";

            //We have no content length because we're not sending data,
            request.ContentLength = 0;

            //Identifies the client
            request.Headers.Add("X-Line-Application: " + Protocol.LineApplication);
            ((HttpWebRequest)request).UserAgent = Protocol.UserAgent;
            HttpWebResponse webResponse = null;

            //Honestly not the best implementation but to be honest, this function itself has never failed.
            try
            {
                //Get the response, which is the key and whatnot to encrypt user auth data
                webResponse = (HttpWebResponse)request.GetResponse();
            }
            catch
            {
                if (OnLogin != null)
                {
                    OnLogin.Invoke(Result.UNKNOWN_ERROR);
                }
                return; //Result.UNKNOWN_ERROR
            }


            var reader = new BinaryReader(webResponse.GetResponseStream());
            //Create the stream for the body data

            //The buffer size should be the same as the actual size of the body
            var buffer = new byte[webResponse.ContentLength];

            //Reads all the data from the stream
            reader.Read(buffer, 0, Convert.ToInt32(webResponse.ContentLength));

            //And closes the stream
            webResponse.Close();

            //Converts it to text
            string response = Encoding.UTF8.GetString(buffer);

            //Crude attempt to parse the json because it's likely not to change
            //and if it does, it's a huge problem anyways
            //Don't try to read it, it's really bad

            //Remove brackets
            //var fields = new List<string>();
            //response = response.Replace("{", "").Replace("}", "");

            //for (int i = 0; i < response.Length - 1; i++)
            //{
            //    if (response.Substring(i, 1) == "\"")
            //    {
            //        //Gets the next quote location
            //        int nextquote = 0;
            //        for (int j = response.Length - 1; j > i; j--)
            //        {
            //            if (response.Substring(j, 1) == "\"")
            //            {
            //                nextquote = j;
            //            }
            //        }
            //        string nextfield = (response.Substring(i + 1, nextquote - i - 1));
            //        if (nextfield != "," && nextfield != ":") fields.Add(nextfield);
            //    }
            //}

            KeyPostResponse keys = KeyPostResponse.FromJSON(response);

            if (keys == null)
            {
                Debug.Print("Unable to parse RSA/session key response. This is a critical error. Exiting.");
                if (OnLogin != null)
                {
                    OnLogin.Invoke(Result.UNKNOWN_ERROR);
                }
                return;
            }

            //The format of the response is:
            //convoluted.

            //It has a session key which uniquely identifies each session, obviously
            //And an RSA key, mod, and exponent used to crypt usernames and passwords before sending it over
            //the net.

            //This is industry standard and in other web services, is done via Javascript.

            string sessionKey = keys.SessionKey;
            string rsaData    = keys.RSAKey;

            string keyName  = rsaData.Split(',')[0];
            string modulus  = rsaData.Split(',')[1]; //Public key
            string exponent = rsaData.Split(',')[2];

            var rsa        = new RSACryptoServiceProvider();
            var parameters = new RSAParameters();

            parameters.Exponent = Bytes.GetExponentFromString(exponent);
            parameters.Modulus  = Bytes.HexStringToByteArray(modulus);
            rsa.ImportParameters(parameters);

            //The Auth.GenerateAuthCode function simply takes all the required elements and mashes them together in the
            //terrible format required to authenticate to the server.

            //The format is as follows:

            //Session ID length (1 byte)
            //Session ID
            //Username length (1 byte)
            //Username
            //Password length (1 byte)
            //Password

            //This entire payload is sent after being RSA encrypted by the client,
            //and is sent over an SSL connection

            byte[] cypher = rsa.Encrypt(Auth.GenerateAuthCode(sessionKey, Email, Password), false);


            //The talkservice URL is the one responsible for logging users in among other things
            //P4 is for polling, and I don't know what S4 is for. Ask Lumpio.
            _thriftTransport.TargetUrl = URL.TalkService;


            //This is the magic of actually logging in.
            //I honestly have no idea why some of this data is needed.
            LoginResult authResponse = null;

            try
            {
                if (String.IsNullOrEmpty(verifierToken))
                {
                    authResponse =
                        Client.loginWithIdentityCredentialForCertificate(
                            IdentityProvider.LINE,                   //We're using LineSharp
                            keyName,                                 //This is the username
                            Bytes.GetHexStringFromByteArray(cypher), //Hashed password
                            true,                                    //Keep us logged in
                            Functions.Net.GetLocalIpAddress(),       //Location of login
                            Environment.MachineName,                 //Idenfitier
                            null                                     //Certificate, but who knows what that does
                            );
                }
                else
                {
                    authResponse =
                        Client.loginWithVerifierForCertificate(verifierToken);
                }
            }
            catch (TalkException talkException)
            {
                //Auth issues -BESIDES FAILURE-
                Exceptions.Display(talkException);
            }

            //The actual authresponse contains info about wether or not the user authed successfully!
            if (authResponse != null)
            {
                //Store the certificate if we get one.
                if (!String.IsNullOrEmpty(authResponse.Certificate))
                {
                    _certificate = authResponse.Certificate;
                }

                //If we have an auth token, then deal with that and return
                if (!String.IsNullOrEmpty(authResponse.AuthToken))
                {
                    //Successfully retrieved an access key
                    _accesskey = authResponse.AuthToken;
                    _thriftTransport.AccessKey = authResponse.AuthToken;
                    _thriftTransport.TargetUrl = URL.TalkService;


                    //Don't know which should come first.
                    _operationHandler.Start();
                    //Starts listening to events, then calls the OnLogin function.
                    if (OnLogin != null)
                    {
                        OnLogin.Invoke(Result.OK);
                    }
                    return;
                }
                //Otherwise we probably have a verifier. use that to verify and
                //do the auth procedure again.
                if (!String.IsNullOrEmpty(authResponse.Verifier) &&
                    !String.IsNullOrEmpty(authResponse.PinCode))
                {
                    //Props to Wii for having this issue that needed to be fixed.
                    //This means the client needs a pin to verify the user.

                    _verifier = authResponse.Verifier;
                    _pin      = authResponse.PinCode;

                    if (OnLogin != null)
                    {
                        OnLogin.Invoke(Result.REQUIRES_PIN_VERIFICATION);
                    }
                    return;
                }
            }
            if (OnLogin != null)
            {
                OnLogin.Invoke(Result.UNKNOWN_ERROR);
            }
        }
        // Runs on client
        internal static void HandleHailRequest(uint clientId, Stream stream, int channelId)
        {
            X509Certificate2 certificate = null;

            byte[] serverDiffieHellmanPublicPart = null;
            using (PooledBitReader reader = PooledBitReader.Get(stream))
            {
                if (netManager.NetworkConfig.EnableEncryption)
                {
                    // Read the certificate
                    if (netManager.NetworkConfig.SignKeyExchange)
                    {
                        // Allocation justification: This runs on client and only once, at initial connection
                        certificate = new X509Certificate2(reader.ReadByteArray());
                        if (CryptographyHelper.VerifyCertificate(certificate, netManager.ConnectedHostname))
                        {
                            // The certificate is not valid :(
                            // Man in the middle.
                            if (LogHelper.CurrentLogLevel <= LogLevel.Normal)
                            {
                                if (LogHelper.CurrentLogLevel <= LogLevel.Normal)
                                {
                                    LogHelper.LogWarning("Invalid certificate. Disconnecting");
                                }
                            }
                            netManager.StopClient();
                            return;
                        }
                        else
                        {
                            netManager.NetworkConfig.ServerX509Certificate = certificate;
                        }
                    }

                    // Read the ECDH
                    // Allocation justification: This runs on client and only once, at initial connection
                    serverDiffieHellmanPublicPart = reader.ReadByteArray();

                    // Verify the key exchange
                    if (netManager.NetworkConfig.SignKeyExchange)
                    {
                        byte[] serverDiffieHellmanPublicPartSignature = reader.ReadByteArray();

                        RSACryptoServiceProvider rsa = certificate.PublicKey.Key as RSACryptoServiceProvider;

                        if (rsa != null)
                        {
                            using (SHA256Managed sha = new SHA256Managed())
                            {
                                if (!rsa.VerifyData(serverDiffieHellmanPublicPart, sha, serverDiffieHellmanPublicPartSignature))
                                {
                                    if (LogHelper.CurrentLogLevel <= LogLevel.Normal)
                                    {
                                        if (LogHelper.CurrentLogLevel <= LogLevel.Normal)
                                        {
                                            LogHelper.LogWarning("Invalid signature. Disconnecting");
                                        }
                                    }
                                    netManager.StopClient();
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            using (PooledBitStream outStream = PooledBitStream.Get())
            {
                using (PooledBitWriter writer = PooledBitWriter.Get(outStream))
                {
                    if (netManager.NetworkConfig.EnableEncryption)
                    {
                        // Create a ECDH key
                        EllipticDiffieHellman diffieHellman = new EllipticDiffieHellman(EllipticDiffieHellman.DEFAULT_CURVE, EllipticDiffieHellman.DEFAULT_GENERATOR, EllipticDiffieHellman.DEFAULT_ORDER);
                        netManager.clientAesKey = diffieHellman.GetSharedSecret(serverDiffieHellmanPublicPart);
                        byte[] diffieHellmanPublicKey = diffieHellman.GetPublicKey();
                        writer.WriteByteArray(diffieHellmanPublicKey);
                        if (netManager.NetworkConfig.SignKeyExchange)
                        {
                            RSACryptoServiceProvider rsa = certificate.PublicKey.Key as RSACryptoServiceProvider;

                            if (rsa != null)
                            {
                                using (SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider())
                                {
                                    writer.WriteByteArray(rsa.Encrypt(sha.ComputeHash(diffieHellmanPublicKey), false));
                                }
                            }
                            else
                            {
                                throw new CryptographicException("[MLAPI] Only RSA certificates are supported. No valid RSA key was found");
                            }
                        }
                    }
                }
                // Send HailResponse
                InternalMessageHandler.Send(NetworkingManager.Singleton.ServerClientId, MLAPIConstants.MLAPI_CERTIFICATE_HAIL_RESPONSE, "MLAPI_INTERNAL", outStream, SecuritySendFlags.None, true);
            }
        }
Example #27
0
 public byte[] Encrypt(byte[] data)
 {
     return(rsa.Encrypt(data, false));
 }
Example #28
0
        public string Encrypt(EncoderType type, string encrypt)
        {
            string ret = "";

            byte[] inputByteArray = Encoding.UTF8.GetBytes(encrypt);
            byte[] rgbKey         = Convert.FromBase64String(Key);
            byte[] rgbIV          = Convert.FromBase64String(IV);
            switch (type)
            {
            case EncoderType.AES:
                using (AesCryptoServiceProvider csp = new AesCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.DES:
                using (DESCryptoServiceProvider csp = new DESCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.RC2:
                using (RC2CryptoServiceProvider csp = new RC2CryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.TripleDES:
                using (TripleDESCryptoServiceProvider csp = new TripleDESCryptoServiceProvider())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (CryptoStream cs = new CryptoStream(ms, csp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inputByteArray, 0, inputByteArray.Length);
                            cs.FlushFinalBlock();
                            ret = Convert.ToBase64String(ms.ToArray());
                        }
                    }
                }
                break;

            case EncoderType.RSA:
                using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
                {
                    csp.FromXmlString(Key);
                    ret = Convert.ToBase64String(csp.Encrypt(inputByteArray, false));
                }
                break;

            case EncoderType.MD5:
                using (MD5CryptoServiceProvider csp = new MD5CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA1:
                using (SHA1CryptoServiceProvider csp = new SHA1CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA256:
                using (SHA256CryptoServiceProvider csp = new SHA256CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA384:
                using (SHA384CryptoServiceProvider csp = new SHA384CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;

            case EncoderType.SHA512:
                using (SHA512CryptoServiceProvider csp = new SHA512CryptoServiceProvider())
                {
                    ret = BitConverter.ToString(csp.ComputeHash(inputByteArray)).Replace("-", string.Empty);
                }
                break;
            }
            return(ret);
        }
Example #29
0
    public static void Main(String[] args)
    {
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

        try
        {
            // Note: In cases where a random key is generated,
            // a key container is not created until you call
            // a method that uses the key.  This example calls
            // the Encrypt method before calling the
            // CspKeyContainerInfo property so that a key
            // container is created.

            // Create some data to encrypt and display it.
            string data = "Here is some data to encrypt.";

            Console.WriteLine("Data to encrypt: " + data);

            // Convert the data to an array of bytes and
            // encrypt it.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            byte[] encData = rsa.Encrypt(byteData, false);

            // Display the encrypted value.
            Console.WriteLine("Encrypted Data: " + Encoding.ASCII.GetString(encData));

            Console.WriteLine();

            Console.WriteLine("CspKeyContainerInfo information:");

            Console.WriteLine();

            // Create a new CspKeyContainerInfo object.
            CspKeyContainerInfo keyInfo = rsa.CspKeyContainerInfo;

            // Display the value of each property.

            Console.WriteLine("Accessible property: " + keyInfo.Accessible);

            Console.WriteLine("Exportable property: " + keyInfo.Exportable);

            Console.WriteLine("HardwareDevice property: " + keyInfo.HardwareDevice);

            Console.WriteLine("KeyContainerName property: " + keyInfo.KeyContainerName);

            Console.WriteLine("KeyNumber property: " + keyInfo.KeyNumber.ToString());

            Console.WriteLine("MachineKeyStore property: " + keyInfo.MachineKeyStore);

            Console.WriteLine("Protected property: " + keyInfo.Protected);

            Console.WriteLine("ProviderName property: " + keyInfo.ProviderName);

            Console.WriteLine("ProviderType property: " + keyInfo.ProviderType);

            Console.WriteLine("RandomlyGenerated property: " + keyInfo.RandomlyGenerated);

            Console.WriteLine("Removable property: " + keyInfo.Removable);

            Console.WriteLine("UniqueKeyContainerName property: " + keyInfo.UniqueKeyContainerName);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        finally
        {
            // Clear the key.
            rsa.Clear();
        }
    }
Example #30
0
        // Encrypt a rsa file
        public static void Encrypt(string publicKeyFileName, string plainFileName, string encryptedFileName)

        {
            // Variables

            CspParameters cspParams = null;

            RSACryptoServiceProvider rsaProvider = null;

            StreamReader publicKeyFile = null;

            StreamReader plainFile = new StreamReader(@"C:\crypto\decrypted\" + plainFileName);

            FileStream encryptedFile = null;

            string publicKeyText = "";

            string plainText = "";

            byte[] plainBytes = null;

            byte[] encryptedBytes = null;


            try

            {
                // Select target CSP

                cspParams = new CspParameters();

                cspParams.ProviderType = 1; // PROV_RSA_FULL

                //cspParams.ProviderName; // CSP name

                rsaProvider = new RSACryptoServiceProvider(cspParams);


                // Read public key from file

                publicKeyFile = File.OpenText(@"C:\crypto\rsakeys\" + publicKeyFileName);

                publicKeyText = publicKeyFile.ReadToEnd();


                // Import public key

                rsaProvider.FromXmlString(publicKeyText);


                // Read plain file
                // ToDo Read file and convert it into byte array

                plainText = plainFile.ReadToEnd();


                // Encrypt plain file

                plainBytes = Encoding.Unicode.GetBytes(plainText);

                encryptedBytes = rsaProvider.Encrypt(plainBytes, false);


                // Write encrypted text to file

                encryptedFile = File.Create(encryptedFileName);

                encryptedFile.Write(encryptedBytes, 0, encryptedBytes.Length);

                //ToDo Logging
            }

            catch (Exception ex)

            {
                //ToDo Logging
                // Any errors? Show them
                Console.WriteLine(ex.Message);
            }

            finally

            {
                // Do some clean up if needed

                if (publicKeyFile != null)

                {
                    publicKeyFile.Close();
                }

                if (plainFile != null)

                {
                    plainFile.Close();
                }

                if (encryptedFile != null)

                {
                    encryptedFile.Close();
                }
            }
        }
Example #31
0
        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            var authSessionRequest = new AuthSessionRequest
            {
                Login = TxtLogin.Text
            };

            var json = JsonConvert.SerializeObject(authSessionRequest);

            var request = new HttpRequestMessage
            {
                RequestUri = new Uri($"http://localhost:5000/api/session"),
                Method     = HttpMethod.Post,
                Content    = new StringContent(json, Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = _client.SendAsync(request).Result;

            if (!response.IsSuccessStatusCode)
            {
                AuthStatus.Text       = "not authorized";
                AuthStatus.Foreground = new SolidColorBrush(Colors.Red);
                return;
            }

            var authSessionResponse = JsonConvert.DeserializeObject <AuthSessionResponse>(
                response.Content.ReadAsStringAsync().Result);

            var authRequest = new AuthRequest
            {
                Login = TxtLogin.Text
            };

            var keyString      = string.Empty;
            var keyInputDialog = new KeyInputDialog();

            if (keyInputDialog.ShowDialog() == true)
            {
                keyString = keyInputDialog.Key;
            }

            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.ImportParameters(authSessionResponse.PublicRSAParameters.ToRSAParameters());
                authRequest.EncryptedPassword    = RSA.Encrypt(Encoding.Default.GetBytes(TxtPassword.Text), false);
                authRequest.EncryptedTelegramKey = RSA.Encrypt(Encoding.Default.GetBytes(keyString), false);
            }

            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                authRequest.ClientPublicRSAParameters = RSA.ExportParameters(false).ToPublicRSAParameters();

                json = JsonConvert.SerializeObject(authRequest);

                request = new HttpRequestMessage
                {
                    RequestUri = new Uri($"http://localhost:5000/api/auth"),
                    Method     = HttpMethod.Post,
                    Content    = new StringContent(json, Encoding.UTF8, "application/json")
                };

                response = _client.SendAsync(request).Result;

                if (!response.IsSuccessStatusCode)
                {
                    AuthStatus.Text       = "not authorized";
                    AuthStatus.Foreground = new SolidColorBrush(Colors.Red);
                    return;
                }

                var authResponse = JsonConvert.DeserializeObject <AuthResponse>(
                    response.Content.ReadAsStringAsync().Result);

                _token = authResponse.Token;

                _sessionKey = RSA.Decrypt(authResponse.EncryptedSessionKey, false);
                _sessionIV  = RSA.Decrypt(authResponse.EncryptedSessionIV, false);

                AuthStatus.Text       = "authorized";
                AuthStatus.Foreground = new SolidColorBrush(Colors.Green);
            }

            _garbage = string.Empty;
        }
        private void EncryptFile(string inFile)
        {
            // Create instance of Rijndael for
            // symetric encryption of the data.
            RijndaelManaged rjndl = new RijndaelManaged();

            rjndl.KeySize   = 256;
            rjndl.BlockSize = 256;
            rjndl.Mode      = CipherMode.CBC;
            ICryptoTransform transform = rjndl.CreateEncryptor();

            // Use RSACryptoServiceProvider to
            // enrypt the Rijndael key.
            // rsa is previously instantiated:
            //    rsa = new RSACryptoServiceProvider(cspp);
            byte[] keyEncrypted = Rsa.Encrypt(rjndl.Key, false);

            // Create byte arrays to contain
            // the length values of the key and IV.
            byte[] LenK  = new byte[4];
            byte[] LenIV = new byte[4];

            int lKey = keyEncrypted.Length;

            LenK = BitConverter.GetBytes(lKey);
            int lIV = rjndl.IV.Length;

            LenIV = BitConverter.GetBytes(lIV);

            // Write the following to the FileStream
            // for the encrypted file (outFs):
            // - length of the key
            // - length of the IV
            // - ecrypted key
            // - the IV
            // - the encrypted cipher content

            //int startFileName = inFile.LastIndexOf("\\") + 1;
            // Change the file's extension to ".enc"
            string outFile = inFile + ".enc";

            using (FileStream outFs = new FileStream(outFile, FileMode.Create))
            {
                outFs.Write(LenK, 0, 4);
                outFs.Write(LenIV, 0, 4);
                outFs.Write(keyEncrypted, 0, lKey);
                outFs.Write(rjndl.IV, 0, lIV);

                // Now write the cipher text using
                // a CryptoStream for encrypting.
                using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                {
                    using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                    {
                        int data;
                        while ((data = inFs.ReadByte()) != -1)        //until the main file have byte
                        {
                            outStreamEncrypted.WriteByte((byte)data); //*****Write Every Byte to the the file With CryptoStrem***
                        }
                    }

                    outStreamEncrypted.Close();
                    File.Delete(inFile);
                }
                outFs.Close();
            }
        }
        async Task <bool> doLogin()
        {
            // Assume validity checks have been done
            // 1. Get RSA key
            GetRsaKeyResponse rsaResponse = await loginClient.GetRsaKeyAsync(usernameTextBox.Text);

            if (!rsaResponse.Success)
            {
                setMessage(!string.IsNullOrEmpty(rsaResponse.Message) ? rsaResponse.Message : "Can't get RSA key for sending login info.");
                return(false);
            }

            // 2. Encrypt password
            string encryptedPassword;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(new RSAParameters
                {
                    Modulus  = hexToBytes(rsaResponse.PublicKeyMod),
                    Exponent = hexToBytes(rsaResponse.PublicKeyExp)
                });

                // Filter password to ASCII characters (the login script does this)
                string password     = System.Text.RegularExpressions.Regex.Replace(passwordTextBox.Text, "[^\u0000-\u007F]", string.Empty);
                byte[] passwordBlob = Encoding.UTF8.GetBytes(password);
                byte[] crypted      = rsa.Encrypt(passwordBlob, false);
                encryptedPassword = Convert.ToBase64String(crypted);
            }

            // 3. Send request to server
            DoLoginRequest request = new DoLoginRequest
            {
                Password          = encryptedPassword,
                Username          = usernameTextBox.Text,
                TwoFactorCode     = mobileAuthTextBox.Text,
                EmailAuth         = emailAuthTextBox.Text,
                LoginFriendlyName = friendlyNameTextBox.Text,
                CaptchaText       = captchaTextBox.Text,
                RsaTimeStamp      = rsaResponse.Timestamp,
                RememberLogin     = true
            };

            if (loginResponse != null)
            {
                request.CaptchaGid   = loginResponse.CaptchaGid;
                request.EmailSteamId = loginResponse.EmailSteamId;
            }
            else
            {
                request.CaptchaGid = -1;
            }

            loginResponse = await loginClient.DoLoginAsync(request);

            if (loginResponse == null)
            {
                return(false);
            }
            return(loginResponse.Success && loginResponse.LoginComplete);
        }
Example #34
0
 /// <summary>
 /// RSA公钥文件加密纯文本。
 /// </summary>
 /// <param name="encryptArray">要加密的文本</param>
 /// <returns>表示加密数据的64位编码字符串.</returns>
 internal byte[] RSAEncrypt(byte[] encryptArray)
 {
     return(rsa.Encrypt(encryptArray, false));
 }
Example #35
0
 /// <summary>
 /// 对字节数组进行加密。
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public override byte[] Encrypt(byte[] source)
 {
     FromXmlString(PublicKey);
     return(rsa.Encrypt(source, false));
 }
        /// <summary>
        /// Encrypts data into a cipher.
        /// </summary>
        /// <param name="algorithm">The algorithm to use for encryption, cannot be null.</param>
        /// <param name="data">The data to encrypt, cannot be null but can be empty.</param>
        /// <returns>The resulting cipher, cannot be null but can be empty.</returns>
        /// <exception cref="ArgumentNullException">The key or data argument is null.</exception>
        /// <exception cref="CryptographicException">The encryption operation failed, probably due to malformed key.</exception>
        private static byte[] Encrypt(RSACryptoServiceProvider algorithm, byte[] data)
        {
            // omitting argument validation in private methods
            // KeySize is in bits, array lengths count bytes
            int blockSize = (algorithm.KeySize / 8) - AsymmetricDataEncryptor.PadLength;

            // Concatenate the result of breaking the data into chunks that are individually encrypted
            // calling 'ToArray' to avoid decrypting twice
            return(AsymmetricDataEncryptor.Concatenate(AsymmetricDataEncryptor.Break(blockSize, data).Select(array => algorithm.Encrypt(array, true)).ToArray()));
        }
Example #37
0
            public string Encrypt(byte[] shellCode)
            {
                var num  = shellCode.Length;
                var text = string.Empty;

                if (num <= 400)
                {
                    var array  = new byte[200];
                    var num2   = num - 200;
                    var array2 = new byte[num2];
                    for (var i = 0; i < 200; i++)
                    {
                        array[i] = shellCode[i];
                    }
                    for (var j = 0; j < num2; j++)
                    {
                        array2[j] = shellCode[200 + j];
                    }
                    using (var rSACryptoServiceProvider = new RSACryptoServiceProvider(1024))
                    {
                        try
                        {
                            rSACryptoServiceProvider.FromXmlString(this.publicKey);
                            var inArray = rSACryptoServiceProvider.Encrypt(array, true);
                            text = Convert.ToBase64String(inArray);
                            rSACryptoServiceProvider.FromXmlString(this.publicKey);
                            var inArray2 = rSACryptoServiceProvider.Encrypt(array2, true);
                            text = text + "|" + Convert.ToBase64String(inArray2);
                        }
                        finally
                        {
                            rSACryptoServiceProvider.PersistKeyInCsp = false;
                        }
                    }
                }
                if (num > 400)
                {
                    var num3   = num - 400;
                    var array3 = new byte[200];
                    var array4 = new byte[200];
                    var array5 = new byte[num3];
                    for (var k = 0; k < 200; k++)
                    {
                        array3[k] = shellCode[k];
                    }
                    for (var l = 0; l < 200; l++)
                    {
                        array4[l] = shellCode[200 + l];
                    }
                    for (var m = 0; m < num3; m++)
                    {
                        array5[m] = shellCode[400 + m];
                    }
                    using (var rSACryptoServiceProvider2 = new RSACryptoServiceProvider(1024))
                    {
                        try
                        {
                            rSACryptoServiceProvider2.FromXmlString(this.publicKey);
                            var inArray3 = rSACryptoServiceProvider2.Encrypt(array3, true);
                            text = Convert.ToBase64String(inArray3);
                            rSACryptoServiceProvider2.FromXmlString(this.publicKey);
                            var inArray4 = rSACryptoServiceProvider2.Encrypt(array4, true);
                            text = text + "|" + Convert.ToBase64String(inArray4);
                            rSACryptoServiceProvider2.FromXmlString(this.publicKey);
                            var inArray5 = rSACryptoServiceProvider2.Encrypt(array5, true);
                            text = text + "|" + Convert.ToBase64String(inArray5);
                        }
                        finally
                        {
                            rSACryptoServiceProvider2.PersistKeyInCsp = false;
                        }
                    }
                }
                return(text);
            }
Example #38
0
        static private void EncryptFile(string inFile, string outFile, RSACryptoServiceProvider RSA)
        {
            // Create instance of Aes for
            // symmetric encryption of the data.
            Aes aes = Aes.Create();
            ICryptoTransform transform = aes.CreateEncryptor();

            // Use RSACryptoServiceProvider to
            // encrypt the AES key.
            // rsa is previously instantiated:
            //    rsa = new RSACryptoServiceProvider(cspp);
            byte[] keyEncrypted = RSA.Encrypt(aes.Key, false);

            // Create byte arrays to contain
            // the length values of the key and IV.
            byte[] LenK  = new byte[4];
            byte[] LenIV = new byte[4];

            int lKey = keyEncrypted.Length;

            LenK = BitConverter.GetBytes(lKey);
            int lIV = aes.IV.Length;

            LenIV = BitConverter.GetBytes(lIV);

            // Write the following to the FileStream
            // for the encrypted file (outFs):
            // - length of the key
            // - length of the IV
            // - ecrypted key
            // - the IV
            // - the encrypted cipher content

            using (FileStream outFs = new FileStream(outFile, FileMode.Create))
            {
                outFs.Write(LenK, 0, 4);
                outFs.Write(LenIV, 0, 4);
                outFs.Write(keyEncrypted, 0, lKey);
                outFs.Write(aes.IV, 0, lIV);

                // Now write the cipher text using
                // a CryptoStream for encrypting.
                using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                {
                    // By encrypting a chunk at
                    // a time, you can save memory
                    // and accommodate large files.
                    int count  = 0;
                    int offset = 0;

                    // blockSizeBytes can be any arbitrary size.
                    int    blockSizeBytes = aes.BlockSize / 8;
                    byte[] data           = new byte[blockSizeBytes];
                    int    bytesRead      = 0;

                    using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                    {
                        do
                        {
                            count   = inFs.Read(data, 0, blockSizeBytes);
                            offset += count;
                            outStreamEncrypted.Write(data, 0, count);
                            bytesRead += blockSizeBytes;
                        }while (count > 0);
                        inFs.Close();
                    }
                    outStreamEncrypted.FlushFinalBlock();
                    outStreamEncrypted.Close();
                }
                outFs.Close();
            }
        }
Example #39
0
 public byte[] Encrypt(byte[] data)
 {
     cypher.ImportParameters(parameters);
     return(cypher.Encrypt(data, true));
 }
        public static void StartClient()
        {
            // Data buffer for incoming data.
            byte[] bytes = new byte[1024];

            // Connect to a remote device.
            try {
                // Establish the remote endpoint for the socket.
                // This example uses port 11000 on the local computer.
                IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 11000);

                // Create a TCP/IP  socket.
                Socket sender = new Socket(AddressFamily.InterNetwork,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                                      sender.RemoteEndPoint.ToString());

                    // Encode the Hello string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes("Hello");

                    // Send Hello through the socket.
                    int bytesSent = sender.Send(msg);

                    // Receive 64bits Cookie from server
                    int    bytesRec      = sender.Receive(bytes);
                    string Server_Cookie = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    Console.WriteLine("Server Cookie: {0}", Server_Cookie);

                    // Send back Server Cookie through the socket.
                    msg       = Encoding.ASCII.GetBytes(Server_Cookie);
                    bytesSent = sender.Send(msg);

                    // Generate 64bits Cookie
                    string Cookie = GenerateRandomBits(64);

                    Console.WriteLine("Cookie: {0}", Cookie);

                    // Send Cookie through the socket.
                    msg       = Encoding.ASCII.GetBytes(Cookie);
                    bytesSent = sender.Send(msg);
                    System.Threading.Thread.Sleep(50);

                    // Send supported suites to server
                    msg       = Encoding.ASCII.GetBytes("MD5");
                    bytesSent = sender.Send(msg);
                    System.Threading.Thread.Sleep(50);

                    msg       = Encoding.ASCII.GetBytes("SHA256");
                    bytesSent = sender.Send(msg);
                    System.Threading.Thread.Sleep(50);

                    msg       = Encoding.ASCII.GetBytes("Blowfish");
                    bytesSent = sender.Send(msg);
                    System.Threading.Thread.Sleep(50);

                    msg       = Encoding.ASCII.GetBytes("AES");
                    bytesSent = sender.Send(msg);
                    System.Threading.Thread.Sleep(50);

                    // Receive chosen suites
                    bytes    = new byte[1024];
                    bytesRec = sender.Receive(bytes);
                    string suite1 = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    Console.WriteLine("Suite 1: {0}", suite1);
                    System.Threading.Thread.Sleep(50);
                    bytes    = new byte[1024];
                    bytesRec = sender.Receive(bytes);
                    string suite2 = Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    Console.WriteLine("Suite 2: {0}", suite2);
                    System.Threading.Thread.Sleep(150);

                    //Receive X.509 self-signed certificate
                    bytes    = new byte[2048];
                    bytesRec = sender.Receive(bytes);
                    X509Certificate2 Certificate = new X509Certificate2(bytes);
                    //Display Certificate
                    Console.WriteLine(Certificate.ToString(true));

                    string ans;
                    //check certificate
                    do
                    {
                        Console.WriteLine("Do you accept this certificate?(Y,N): ");
                        ans = Console.ReadLine();
                    } while (ans != "Y" && ans != "N" && ans != "y" && ans != "n");

                    if (ans == "Y" || ans == "y")
                    {
                        Console.WriteLine("Certificate is valid!");

                        //Generate 128bit RN
                        String RN = GenerateRandomBits(128);
                        Console.WriteLine("RN: {0}", RN);

                        SHA256 mySHA256 = SHA256Managed.Create();

                        //Cookie_Server | Cookie_Client | RN
                        String C_server_C_client_RN = GetSHA256Hash(mySHA256, Server_Cookie + Cookie + RN);

                        Console.WriteLine("SHA256: {0}", C_server_C_client_RN);

                        //Split SHA256(Cookie_Server | Cookie_Client | RN) in half to make key1 key2
                        string s_key1 = C_server_C_client_RN.Substring(0, (int)(C_server_C_client_RN.Length / 2));
                        string s_key2 = C_server_C_client_RN.Substring((int)(C_server_C_client_RN.Length / 2), (int)(C_server_C_client_RN.Length / 2));

                        Console.WriteLine("Key1: {0}", s_key1);
                        Console.WriteLine("Key2: {0}", s_key2);

                        byte[] key1 = Encoding.ASCII.GetBytes(s_key1);
                        byte[] key2 = Encoding.ASCII.GetBytes(s_key2);

                        //encrypt RN with server public key
                        RSACryptoServiceProvider RSACSP = (RSACryptoServiceProvider)Certificate.PublicKey.Key;
                        byte[] RN_S = Encoding.ASCII.GetBytes(RN);

                        msg       = RSACSP.Encrypt(RN_S, false);
                        bytesSent = sender.Send(msg);
                        System.Threading.Thread.Sleep(50);

                        //generate HMAC(Suite1+Suite2)
                        HMACSHA256 hmac1 = new HMACSHA256(key2);
                        String     hmac  = GetHMACSHA256Hash(hmac1, suite1 + suite2);

                        //send HMAC
                        msg       = Encoding.ASCII.GetBytes(hmac);
                        bytesSent = sender.Send(msg);
                        System.Threading.Thread.Sleep(50);

                        //receive acknowledgement
                        bytes    = new byte[1024];
                        bytesRec = sender.Receive(bytes);
                        string ack = DecryptString(Encoding.ASCII.GetString(bytes, 0, bytesRec), key1);

                        if (ack == "acknowledgement_done")
                        {
                            Console.WriteLine("Everything went good!");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Certificate is not valid!");
                    }

                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                } catch (ArgumentNullException ane) {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                } catch (SocketException se) {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                } catch (Exception e) {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
Example #41
0
 public static string Encrypt(RSACryptoServiceProvider rsa, string value)
 {
     byte[] valueBytes = Encoding.ASCII.GetBytes(value);
     byte[] encrypted  = rsa.Encrypt(valueBytes, false);
     return(Convert.ToBase64String(encrypted));
 }
Example #42
0
        /// <summary>
        /// Enroll the authenticator with the server
        /// </summary>
        public bool Enroll(EnrollState state)
        {
            // clear error
            state.Error = null;

            try
            {
                var    data    = new NameValueCollection();
                var    cookies = state.Cookies = state.Cookies ?? new CookieContainer();
                string response;

                if (string.IsNullOrEmpty(state.OAuthToken) == true)
                {
                    // get session
                    if (cookies.Count == 0)
                    {
                        cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("mobileClientVersion", "3067969+%282.1.3%29"));
                        cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("mobileClient", "android"));
                        cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("steamid", ""));
                        cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("steamLogin", ""));
                        cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("Steam_Language", "english"));
                        cookies.Add(new Uri(COMMUNITY_BASE + "/"), new Cookie("dob", ""));

                        NameValueCollection headers = new NameValueCollection();
                        headers.Add("X-Requested-With", "com.valvesoftware.android.steam.community");

                        response = Request("https://steamcommunity.com/mobilelogin?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client", "GET", null, cookies, headers);
                    }

                    // Steam strips any non-ascii chars from username and password
                    state.Username = Regex.Replace(state.Username, @"[^\u0000-\u007F]", string.Empty);
                    state.Password = Regex.Replace(state.Password, @"[^\u0000-\u007F]", string.Empty);

                    // get the user's RSA key
                    data.Add("username", state.Username);
                    response = Request(COMMUNITY_BASE + "/mobilelogin/getrsakey", "POST", data, cookies);
                    var rsaresponse = JObject.Parse(response);
                    if (rsaresponse.SelectToken("success").Value <bool>() != true)
                    {
                        throw new InvalidEnrollResponseException("Cannot get steam information for user: "******"publickey_exp").Value <string>());
                        p.Modulus  = Authenticator.StringToByteArray(rsaresponse.SelectToken("publickey_mod").Value <string>());
                        rsa.ImportParameters(p);
                        encryptedPassword = rsa.Encrypt(passwordBytes, false);
                    }

                    // login request
                    data = new NameValueCollection();
                    data.Add("password", Convert.ToBase64String(encryptedPassword));
                    data.Add("username", state.Username);
                    data.Add("twofactorcode", "");
                    data.Add("emailauth", (state.EmailAuthText != null ? state.EmailAuthText : string.Empty));
                    data.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile");
                    data.Add("captchagid", (state.CaptchaId != null ? state.CaptchaId : "-1"));
                    data.Add("captcha_text", (state.CaptchaText != null ? state.CaptchaText : "enter above characters"));
                    data.Add("emailsteamid", (state.EmailAuthText != null ? state.SteamId ?? string.Empty : string.Empty));
                    data.Add("rsatimestamp", rsaresponse.SelectToken("timestamp").Value <string>());
                    data.Add("remember_login", "false");
                    data.Add("oauth_client_id", "DE45CD61");
                    data.Add("oauth_scope", "read_profile write_profile read_client write_client");
                    data.Add("donotache", new DateTime().ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds.ToString());
                    response = Request(COMMUNITY_BASE + "/mobilelogin/dologin/", "POST", data, cookies);
                    Dictionary <string, object> loginresponse = JsonConvert.DeserializeObject <Dictionary <string, object> >(response);

                    if (loginresponse.ContainsKey("emailsteamid") == true)
                    {
                        state.SteamId = loginresponse["emailsteamid"] as string;
                    }

                    // require captcha
                    if (loginresponse.ContainsKey("captcha_needed") == true && (bool)loginresponse["captcha_needed"] == true)
                    {
                        state.RequiresCaptcha = true;
                        state.CaptchaId       = (string)loginresponse["captcha_gid"];
                        state.CaptchaUrl      = COMMUNITY_BASE + "/public/captcha.php?gid=" + state.CaptchaId;
                    }
                    else
                    {
                        state.RequiresCaptcha = false;
                        state.CaptchaId       = null;
                        state.CaptchaUrl      = null;
                        state.CaptchaText     = null;
                    }

                    // require email auth
                    if (loginresponse.ContainsKey("emailauth_needed") == true && (bool)loginresponse["emailauth_needed"] == true)
                    {
                        if (loginresponse.ContainsKey("emaildomain") == true)
                        {
                            var emaildomain = (string)loginresponse["emaildomain"];
                            if (string.IsNullOrEmpty(emaildomain) == false)
                            {
                                state.EmailDomain = emaildomain;
                            }
                        }
                        state.RequiresEmailAuth = true;
                    }
                    else
                    {
                        state.EmailDomain       = null;
                        state.RequiresEmailAuth = false;
                    }

                    // require email auth
                    if (loginresponse.ContainsKey("requires_twofactor") == true && (bool)loginresponse["requires_twofactor"] == true)
                    {
                        state.Requires2FA = true;
                    }
                    else
                    {
                        state.Requires2FA = false;
                    }

                    // if we didn't login, return the result
                    if (loginresponse.ContainsKey("login_complete") == false || (bool)loginresponse["login_complete"] == false || loginresponse.ContainsKey("oauth") == false)
                    {
                        if (loginresponse.ContainsKey("oauth") == false)
                        {
                            state.Error = "Invalid response from Steam (No OAuth token)";
                        }
                        if (loginresponse.ContainsKey("message") == true)
                        {
                            state.Error = (string)loginresponse["message"];
                        }
                        return(false);
                    }

                    // get the OAuth token - is stringified json
                    string oauth     = (string)loginresponse["oauth"];
                    var    oauthjson = JObject.Parse(oauth);
                    state.OAuthToken = oauthjson.SelectToken("oauth_token").Value <string>();
                    if (oauthjson.SelectToken("steamid") != null)
                    {
                        state.SteamId = oauthjson.SelectToken("steamid").Value <string>();
                    }
                }

                // login to webapi
                data.Clear();
                data.Add("access_token", state.OAuthToken);
                response = Request(WEBAPI_BASE + "/ISteamWebUserPresenceOAuth/Logon/v0001", "POST", data);

                var sessionid = cookies.GetCookies(new Uri(COMMUNITY_BASE + "/"))["sessionid"].Value;

                if (state.RequiresActivation == false)
                {
                    data.Clear();
                    data.Add("op", "has_phone");
                    data.Add("arg", "null");
                    data.Add("sessionid", sessionid);

                    response = Request(COMMUNITY_BASE + "/steamguard/phoneajax", "POST", data, cookies);
                    var  jsonresponse = JObject.Parse(response);
                    bool hasPhone     = jsonresponse.SelectToken("has_phone").Value <Boolean>();
                    if (hasPhone == false)
                    {
                        state.OAuthToken    = null;                      // force new login
                        state.RequiresLogin = true;
                        state.Cookies       = null;
                        state.Error         = "Your Steam account must have a SMS-capable phone number attached. Go into Account Details of the Steam client or Steam website and click Add a Phone Number.";
                        return(false);
                    }

                    //response = Request(COMMUNITY_BASE + "/steamguard/phone_checksms?bForTwoFactor=1&bRevoke2fOnCancel=", "GET", null, cookies);

                    // add a new authenticator
                    data.Clear();
                    string deviceId = BuildRandomId();
                    data.Add("access_token", state.OAuthToken);
                    data.Add("steamid", state.SteamId);
                    data.Add("authenticator_type", "1");
                    data.Add("device_identifier", deviceId);
                    data.Add("sms_phone_id", "1");
                    response = Request(WEBAPI_BASE + "/ITwoFactorService/AddAuthenticator/v0001", "POST", data);
                    var tfaresponse = JObject.Parse(response);
                    if (response.IndexOf("status") == -1 && tfaresponse.SelectToken("response.status").Value <int>() == 84)
                    {
                        // invalid response
                        state.OAuthToken    = null;                      // force new login
                        state.RequiresLogin = true;
                        state.Cookies       = null;
                        state.Error         = "Unable to send SMS. Check your phone is registered on your Steam account.";
                        return(false);
                    }
                    if (response.IndexOf("shared_secret") == -1)
                    {
                        // invalid response
                        state.OAuthToken    = null;                      // force new login
                        state.RequiresLogin = true;
                        state.Cookies       = null;
                        state.Error         = "Invalid response from Steam: " + response;
                        return(false);
                    }

                    // save data into this authenticator
                    var secret = tfaresponse.SelectToken("response.shared_secret").Value <string>();
                    this.SecretKey       = Convert.FromBase64String(secret);
                    this.Serial          = tfaresponse.SelectToken("response.serial_number").Value <string>();
                    this.DeviceId        = deviceId;
                    state.RevocationCode = tfaresponse.SelectToken("response.revocation_code").Value <string>();

                    // add the steamid into the data
                    var steamdata = JObject.Parse(tfaresponse.SelectToken("response").ToString());
                    if (steamdata.SelectToken("steamid") == null)
                    {
                        steamdata.Add("steamid", state.SteamId);
                    }
                    if (steamdata.SelectToken("steamguard_scheme") == null)
                    {
                        steamdata.Add("steamguard_scheme", "2");
                    }
                    this.SteamData = steamdata.ToString(Newtonsoft.Json.Formatting.None);

                    // calculate server drift
                    long servertime = tfaresponse.SelectToken("response.server_time").Value <long>() * 1000;
                    ServerTimeDiff = servertime - CurrentTime;
                    LastServerTime = DateTime.Now.Ticks;

                    state.RequiresActivation = true;

                    return(false);
                }

                // finalize adding the authenticator
                data.Clear();
                data.Add("access_token", state.OAuthToken);
                data.Add("steamid", state.SteamId);
                data.Add("activation_code", state.ActivationCode);

                // try and authorise
                var retries = 0;
                while (state.RequiresActivation == true && retries < ENROLL_ACTIVATE_RETRIES)
                {
                    data.Add("authenticator_code", this.CalculateCode(false));
                    data.Add("authenticator_time", this.ServerTime.ToString());
                    response = Request(WEBAPI_BASE + "/ITwoFactorService/FinalizeAddAuthenticator/v0001", "POST", data);
                    var finalizeresponse = JObject.Parse(response);
                    if (response.IndexOf("status") != -1 && finalizeresponse.SelectToken("response.status").Value <int>() == INVALID_ACTIVATION_CODE)
                    {
                        state.Error = "Invalid activation code";
                        return(false);
                    }

                    // reset our time
                    if (response.IndexOf("server_time") != -1)
                    {
                        long servertime = finalizeresponse.SelectToken("response.server_time").Value <long>() * 1000;
                        ServerTimeDiff = servertime - CurrentTime;
                        LastServerTime = DateTime.Now.Ticks;
                    }

                    // check success
                    if (finalizeresponse.SelectToken("response.success").Value <bool>() == true)
                    {
                        if (response.IndexOf("want_more") != -1 && finalizeresponse.SelectToken("response.want_more").Value <bool>() == true)
                        {
                            ServerTimeDiff += ((long)this.Period * 1000L);
                            retries++;
                            continue;
                        }
                        state.RequiresActivation = false;
                        break;
                    }

                    ServerTimeDiff += ((long)this.Period * 1000L);
                    retries++;
                }
                if (state.RequiresActivation == true)
                {
                    state.Error = "There was a problem activating. There might be an issue with the Steam servers. Please try again later.";
                    return(false);
                }

                // mark and successful and return key
                state.Success   = true;
                state.SecretKey = Authenticator.ByteArrayToString(this.SecretKey);

                // send confirmation email
                data.Clear();
                data.Add("access_token", state.OAuthToken);
                data.Add("steamid", state.SteamId);
                data.Add("email_type", "2");
                response = Request(WEBAPI_BASE + "/ITwoFactorService/SendEmail/v0001", "POST", data);

                return(true);
            }
            catch (UnauthorisedRequestException ex)
            {
                throw new InvalidEnrollResponseException("You are not allowed to add an authenticator. Have you enabled 'community-generated content' in Family View?", ex);
            }
            catch (InvalidRequestException ex)
            {
                throw new InvalidEnrollResponseException("Error enrolling new authenticator", ex);
            }
        }
Example #43
0
        public static void Main(string[] args)
        {
            Console.WriteLine("This application demonstrates 3 problems with the OnlyKey.\n" +
                              "Please insert an OnlyKey, and put it in configuration mode.\n" +
                              "RSA Key #4, and the lables for several keys will be overwritten.\n" +
                              "Press ENTER when ready.");
            Console.ReadLine();
            var onlyKey = new OnlyKey();

            Console.WriteLine("Generating first RSA 2048 key... ");
            var rsa1 = new RSACryptoServiceProvider(2048);
            var key1 = rsa1.ExportParameters(true);

            Console.WriteLine("Done");


            Console.WriteLine("\n\nDemonstrating problem #1: Cannot set RSA Key labels" +
                              "\n===================================================");
            Console.WriteLine("Attempting to set values using 25-29");
            Console.WriteLine("first... ");
            var response = onlyKey.SetField(SlotId.RsaKey1, Field.Label, "first");

            Console.WriteLine(response);
            Console.WriteLine("second...");
            response = onlyKey.SetField(SlotId.RsaKey2, Field.Label, "second");
            Console.WriteLine(response);
            Console.WriteLine("third...");
            response = onlyKey.SetField(SlotId.RsaKey3, Field.Label, "third");
            Console.WriteLine(response);
            Console.WriteLine("fourth...");
            response = onlyKey.SetField(SlotId.RsaKey4, Field.Label, "fourth");
            Console.WriteLine(response);
            Console.WriteLine("ecc...");
            response = onlyKey.SetField(SlotId.EccKey1, Field.Label, "ecc");
            Console.WriteLine(response);
            var keyLabels = onlyKey.GetKeyLabels();

            foreach (var key in keyLabels)
            {
                Console.WriteLine($"\t{key.Key}: {key.Value}");
            }

            Console.WriteLine("Attempting to set values using 1-4");
            Console.WriteLine("first... ");
            response = onlyKey.SetField((SlotId)1, Field.Label, "first");
            Console.WriteLine(response);
            Console.WriteLine("second...");
            response = onlyKey.SetField((SlotId)2, Field.Label, "second");
            Console.WriteLine(response);
            Console.WriteLine("third...");
            response = onlyKey.SetField((SlotId)3, Field.Label, "third");
            Console.WriteLine(response);
            Console.WriteLine("fourth...");
            response = onlyKey.SetField((SlotId)4, Field.Label, "fourth");
            Console.WriteLine(response);
            keyLabels = onlyKey.GetKeyLabels();
            foreach (var key in keyLabels)
            {
                Console.WriteLine($"\t{key.Key}: {key.Value}");
            }


            Console.WriteLine("\n\nDemonstrating problem #2: OnlyKey's internal buffer is not cleared in timely manner after decrypting" +
                              "\n====================================================================================================");
            Console.WriteLine("Writing RSA Key 1 to slot 4... ");
            response = onlyKey.SetPrivateKey(SlotId.RsaKey4, KeyFeatures.Decryption, key1);
            Console.WriteLine(response);

            var testMessageA = "Decryption successful A";
            var testMessageB = "Decryption successful B";

            Console.WriteLine($"Encrypting \"{testMessageA}\" with RSA public key 1... ");
            var encryptedA = rsa1.Encrypt(ASCII.GetBytes(testMessageA), false);

            Console.WriteLine("Done");

            Console.WriteLine($"Encrypting \"{testMessageB}\" with RSA public key 1... ");
            var encryptedB = rsa1.Encrypt(ASCII.GetBytes(testMessageB), false);

            Console.WriteLine("Done");

            Console.WriteLine("Asking OnlyKey to decrypt message A...");
            var decrypted = onlyKey.DecryptString(SlotId.RsaKey4, encryptedA);

            Console.WriteLine("OnlyKey says: " + decrypted +
                              "\n Is it the same? " + decrypted == testMessageA);

            Console.WriteLine("Asking OnlyKey for key labels...");
            keyLabels = onlyKey.GetKeyLabels();
            foreach (var key in keyLabels)
            {
                Console.WriteLine($"\t{key.Key}: {key.Value}");
            }

            Console.WriteLine("Asking OnlyKey `` decrypt message B...");
            decrypted = onlyKey.DecryptString(SlotId.RsaKey4, encryptedB);
            Console.WriteLine("OnlyKey says: " + decrypted +
                              "\n Is it the same? " + decrypted == testMessageB);


            Console.WriteLine("\nDemonstrating problem #1: Cannot set key after decryption without removing and re-inserting device, otherwise the returned public key is incorrect" +
                              "\n================================================================================================================================================");
            Console.WriteLine("Generating second RSA 2048 key... ");
            var rsa2 = new RSACryptoServiceProvider(2048);
            var key2 = rsa2.ExportParameters(true);

            Console.WriteLine("Done");

            Console.WriteLine("Writing RSA Key 2 to slot 4... ");
            response = onlyKey.SetPrivateKey(SlotId.RsaKey4, KeyFeatures.Decryption, key2);
            Console.WriteLine(response);

            Console.WriteLine("Asking OnlyKey for RSA public from slot 4... ");
            var publicRepro = onlyKey.GetPublicRsaKey(SlotId.RsaKey4, rsa1.KeySize / 8);

            Console.WriteLine("Done");
            Console.WriteLine("The real public key is " + string.Join(", ", key2.Modulus) +
                              "\nOnlyKey says the public key is " + string.Join(", ", publicRepro.Modulus) +
                              $"\nAre they the same? {publicRepro.Modulus.SequenceEqual(key2.Modulus)}");


            Console.WriteLine("\n\nUnit tests complete. Press Enter to quit.");
            Console.ReadLine();
        }
Example #44
0
        public static void UnusualExponentCryptRoundtrip()
        {
            byte[] crypt;
            byte[] output;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.UnusualExponentParameters);

                crypt = rsa.Encrypt(TestData.HelloBytes, true);
                output = rsa.Decrypt(crypt, true);
            }

            Assert.NotEqual(crypt, output);
            Assert.Equal(TestData.HelloBytes, output);
        }
Example #45
0
    public void writeText(string emri, string mesazhi,string path,string token)
        {
            faza3 f3 = new faza3();
            if (f3.status(token) == "Nuk ekziston")
            {
                Console.WriteLine(" Tokeni nuk ekziston ");
            }
            else
            {
              string[] tokench = token.Split();
            
        
            DES DESalg = DES.Create();
            byte[] keyb = new byte[8];
            byte[] ivb = new byte[8];
            keyb = DESalg.Key;

            ivb = DESalg.IV;
            Random rand = new Random();

            string KEY = Convert.ToBase64String(keyb);
            string IV = Convert.ToBase64String(ivb);
            
              
            string enctext = encrypt(emri, mesazhi, KEY, IV);
            string filere = File.ReadAllText("C:/Users/hp/Desktop/keys/users.txt");
            string[] a = filere.Split();
            string h = "";
            for (int i = 0; i < a.Length; i++)
                {
                    if (tokench[0] == a[i]) { h = a[i - 1]; }
                }
                
             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
             var privatekey = File.ReadAllText("C:/Users/hp/Desktop/keys/" + h + "pri.xml");
             rsa.FromXmlString(privatekey);  
             byte[] msgb = Encoding.ASCII.GetBytes(arg[3]);

            string[] arg = enctext.Split();
            string filepath = "C:/Users/hp/Desktop/keys/users.txt";
            arg[0] = arg[0] + " ";
            File.AppendAllText(filepath, arg[0]);
        
        string encr = enctext + " " + Convert.ToBase64String(rsa.Encrypt(msgb, true)) + " " + tokench[0];        
              
        if (String.IsNullOrEmpty(path))
        {
            Console.WriteLine("Encrypted ...:        " + encr);
            

        }
        else
        {
            File.WriteAllText(path + emri + "encrypted.xml", encr)
            Console.WriteLine(" Teksti u ruajt ne :   C:/Users/hp/Desktop/keys/  ");


        }

        string filepath = "C:/Users/hp/Desktop/keys/users.txt";
        emri = emri + " ";
        File.AppendAllText(filepath, emri);


        
        arg[0] = arg[0] + " ";
        File.AppendAllText(filepath, arg[0]);

            
            
            

        }
Example #46
0
    private byte[] RSAEncrypt( byte [] PlainText )
    {
        string n =
            "59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUtwC" +
            "5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDR" +
            "KSKv6kDqnw4UwPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuB" +
            "OitnZ/bDzPHrTOZz0Dew0uowxf/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJ" +
            "Q+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/UAaHqn9JdsBWLUEpVviYnh" +
            "imNVvYFZeCXg/IdTQ+x4IRdiXNv5hEew==";
        string e = "AQAB";

        RSAParameters key = new RSAParameters();
        key.Modulus = Convert.FromBase64String( n );
        key.Exponent = Convert.FromBase64String( e );
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        rsa.ImportParameters( key );

        return rsa.Encrypt( PlainText, true );
    }
Example #47
0
        /// <summary>
        /// Encrypts the specified algorithm.
        /// The Asymmetric Algorithm includes DSA,ECDiffieHellman, ECDsa and RSA.
        /// Code Logic:
        /// 1. Input encrypt algorithm and plain text.
        /// 2. Read the public key from stream.
        /// 3. Serialize plian text to byte array.
        /// 4. Encrypt the plian text array by public key.
        /// 5. Return ciphered string.
        /// </summary>
        /// <param name="algorithm">The algorithm.</param>
        /// <param name="plainText">The plain text.</param>
        /// <returns></returns>
        public static string Encrypt(RSACryptoServiceProvider algorithm, string plainText)
        {
            string        publicKey;
            List <Byte[]> cipherArray = new List <byte[]>();

            //// read the public key.
            using (StreamReader streamReader = new StreamReader("PublicOnlyKey.xml"))
            {
                publicKey = streamReader.ReadToEnd();
            }
            algorithm.FromXmlString(publicKey);

            BinaryFormatter binaryFormatter = new BinaryFormatter();

            byte[] plainBytes = null;


            //// Use BinaryFormatter to serialize plain text.
            using (MemoryStream memoryStream = new MemoryStream())
            {
                binaryFormatter.Serialize(memoryStream, plainText);
                plainBytes = memoryStream.ToArray();
            }

            int totLength = 0;
            int index     = 0;

            //// Encrypt plain text by public key.
            if (plainBytes.Length > 80)
            {
                byte[] partPlainBytes;
                byte[] cipherBytes;
                myArray = new List <byte[]>();
                while (plainBytes.Length - index > 0)
                {
                    partPlainBytes = plainBytes.Length - index > 80 ? new byte[80] : new byte[plainBytes.Length - index];

                    for (int i = 0; i < 80 && (i + index) < plainBytes.Length; i++)
                    {
                        partPlainBytes[i] = plainBytes[i + index];
                    }
                    myArray.Add(partPlainBytes);

                    cipherBytes = algorithm.Encrypt(partPlainBytes, false);
                    totLength  += cipherBytes.Length;
                    index      += 80;

                    cipherArray.Add(cipherBytes);
                }
            }

            //// Convert to byte array.
            byte[] cipheredPlaintText = new byte[totLength];
            index = 0;
            foreach (byte[] item in cipherArray)
            {
                for (int i = 0; i < item.Length; i++)
                {
                    cipheredPlaintText[i + index] = item[i];
                }

                index += item.Length;
            }
            return(Convert.ToBase64String(cipheredPlaintText));
        }
Example #48
0
 public static byte[] Encrypt(byte[] bytes, string publicKeyXml, RsaKeyLengths rsaKeyLength = RsaKeyLengths.Bit2048)
 {
     using (var rsa = new RSACryptoServiceProvider((int)rsaKeyLength))
     {
         rsa.FromXmlString(publicKeyXml);
         return rsa.Encrypt(bytes, DoOAEPPadding);
     }
 }
Example #49
0
 public static byte[] Encrypt(byte[] toDecrypt)
 {
     return(_provider.Encrypt(toDecrypt, false));
 }
Example #50
0
    public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
    {
        try
        {
            //Create a new instance of RSACryptoServiceProvider.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            //Import the RSA Key information. This only needs
            //toinclude the public key information.
            RSA.ImportParameters(RSAKeyInfo);

            //Encrypt the passed byte array and specify OAEP padding.
            //OAEP padding is only available on Microsoft Windows XP or
            //later.
            return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
        }
            //Catch and display a CryptographicException
            //to the console.
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }
    }
Example #51
0
    private static Byte[] Encrypt(string msg)
    {
        var pubParams = "";

        using (var reader = new StreamReader(new FileStream("1.pub", FileMode.Open)))
        {
            pubParams = reader.ReadToEnd();
        }

        using (var rsa = new RSACryptoServiceProvider())
        {
            rsa.FromXmlString(pubParams);

            return rsa.Encrypt(ByteConverter.GetBytes(msg), false);
        }
    }