Friday, 31 May 2013

AesManaged

class Program
    {
        static Encoding encoder = UTF8Encoding.UTF8;
        static string data = "i am fine here";
        static byte[] bytes = encoder.GetBytes(data);
 
        static void SimpleImplementation(byte[] Key, byte[] IV)
        {
            using (AesManaged aes = new AesManaged())
            {
                aes.Key = Key; aes.IV = IV;
 
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
 
                byte[] cipherValue = encryptor.TransformFinalBlock(bytes, 0, bytes.Length);
                byte[] plainValue = decryptor.TransformFinalBlock(cipherValue, 0, 
                             cipherValue.Length);
 
                Console.WriteLine("Assert the bytes = " + plainValue.SequenceEqual(bytes));
                Console.WriteLine("Assert the string = " + 
                             encoder.GetString(plainValue).Equals(data));
            }
        }
 
        static void StreamOrientedImplementation(byte[] Key, byte[] IV)
        {
            byte[] cipherValue = null;
            byte[] plainValue = null;
 
            using (AesManaged aes = new AesManaged())
            {
                aes.Key = Key;
                aes.IV = IV;
 
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
 
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream secureStream = new CryptoStream(memoryStream, 
                            encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(secureStream))
                        {
                            writer.Write(data);
                        }
 
                        cipherValue = memoryStream.ToArray();
                    }
                }
 
                using (MemoryStream memoryStream = new MemoryStream(cipherValue))
                {
                    using (CryptoStream secureStream = new CryptoStream(memoryStream, 
                              decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader reader = new StreamReader(secureStream))
                        {
                            plainValue = encoder.GetBytes(reader.ReadToEnd());
                        }
                    }
                }
 
                Console.WriteLine("Assert the bytes = " + plainValue.SequenceEqual(bytes));
                Console.WriteLine("Assert the string = " + 
                             encoder.GetString(plainValue).Equals(data));
            }
        }
 
        static void Main(string[] args)
        {
            AesManaged aes = new AesManaged();
 
            Console.WriteLine("AES Default - IV = {0}, KeySize = {1}, BlockSize = {2}, 
                  Mode = {3}", aes.IV.Length, aes.KeySize, aes.BlockSize, aes.Mode);
 
            SimpleImplementation(aes.Key, aes.IV);
            StreamOrientedImplementation(aes.Key, aes.IV);
 
            aes.Dispose();
        }
    }

Thursday, 30 May 2013

WCF Security

few reads for my reference

Securing services
Authentication, Authorization, and Identities in WCF
Federated Security

Message Security with Certificates for Client/Server validation

few reads

http://msdn.microsoft.com/en-us/library/ms733098.aspx
http://msdn.microsoft.com/en-us/library/ms751516.aspx
http://stackoverflow.com/questions/1570939/wcf-message-security-without-certificate-and-windows-auth

and create two certificates - for client/server.

Server

ICalculator.cs
using System.ServiceModel;
 
namespace MySimpleCalculator
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        int Add(int num1, int num2);
 
        [OperationContract]
        string GetCallerIdentity();
    }
}

Calculator.svc
<%@ ServiceHost Language="C#" Debug="true" Service="MySimpleCalculator.Calculator" CodeBehind="Calculator.svc.cs" %>
Calculator.svc.cs

using System.ServiceModel;
namespace MySimpleCalculator
{
    public class Calculator : ICalculator
    {
        public int Add(int num1, int num2)
        {
            return num1 + num2;
        }
 
        public string GetCallerIdentity()
        {
            // The client certificate is not mapped to a Windows identity by default.
            // ServiceSecurityContext.PrimaryIdentity is populated based on the information
            // in the certificate that the client used to authenticate itself to the service.
            return ServiceSecurityContext.Current.PrimaryIdentity.Name;
        }
    }
}
 
web.config 

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceCredentialsBehavior">
          <serviceCredentials>
            <serviceCertificate findValue="CN=Server" 
                 x509FindType="FindBySubjectDistinguishedName"/>
            <clientCertificate>
              <authentication certificateValidationMode="PeerOrChainTrust" 
                    revocationMode="NoCheck" />
            </clientCertificate>
          </serviceCredentials>
          <!-- To avoid disclosing metadata information, set the value below to false 
                and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the 
                value below to true.  Set to false before deployment to avoid disclosing 
                exception information -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="MySimpleCalculator.Calculator" behaviorConfiguration="ServiceCredentialsBehavior">
        <endpoint contract="MySimpleCalculator.ICalculator" address="/SimpleCalculator" 
                  binding="wsHttpBinding"
                  bindingConfiguration="MessageUsingCertificate" />
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="MessageUsingCertificate">
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  
</configuration>
------------------------------------------------------------------------

client

class Program
{
   static void Main(string[] args)
   {
      ServiceReference1.CalculatorClient client = new ServiceReference1.CalculatorClient();
 
      Console.WriteLine(client.Add(1, 2));
      Console.WriteLine(client.GetCallerIdentity());
 
      Console.ReadLine();
    }
}
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <wsHttpBinding>
                <binding name="WSHttpBinding_ICalculator">
                    <security>
                        <message clientCredentialType="Certificate" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
      <behaviors>
        <endpointBehaviors>
          <behavior name="endpointCredentialsBehavior">
            <clientCredentials>
              <clientCertificate findValue="CN=client"
                 storeLocation="LocalMachine"
                x509FindType="FindBySubjectDistinguishedName" />
              <serviceCertificate>
                <authentication revocationMode="NoCheck"/>
              </serviceCertificate>
            </clientCredentials>
          </behavior>
        </endpointBehaviors>
      </behaviors>
        <client>
            <endpoint address="http://localhost:18499/Calculator.svc/SimpleCalculator"
                binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator"
                contract="ServiceReference1.ICalculator" name="WSHttpBinding_ICalculator"
                behaviorConfiguration="endpointCredentialsBehavior">
                <identity>
                    <certificate encodedValue="server certificate value" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration> 


Issues

1. {"The request for security token could not be satisfied because authentication failed."} - It means
   Server tries to authenticate Client certificate and its revocation status. So add 'No Revocation'
   @ server side for client certificate.
 
2. SOAP security negotiation with "uri" fails.

   The X.509 certificate CN=subject chain building failed. The certificate that was used has 
   a trust chain that cannot be verified. Replace the certificate or change the 
   certificateValidationMode. The revocation function was unable to check revocation for 
   the certificate. - This happens if server certificate is not trusted by client, add no revocation.
 
     

Wednesday, 29 May 2013

Certificate may not have a private key that is capable of key exchange or the process may not have access rights for the private key

When we add certificate into IIS\Server Certificates, please make sure you have given 'Read' permission for the users that's hosting your web service/site.

Start MMC and add the Certificate Snap-in, selecting the right container owner for your SSL certificate. Find the certificate (it's probably in the personal store), right click on it and choose All Tasks > Manage Private key. Grant read access to the private key to the user hosting your service.

Wednesday, 15 May 2013

VS 2010 Solution by default opens with VS2008

This problem happens sometimes when you download/copy a Visual Studio 2010 solution before installing Visual Studio itself. To solve this, go to Tools > Option > Environment > General > Restore File Associations

Tuesday, 14 May 2013

Combinations and Permutations

A Permutation is an ordered Combination

What's the Difference?

In English we use the word "combination" loosely, without thinking if the order of things is important. In other words:

    "My fruit salad is a combination of apples, grapes and bananas" We don't care what order the fruits are in, they could also be "bananas, grapes and apples" or "grapes, apples and bananas", its the same fruit salad.
     
    "The combination to the safe was 472". Now we do care about the order. "724" would not work, nor would "247". It has to be exactly 4-7-2.

So, in Mathematics we use more precise language:
    If the order doesn't matter, it is a Combination.
    If the order does matter it is a Permutation.
   
Permutations

There are basically two types of permutation:

    'n' is number of items to choose from, 'r' is the sample size(number of items to choose from 'n')
    Repetition is Allowed: n ^ r
    No Repetition: n!/(n - r)!

Combinations

    Repetition : (n+r-1)!/r!(n-1)!
    No Repetition : n!/r!(n-r)!

from this
Excellent use case for Combinations is birthday problem, to figure out matching birthday's from list of people. In this case of 23 people, we could use Combinations without repetitions \textstyle {23 \choose 2} = \frac{23 \cdot 22}{2} = 253.