简体   繁体   中英

what's the proper way to encrypt login credentials in an http request?

If I need to make an HttpRequest to a site that requires login credentials, I can use code similar to the following, but as you can see the username and password are just base64 encoded, which means that if someone were to intercept the http request all they have to do is search for the value associated with the "Authorization" header and they have my login information.

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://...");

        request.Headers.Add("Authorization",
        string.Format("Basic {0}", Convert.ToBase64String(Encoding.Default.GetBytes(
        string.Format("{0}:{1}", username, password)))));

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream s = response.GetResponseStream())
            {
                using (StreamReader r = new StreamReader(s))
                {
                    DoSomething(r.ReadToEnd());
                }
            }
        }

Is the following code a better alternative or does it also make http requests with the "Basic " Authorization header?

        WebClient wc = new WebClient();
        wc.Credentials = new NetworkCredential(username, password);
        DoSomething(wc.DownloadString("https://..."));

If neither code results in http requests that "hide" the login credentials and if there is actually a way to "hide" them, what's the proper way to do it?

If you're making a webrequest to a server using HTTPS your entire message including headers are encrypted. So there is essentially no need for you to worry about encrypting your data. If you were to open Wireshark and try and sniff the packets, you'd see they are unreadable.

The .NET Framework will take care of the SSL encryption required under the hood based on the URL you're sending requests to.

More information can be found on MSDN: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

这两个都将使用HTTP基本访问身份验证,但是就像您正在使用HTTPS一样,您不必担心这一点,因为整个请求都会被加密。

I would recommend using WebClient not considering that it part of encryption i just think it a lot more cleaner approach and if you really care about login credentials you can use

SecureString testString = new SecureString(); 

http://blogs.msdn.com/b/fpintos/archive/2009/06/12/how-to-properly-convert-securestring-to-string.aspx

;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM