Symmetric Hashing With .NET Crypto Service Providers and COM Interop

I wrote the DotNetCryptoCOM (DNCC) library because I  wanted to be able to generate and reverse cypher text between .NET and COM applications using a single .dll.  It allows developers to drive the builtin .NET Cryptographic Service Providers with a simple API.  I’ve used this lib in VB, Managed C++, and of course C# applications.  Some of you may find it useful as well.
 
A few notes of interest:
 
1.  If you plan to use it from COM apps, you’ll need to do the following from a cmd shell:

(hint, use a Visual Studio Shell to have the path var in your env setup properly)

     copy DotNetCryptoCOM.dll  %windir%\system32

     cd %windir%\system32

     regasm %windir%\system32\DotNetCryptoCOM.dll /tlb:DotNetCryptoCOM.tlb

     gacutil /i DotNetCryptoCOM.dll

2.  If you plan to use it in Classic ASP apps, you’ll also need to remember to configure IIS to support ASP pages and from a cmd shell type:

     iisreset.

Now, I present a brief sample that shows how to use DNCC. 

First, I’ll encrypt some text in VBScript with it:

——————————————————————–

‘ Set raw text

Dim

strRawData

strRawData =

"super secret message"

‘ Set secret key

Dim strKey

strKey = "shhhh"  

‘ Set an instance of the CryptoProvider

Set dncc = CreateObject("DotNetCryptoCOM.CryptoClass")

‘ Encrypt the data with key

strEncryptedData = dncc.Encrypt(strRawData, strKey)

——————————————————————–

Now assume you’ve provided strEncryptedData to a C# .NET application.

——————————————————————–

string

secretKey = "shhhh";

DotNetCryptoCOM.

CryptoClass dncc = new DotNetCryptoCOM.CryptoClass();

string

 strRawData = dncc.Decrypt(strEncryptedData, secretKey);

——————————————————————–

Voila..  Secure trip between domains.  Note, the default Cryptographic Service Provider is DES.

If you’re interested in DNCC’s internal implementation, I’ll leave that to your curiosity and reflector

Its really pretty straight forward if you take a look inside…

I have provided the DNCC library for download here.

A more complete example of an ASP to ASP.NET shared authentication solution uses it here.

Happy hashing and best of luck..

A config-based approach to pluggable composition

I wanted to share this sample to demonstrate a simple way to implement a configuration based approach to switching out pluggable dependencies.  The example here uses reflection to dynamically load an assembly and then instantiate the targeted class contained therein.  The idea with this approach is that you may have different implementations of an interface contained in different assemblies.  Thus,  you’re able to simply target the different implementations of the interface by switching an app config key that specifies a different assembly name.  Note the following:

1.  The path variable is the fully qualfied assembly name.

2.  The className variable is path with the name of the class that implements an expected interface appended to it.  In this case, we expect the assembly to contain an implementation of IOrder.

From PetShop.NET 4.0 reference app source:

using System;

using System.Reflection;

using

System.Configuration;

namespace

PetShop.MessagingFactory

 {

         /// <summary>

        /// This class is implemented following the Abstract Factory pattern to create the Order

        /// Messaging implementation specified from the configuration file

        /// </summary>

        public sealed class QueueAccess

        {

             // Look up the Messaging implementation we should be using

             private static readonly string path = ConfigurationManager.AppSettings["OrderMessaging"];

             private QueueAccess() { }

             public static PetShop.IMessaging.IOrder CreateOrder() {

             string className = path + ".Order";

             return (PetShop.IMessaging.IOrder)Assembly.Load(path).CreateInstance(className);

          }

    }

}

Simple Random Password Generator

 
Simple C# function to generate random passwords:
 

Random randomizer = new Random();

public string CreateTemporaryPassword(int length)

{

    string letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    var chars = new char[length];

    for (int i = 0; i < length; i++)

        chars[i] = letters[randomizer.Next(0, letters.Length)];

    return new string(chars);

}

TSQL function to parse delimeted string and return a memory table containing the values

This script is useful when you need to generate a rowset from a delimeted string.  It allows the "WHERE IN" clause to be used against the values in the string, because they are converted into table rows.  This UDF is designed to be plugged into other queries where this need is present.  Here’s an example of how to use it:
 
Basic Usage:

select VALUE from PARSE_STRING(‘a,b,c,d,e’, ‘,’)

GO

Real World Usage:

select

* from customers where last_name in (select VALUE from PARSE_STRING(‘obama,biden,clinton,holder’, ‘,’))

GO

 
The Function:
 

SET

ANSI_NULLS ON

GO

SET

QUOTED_IDENTIFIER ON

GO

— =============================================

— Author: Joel Holder

— Description: parses a delimeted string and returns a table

— =============================================

 

/****** Object: UserDefinedFunction [dbo].[PARSE_STRING] ******/

IF

EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N‘[dbo].[PARSE_STRING]’) AND type in (N‘FN’, N‘IF’, N‘TF’, N‘FS’, N‘FT’))

    DROP

FUNCTION [dbo].[PARSE_STRING]

go

CREATE

FUNCTION PARSE_STRING  (@string nvarchar(max),  @delimeter char(1))

RETURNS

@result_table TABLE (POSITION int, VALUE nvarchar(max))

AS

BEGIN

— Fill the table variable with the rows for your result set

declare @pos int

declare @piece varchar(500)

declare @id int

set @id = 0

— Need to tack a delimiter onto the end of the input string if one doesn’t exist

    if right(rtrim(@string),1) <> @delimeter

    set @string = @string + @delimeter

    set @pos = patindex(‘%’ + @delimeter + ‘%’ , @string)

    while (@pos <> 0)

        begin

            set @id = @id + 1

            set @piece = left(@string, @pos 1)

            — You have a piece of data, so insert it, print it, do whatever you want to with it.

            insert into @result_table values (@id, @piece)

            set @string = stuff(@string, 1, @pos, )

            set @pos = patindex(‘%’ + @delimeter + ‘%’ , @string)

        end

 

return

END 

GO

AutoFocus the UserName field of an ASP.NET Login Control

Even if you’re not using a templated version of the Login Control, the builtin TextBox for username entry can be targeted like this:

protected void Page_Load(object sender, EventArgs e){

           SetFocus(Login1.FindControl("UserName"));

SetFocus is in the Page class.

Easy joy..