MS SQL MD5Sum Support

30. January 2011 14:56

Adding an MD5SUM function to MS SQL.

 

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true, IsPrecise = false)]
    public static SqlString MD5Sum(SqlString S1)
    {
        MD5 md5 = System.Security.Cryptography.MD5.Create();
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(S1.Value);
        byte[] hash = md5.ComputeHash(inputBytes);

        // step 2, convert byte array to hex string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
            sb.Append(hash[i].ToString("X2"));

        return new SqlString(sb.ToString());
    }
}

 

You will also need to following SQL To install the function

 

CREATE Function MD5Sum(@S1 nvarchar(512))
	RETURNS nvarchar(64) AS EXTERNAL NAME SqlExtensions.UserDefinedFunctions.MD5Sum
GO

You should be able to call the function in normal sql code like SELECT dbo.MD5SUM('test value')

More about enabling .NET CLR In SQL Server

E-mail Kick it! DZone it! del.icio.us Permalink


Pingbacks and trackbacks (1)+

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading