Login example in C#

Sample C# code for generating the encrypted login parameter auth. Also shows how
to create a REST call.

The public key data for NEXTAPI is embedded in the code.


using System;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace nExt_login
{
 class Program
 {
     static string BASE_URL = "https://api.test.nordnet.se/next";
     static string VERSION = "2";
     // The public key for NEXTAPI from the XML file
     static string PUBLIC_KEY =
       "<?xml version=\"1.0\"?>" +
       "<RSAParameters xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
       "<Exponent>AQAB</Exponent>" +
       "<Modulus>5td/64fAicX2r8sN6RP3mfHf2bcwvTzmHrLcjJbU85gLROL+IXclrjWsluqyt5xtc/TCwM" +
       "TfC/NcRVIAvfZdt+OPdDoO0rJYIY3hOGBwLQJeLRfruM8dhVD+/Kpu8yKzKOcRdne2hBb/mpkVtIl5av" +
       "JPFZ6AQbICpOC8kEfI1DHrfgT18fBswt85deILBTxVUIXsXdG1ljFAQ/lJd/62J74vayQJq6l2DT663Q" + 
       "B8nLEILUKEt/hQAJGU3VT4APSfT+5bkClfRb9+kNT7RXT/pNCctbBTKujr3tmkrdUZiQiJZdl/O7LhI9" +
       "9nCe6uyJ+la9jNPOuK5z6v72cXenmKZw==</Modulus>" +
       "</RSAParameters>";

     static void Main(string[] args)
     {
         Login(args[0], args[1], PUBLIC_KEY);

     }

     // Login to nExt with username, password and the public key as XML.
     private static void Login(string username, string password, string public_key)
     {
         RSACryptoServiceProvider RSA = 
            new System.Security.Cryptography.RSACryptoServiceProvider();

         // Deserialize the public key
         RSAParameters parameters = Deserialize<RSAParameters>(public_key);

         // Set the public key
         RSA.ImportParameters(parameters);

         // Create timestamp (Unix timestamp in milliseconds)
         string timestamp = 
            Math.Round((DateTime.UtcNow - 
         new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds).ToString();

         // Base64 encode each field and concatenate with ":" 
         string encoded = 
             Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username)) + ":" +
             Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(password)) + ":" +
             Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(timestamp));

         // Encrypt
         byte[] encrypted = RSA.Encrypt(System.Text.Encoding.UTF8.GetBytes(encoded), false);

         // Base 64 encode the blob.
         string blob = Convert.ToBase64String(encrypted);

         Dictionary<string, string> restParameters = new Dictionary<string, string>();
         restParameters["service"] = "NEXTAPI";
         restParameters["auth"] = blob;

         // Send request and write response
         System.Console.WriteLine(SendRequest("POST", "login", restParameters));
     }

     // Do a HTTP request with parameters
     private static string SendRequest(string method, string requestPath, Dictionary<string, string> parameters )
     {
         string retVal = "";
         try
         {
             // Should ONLY be used in test where the certificate is not real.
              ServicePointManager.ServerCertificateValidationCallback +=  
                   delegate(  
                       object sender,  
                       X509Certificate certificate,  
                       X509Chain chain,  
                       SslPolicyErrors sslPolicyErrors)  
                       {  
                        return true;  
                       }; 

             // Create the URL
             Uri address = new Uri(BASE_URL + "/" + VERSION + "/" + requestPath);

             // Create request
             HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

             request.Method = "POST";
             request.Accept = "application/json";
             request.ContentType = "application/x-www-form-urlencoded";

             if (parameters != null && (method == "POST" || method == "PUT" || method == "DELETE"))
             {
                 request.ContentType = "application/x-www-form-urlencoded";

                 byte[] byteData = UTF8Encoding.UTF8.GetBytes(CreateParameterList(parameters));

                 request.ContentLength = byteData.Length;

                 // Write data  
                 using (Stream postStream = request.GetRequestStream())
                 {
                     postStream.Write(byteData, 0, byteData.Length);
                 }
             }
             // Get response  
             using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
             {
                 // Get the response stream  
                 StreamReader reader = new StreamReader(response.GetResponseStream());

                 // Console application output  
                 retVal += reader.ReadToEnd();
             }
         }
         catch (System.Net.WebException e)
         {
             System.Console.WriteLine("REST call failed. Message: " + e.Message);
         }
         return retVal;
     }

     // Create a list of parameters
     private static string CreateParameterList(Dictionary<string, string> parameters)
     {
         // Create parameter list
         StringBuilder data = new StringBuilder();
         if (parameters != null)
         {
             foreach (KeyValuePair<string, string> parameter in parameters)
             {
                 data.Append(data.Length == 0 ? "" : "&");
                 data.Append(parameter.Key + "=" + 
         HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(parameter.Value)));
             }
         }
         return data.ToString(); ;
     }

     // Deserialize an object of type T from XML.
     private static T Deserialize<T>(string xml)
     {
         MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(xml));

         T reply = Activator.CreateInstance<T>();

         XmlSerializer serializer = new XmlSerializer(reply.GetType());

         reply = (T)serializer.Deserialize(ms);

         ms.Close();
         return reply;
     }
 }
}