blog.darkstar.work - a simple url encoder/decoder

 a simple url encoder/decoder
 http://blog.darkstar.work

Labels

Wirtschaft (150) Pressefreiheit (125) Österreich (120) IT (95) code (60) Staatsschulden (37) EZB (27) Pensionssystem (16)

2014-07-19

a simple twitter login tester in C#

using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Web;
using System.Windows.Forms;
// [...]

namespace TweetBotTestForm
{
    public partial class Form1 : Form
    {
        const string AUTHURL = "https://twitter.com/sessions";

        public Form1()
        {
            InitializeComponent();
            this.textUsername.Text = "AAA@BBB";
            this.textPassword.Text = "XXXXXXX";
        }
    

        private void buttonLogin_Click(object sender, EventArgs e)
        {
            this.textOutput.Clear();
            this.textOutput.Text = string.Format(
                "Posting Username \'{0}\' Password \'{1}\' in {2}\r\n\n",
                this.textUsername.Text, this.textPassword.Text, AUTHURL);

            Dictionary<string, string> postParams =
                new Dictionary<string, string>();

            postParams.Add("session[username_or_email]", textUsername.Text);
            postParams.Add("session[password]", textPassword.Text);
            postParams.Add("remember_me", "0");
            postParams.Add("redirect_after_login", "/");

            string responseText = this.HttpPostLogin(AUTHURL, postParams);
            this.textOutput.Text += "AuthToken: " + responseText + "\r\n\n";

            string webResultText = this.LoginTweet(AUTHURL,
                this.textUsername.Text, this.textPassword.Text);
            this.textOutput.Text += "WebClient: " + webResultText + "\r\n\n";

        }       

        /// <summary>
        /// twitter login test
        /// by using System.Net.WebClient class
        /// </summary>
        /// <param name="authUrl">twitter session url</param>
        /// <param name="username">username</param>
        /// <param name="password">password</param>
        /// <returns>AuthToken</returns>
        protected string LoginTweet(
            string authUrl,
            string username,
            string password
        )
        {
            WebClient webClient = new WebClient();

            NameValueCollection formData = new NameValueCollection();
            // formData["authenticity_token"] = "3f962756ee8ab2afb0e0cb35ae1c97117844a6c7";
            formData["remember_me"] = "0";
            formData["redirect_after_login"] = "/";
            formData["return_to_ssl"] = "false";
            formData["scribe_log"] = string.Empty;
            formData["session[username_or_email]"] = username;
            formData["session[password]"] = password;

           
            byte[] responseBytes =
                webClient.UploadValues(authUrl, "POST", formData);
            string result = Encoding.UTF8.GetString(responseBytes);

            webClient.Dispose();

            string authResponse = ParseTwitterSession(ref result);

            return authResponse; // result;
        }

        /// <summary>
        /// twitter login test
        /// by using System.Net.HttpWebRequest/HttpWebResponse class
        /// </summary>
        /// <param name="authUrl"></param>
        /// <param name="postParameters"></param>
        /// <returns></returns>
        protected string HttpPostLogin(
            string authUrl,
            Dictionary<string, string> postParameters
        )
        {
            string postData = "";

            foreach (string key in postParameters.Keys)
            {
                postData += HttpUtility.UrlEncode(key) + "="
                      + HttpUtility.UrlEncode(postParameters[key]) + "&";
            }

            HttpWebRequest myHttpWebRequest =
                (HttpWebRequest)HttpWebRequest.Create(authUrl);
            myHttpWebRequest.Method = "POST";

            byte[] data = Encoding.ASCII.GetBytes(postData);

            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.ContentLength = data.Length;

            Stream requestStream = myHttpWebRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            HttpWebResponse myHttpWebResponse =
                (HttpWebResponse)myHttpWebRequest.GetResponse();

            this.textOutput.Text += "\r\n Cookie Count = " +
                myHttpWebResponse.Cookies.Count.ToString();
            this.textOutput.Text += "\r\n Header = " +
                myHttpWebResponse.Headers.ToString();
            this.textOutput.Text += "\r\n";

            Stream responseStream = myHttpWebResponse.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(
                responseStream,
                Encoding.Default
            );
            string pageContent = myStreamReader.ReadToEnd();

            myStreamReader.Close();
            responseStream.Close();
            myHttpWebResponse.Close();

            string authResponse = ParseTwitterSession(ref pageContent);

            return authResponse; // pageContent;
        }


        /// <summary>
        /// Dummy html code in response parsing
        /// very quick & dirty implemented
        /// </summary>
        /// <param name="pageContent">html response from webclient</param>
        /// <returns>authentication_token</returns>
        protected static string ParseTwitterSession(ref string pageContent)
        {
            string authResponse = string.Empty;
            if (pageContent.IndexOf("authenticity_token") < 0)
            {
                return authResponse;
            }
            pageContent = pageContent.Substring(

                pageContent.IndexOf("authenticity_token") + 18);

            while (pageContent.IndexOf("value=\"") > -1)
            {
                pageContent = pageContent.Substring(
                    pageContent.IndexOf("value=") + 8
                );
                if (pageContent.IndexOf('\"') > -1)
                {
                    string valueString =
                        pageContent.Substring(
                            0,
                            pageContent.IndexOf("\"")
                        );

                    if (valueString.Length > 37)
                    {
                        authResponse = valueString;
                        break;
                    }
                }
                else
                {
                    authResponse = string.Empty;
                    break;
                }
            }
            return authResponse;
        }

    }
}



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Web;

namespace TwitterTestLogon
{
    public partial class TweetLogin : Form
    {
        const string AUTHURL = "https://twitter.com/sessions";

        public TweetLogin()
        {
            InitializeComponent();
            this.textUsername.Text = "myemail@mydomain.org";
            this.textPassword.Text = "mypassword";
        }
  

        /// <summary>
        /// event that is fired, when buttonLogin clicked
        /// </summary>
        /// <param name="sender">sender, that fires event</param>
        /// <param name="e">EventArgs e</param>
        private void buttonLogin_Click(object sender, EventArgs e)
        {
            this.textOutput.Clear();
            this.textOutput.Text = string.Format(
                "Posting Username \'{0}\' Password \'{1}\' in {2}\r\n\n",
                this.textUsername.Text, this.textPassword.Text, AUTHURL);

            // create Dictionary<string, string> postParams with default parameters to post for twitter login
            Dictionary<string, string> postParams = new Dictionary<string, string>();
            postParams.Add("session[username_or_email]", textUsername.Text);
            postParams.Add("session[password]", textPassword.Text);
            postParams.Add("remember_me", "0");
            postParams.Add("redirect_after_login", "/");
            postParams.Add("return_to_ssl", "false");
            // postParams.Add("scribe_log", string.Empty);


            // get authentication Parameters from twitter Login via HttpPostLogin(AUTHURL, postParams);
            Dictionary<string, string> authTwitterParams = this.HttpPostLogin(AUTHURL, postParams);
            // write authentication Parameters to TextBox textOutput
            this.textOutput.Text += "\r\nTwitter Login POSTING via HttpWebRequest: \r\n";
            foreach (string ikey in authTwitterParams.Keys)
            {
                string ivalue =  authTwitterParams[ikey];
                this.textOutput.Text += ikey + " \t= "
                    + authTwitterParams[ikey] + "\r\n";
                
                try
                {
                    // add 4 authentication twitter parameters to postParams
                    if (ikey.StartsWith("Set-Cookie"))
                    {
                        string guest_id = HttpUtility.UrlDecode(ParseTwitterSession(ivalue, "guest_id"));
                        postParams.Add("guest_id", guest_id);
                        this.textOutput.Text += "guest_id" + " \t= " + guest_id + "\r\n";

                        string _twitter_sess = ParseTwitterSession(ivalue, "_twitter_sess");
                        postParams.Add("_twitter_sess", _twitter_sess);
                        this.textOutput.Text += "_twitter_sess" + " \t= " + _twitter_sess + "\r\n";

                        string ct0 = ParseTwitterSession(ivalue, "ct0");
                        postParams.Add("ct0", ct0);
                        this.textOutput.Text += "ct0" + " \t= " + ct0 + "\r\n";

                        string tdomain  = ParseTwitterSession(ivalue, "Domain");
                        postParams.Add("Domain", tdomain);
                        this.textOutput.Text += "Domain" + " \t= " + tdomain + "\r\n";
                    }   
                }
                catch (Exception ex)
                {
                    this.textOutput.Text += "\r\nException: " + ex.ToString() + "\r\n";
                }
            }

            // pass postParams from Dictionary<string, string> to NameValueCollection formData 
            NameValueCollection formData = new NameValueCollection();
            foreach (string pkey in postParams.Keys) { formData[pkey] = postParams[pkey]; }

            // get authentication Parameters from twitter Login via WebClientLoginTwitter(AUTHURL, formData);
            Dictionary<string, string> gotAuthParams = this.WebClientLoginTwitter(AUTHURL, formData);
            // write authentication Parameters to TextBox textOutput
            this.textOutput.Text += "\r\nTwitter Login POSTING via WebClient: \r\n";
            foreach (string ikey in gotAuthParams.Keys)
            {
                this.textOutput.Text += ikey + " \t= "
                        + gotAuthParams[ikey] + "\r\n";
            }            

        }
  

        /// <summary>
        /// twitter login test
        /// by using System.Net.HttpWebRequest/HttpWebResponse class
        /// </summary>
        /// <param name="authUrl">twitter session url</param>
        /// <param name="postParameters">parameter collection, that will be POSTed urlencoded to requested authUrl</param>
        /// <returns>Dictionary<string, string> authParams from response Headers and authenticity_token from response body</returns>
        protected Dictionary<string, string> HttpPostLogin(
   string authUrl, 
   Dictionary<string, string> postParameters
  )
        {
            string postData = "";
            // add all postParameters as an UrlEncoded string
            foreach (string key in postParameters.Keys)
            {
                postData += HttpUtility.UrlEncode(key) + "="
                      + HttpUtility.UrlEncode(postParameters[key]) + "&";
            }
            // get postData as byte[]
            byte[] data = Encoding.ASCII.GetBytes(postData);

            // create HttpWebRequest via authUrl // set POST Method, ContentType, ContentLength
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(authUrl); 
            myHttpWebRequest.Method = "POST";
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
            myHttpWebRequest.ContentLength = data.Length;

            // Write postParameters as byte[] to RequestStream of created HttpWebRequest
            Stream requestStream = myHttpWebRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();

            // get HttpWebResponse now from HttpWebRequest
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

            // create twitterResponseHeaders Dictionary<string, string> 
            Dictionary<string, string> twitterResponseHeaders = new Dictionary<string, string>();

            // add key values from HttpWebResponse.Headers to twitterResponseHeaders Dictionary<string, string> 
            foreach (string hkey in myHttpWebResponse.Headers.AllKeys)
            {
                string hvalue = myHttpWebResponse.Headers[hkey];
                twitterResponseHeaders.Add(hkey, hvalue);
            }

            // get ResponseStream from HttpWebResponsem, read Content of ResponseStream and store it in string pageContent
            Stream responseStream = myHttpWebResponse.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);
            string pageContent = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            responseStream.Close();

            // close HttpWebResponse received from HttpWebRequest
            myHttpWebResponse.Close();

            // parse authenticity_token hidden form value from received pageContent
            string authenticity_token = ParseTwitterAuthValue(ref pageContent, "authenticity_token");
            // and add it to twitterResponseHeaders Dictionary<string, string> 
            twitterResponseHeaders.Add("authenticity_token", authenticity_token);

            return twitterResponseHeaders; // pageContent;
        }
  

        /// <summary>
        /// twitter login test
        /// using System.Net.WebClient class
        /// </summary>
        /// <param name="authUrl">twitter session url</param>
        /// <param name="authParams">parameter collection, that will be POSTed as NameValueCollection formData to requested authUrl</param>
        /// <returns>Dictionary<string, string> authParams from response Headers and authenticity_token from response body</returns>
        protected Dictionary<string, string> WebClientLoginTwitter(
   string authUrl, 
   NameValueCollection formData
  )
        {
            WebClient webClient = new WebClient();

            // add authParams to NameValueCollection formData
           

            // POST to authUrl pairs in NameValueCollection formData via WebClient.UploadValues
            byte[] responseBytes = webClient.UploadValues(authUrl, "POST", formData);
            string result = Encoding.UTF8.GetString(responseBytes);

            Dictionary<string, string> responseHeaders = new Dictionary<string, string>();
            for (int rh = 0; rh < webClient.ResponseHeaders.Keys.Count; rh++)
            {
                string rhkey = webClient.ResponseHeaders.Keys[rh];
                string rhvalue = webClient.ResponseHeaders[rhkey];
                responseHeaders.Add(rhkey, rhvalue);
            }

            webClient.Dispose();
            
            string authResponse = ParseTwitterAuthValue(ref result, "authenticity_token");
            responseHeaders.Add("authenticity_token", authResponse);

            return responseHeaders; // result;
        }

  
        /// <summary>
        /// Dummy html code in response parsing
        /// very quick & dirty implemented
        /// </summary>
        /// <param name="pageContent">html response from webclient or httpwebresponse</param>
        /// <returns>authentication_token</returns>
        protected static string ParseTwitterAuthValue(ref string pageContent, string parseString)
        {
            int parseStringLength = parseString.Length; 
            if (string.IsNullOrEmpty(parseString) || (parseStringLength < 2)) {
                throw new ArgumentException("ParseTwitterSession(ref string pageContent, string parseString)\r\n, parseString is null, empty or to short for parse...");
            }
            
            string authResponse = string.Empty;
            if (pageContent.IndexOf(parseString) < 0)
            {
                return authResponse;
            }
            pageContent = pageContent.Substring(
                pageContent.IndexOf(parseString) + parseStringLength);

            while (pageContent.IndexOf("value=\"") > -1)
            {
                pageContent = pageContent.Substring(
                    pageContent.IndexOf("value=") + 8
                );
                if (pageContent.IndexOf('\"') > -1)
                {
                    string valueString =
                        pageContent.Substring(
                            0,
                            pageContent.IndexOf("\"")
                        );

                    if (valueString.Length > 37)
                    {
                        authResponse = valueString;
                        break;
                    }
                }
                else
                {
                    authResponse = string.Empty;
                    break;
                }
            }
            return authResponse;
        }

  
        /// <summary>
        /// Dummy html code in response parsing
        /// very quick & dirty implemented
        /// </summary>
        /// <param name="pageContent">html response from webclient or httpwebresponse</param>
        /// <returns>authentication_token</returns>
        protected static string ParseTwitterSession(string contentForSearch, string parseString)
        {
            int parseStringLength = parseString.Length;
            if (string.IsNullOrEmpty(parseString) || (parseStringLength < 2))
            {
                throw new ArgumentException("ParseTwitterSession(ref string pageContent, string parseString)\r\n, parseString is null, empty or to short for parse...");
            }
            string content2Parse = contentForSearch;
            string parsedValue = string.Empty;

            if (content2Parse.IndexOf(parseString) < 0)
            {
                return parsedValue;
            }
            content2Parse = content2Parse.Substring(
                content2Parse.IndexOf(parseString) + parseStringLength);

            while (content2Parse.IndexOf("=") > -1)
            {
                content2Parse = content2Parse.Substring(
                    content2Parse.IndexOf("=") + 1
                );
                if (content2Parse.IndexOf(';') > -1)
                {
                    string valueString =
                        content2Parse.Substring(
                            0,
                            content2Parse.IndexOf(";")
                        );

                    if (valueString.Length > 1)
                    {
                        parsedValue = valueString;
                        break;
                    }
                }
                else
                {
                    parsedValue = content2Parse;
                    break;
                }
            }
            return parsedValue;
        }

    }
}

2014-07-13

decode OpenSSL PrivateKey with user salt in C#

  1. public static byte[UserSalzDerAndroschErhalts(string saltIn, out string saltOut{
  2.   StringReader sreader = new StringReader(saltIn);
  3.   saltOut = String.Empty;
  4.   if(!sreader.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED"))
  5.     return null;

  6.   string saltline = sreader.ReadLine();
  7.   if(!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,") )
  8.     return null;

  9.   string saltstr saltline.Substring(saltline.IndexOf(",") + 1).Trim();

  10.   byte[] saltbytes = new byte[saltstr.Length/2];
  11.   for (int i 0; i saltbytes.Length; i++) {
  12.     saltbytes[i] = Convert.ToByte(saltstr.Substring (22)16);
  13.   }

  14.   if (!(sreader.ReadLine() == ""))
  15.     return null;
  16.   // read rest of base64 data and you have the RSA key
  17.   saltOut = sreader.ReadToEnd() 
  18.   // Console.Writeln("cryptkey " + saltOut);
  19.   return saltbytes;
  20. }  
  1. public static byte[] DecodeOpenSSLPrivateKey(string instr{
  2.   const string pemprefix = "-----BEGIN RSA PRIVATE KEY-----" ;
  3.   const string pemsuffix = "-----END RSA PRIVATE KEY-----" ;
  4.   string pemstr = instr.Trim() ;
  5.   if(!pemstr.StartsWith(pemprefix) || !pemstr.EndsWith(pemsuffix)) {
  6.     throw new ArgumentException("missing BEGIN or END sequence of RSA private Key");
  7.   }

  8.   string pvkstr = 
  9.     pemstr.Replace(pemprivheader, "").Replace(pemprivfooter, "").Trim(); //remove
  10.   
  11.   byte[] binkey;
  12.   try { // there aren't any PEM encryption infos => UNencrypted PEM private key
  13.     binkey = Convert.FromBase64String(pvkstr) ;
  14.     return binkey;
  15.   }
  16.   catch(System.FormatException) { 
  17.     //Console.WriteLine("We have a full encrypted OpenSSL PEM private key");  
  18.   }

  19.   string encryptedstr = string.Empty;

  20.   // read crypted chiffer lets extract salt
  21.   byte[] salt = UserSalzDerAndroschErhalts(pvkstr, out encryptedstr);
  22.   if (salt == null || string.IsNullOrEmpty(encryptedstr)) {
  23.     throw new ArgumentException("invalid RSA private Key");
  24.   }

  25.   try { // it's an encrypted RSA key?
  26.     binkey = Convert.FromBase64String(encryptedstr);
  27.   }
  28.   catch(System.FormatException) {  
  29.     throw; // rethrow the Exception
  30.   }
  31.   // 3DES SSL key fetch 
  32.   SecureString passwd3DES = GetSecPswd("Enter password for 3DESkey==>") ;
  33.   // Console.Write("\nEnter password for key: ");
  34.   // string passwd = Console.ReadLine();
  35.   byte[] tripledes = GetOpenSSL3deskey(salt, passwd3DES, 12);    
  36.   if (tripledes == null{
  37.     throw new ArgumentException("error decrypting 3DES key\n" + salt.ToString());
  38.   }
  39.   // Decrypt the encrypted 3DES key by using salt from PEM header
  40.   // same method how anonymous hacked IV
  41.   byte[] rsakey = DecryptKey(binkey, tripledes, salt);    
  42.   if (rsakey == null{
  43.     throw new ArgumentException("error decrypting 3DES key\n" + salt.ToString());
  44.   }

  45.   return rsakey; // return decrypted RSA private key
  46. }

2014-06-22

Comparing macro economic indicators of Serbia with Austria

see http://www.tradingeconomics.com/serbia/indicators and http://www.tradingeconomics.com/austria/indicators

What could be the benefits of Serbia, how can Serbia recover?

Inflation rate in Serbia is at 2.1% and at 1.8% in Austria
Consumer price index (CPI) is at 180.2 in Serbia and at 110 in Austria (Serbia : Austria +63%)
If we compare consumer prices and inflation indicators to prime and key interest rates, then we might wonder:
On June 12th serbian central bank cuts its prime rates by (- 0.50) to very proud 8.50%.

Before we enjoy too fast over high interest rates in Serbia, we have at first take a look at the exchange rate of Euro to serbian Dinar:
http://www.finanzen.at/devisen/chart/euro-serbischer_dinar-kurs
Well the € climbed up from 114,5 one year ago to 115,5 (that's about +0.8% not much compared to prime rate difference). However, other things in that forex chart scare me a little bit.
Hätte jemand vor einem Jahr Geld auf ein Sparbuch in serbischen Dinar gelegt, dann hätte das 8,5% Guthabenzinsen und -0,8 Wechselkursverlust zum Euro gebracht.
A negative point for Serbia are not heavy but slight problems in the balance of payments, current account and trade balance.

The biggest advantage of Serbia are very appropriate business friendly taxes.
Social security contributions are almost as high as in Austria. (But don't forget, that Serbia still has to provide war disability pensions  for heavy wounded soldiers as part from social security.)