mehmetserif
mehmetserif

Reputation: 1227

How can i create a checksum from a DataTable object?

I have a datatable with 45-50 columns and 45-50 rows and i want to create a checksum text or md5, sha1, i don't know which one is better. I'll create that text and search for it in database if there is one more of it. But the text length must be between 100-200 character, i don't know if i can do it. So what's your opinions about that and how can i do that?

Thanks.

Upvotes: 1

Views: 6978

Answers (4)

Gratzy
Gratzy

Reputation: 2898

If you're doing a hash on a dataRow within a datatable use drRow.GetHashCode().

Upvotes: 0

vc 74
vc 74

Reputation: 38179

The following should do:

// Serialize the table
var serializer = new DataContractSerializer(typeof(DataTable));
var memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, table);
byte[] serializedData = memoryStream.ToArray();

// Calculte the serialized data's hash value
var SHA = new SHA1CryptoServiceProvider();
byte[] hash = SHA.ComputeHash(serializedData);

// Convert the hash to a base 64 string
string hashAsText = Convert.ToBase64String(hash);

Note that we are serializing the whole table, not only its field values and that the table must have a name in order to allow serialization

Upvotes: 5

oursgris
oursgris

Reputation: 2882

first you should do a binary serialization of your dataset

http://www.eggheadcafe.com/community/aspnet/2/7700/serializedeserialize-a-datatable.aspx

for calculating sha1 :

/// <summary>
/// Calculates SHA1 hash
/// </summary>
/// <param name="text">input string</param>
/// <param name="enc">Character encoding</param>
/// <returns>SHA1 hash</returns>
public static string CalculateSHA1(string text, Encoding enc)
{
    byte[] buffer = enc.GetBytes(text);
    SHA1CryptoServiceProvider cryptoTransformSHA1 = 
    new SHA1CryptoServiceProvider();
    string hash = BitConverter.ToString(
        cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");

    return hash;
}

or md5 :

http://www.spiration.co.uk/post/1203/MD5%20in%20C%23%20-%20works%20like%20php%20md5%28%29%20example

Upvotes: 0

Kyle Rosendo
Kyle Rosendo

Reputation: 25287

Well algorithm wise, either MD5 or SHA1 (Newer) will work for a checksum.

Couple of things though:

  • Why does the text length need to be between 100-200 characters? It's still a hash, and portrays the same information no matter then length.
  • What are you looking to do?
  • What part do you require help with?

Upvotes: 2

Related Questions