C# programming

This part of druidsys.com is dedicated for C# programming.

Conversions

String to byte array and back

To convert a string to a byte array, you can use this method:

public static byte[] StringToByteArray(string s)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(s);
}

To convert it back to a string:

public static string ByteArrayToString(byte[] b)
{
System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
return encode.GetString(b);
}

Cryptography

Create a SHA-512 hash

For this function to work you need to add using System.Security.Cryptography; to your project.
You can easily change 512 to 1/256/384 to match the size you need. The method below return a 512 bit hash with the SHA algorithm.


public static string generateSHA512(byte[] data)
{
byte[] result;

SHA512 hash = new SHA512Managed();
result = hash.ComputeHash(data);

System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
return encode.GetString(result);
}