|
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace GSS.Web.Security
{
static class Utils
{
/// <summary>
/// Generates a random bytes using RNGCryptoServiceProvider
/// </summary>
/// <param name="count">Number of bytes to return</param>
/// <returns>A randomly generated bytes array of the specified length</returns>
public static byte[] GetRandomBytes(int count)
{
byte[] randomBytes = new byte[count];
RNGCryptoServiceProvider gen = new RNGCryptoServiceProvider();
gen.GetBytes(randomBytes);
return randomBytes;
}
/// <summary>
/// Converts a byte array to a hex string
/// </summary>
/// <param name="bytes">Bytes to convert</param>
/// <returns>Formatted hex string</returns>
public static string ByteArrayToHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("X2"));
}
return sb.ToString();
}
/// <summary>
/// Converts a hex string to a byte array
/// </summary>
/// <param name="hexString">The hex string to convert</param>
/// <returns>A byte array representing the hex string</returns>
public static byte[] HexStringToByteArray(string hexString)
{
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/// <summary>
/// Convert a DateTime to the equivalent long (Win32 FileTime) byte array
/// </summary>
/// <param name="date">DateTime to convert</param>
/// <returns>"long" byte array representing the DateTime</returns>
public static byte[] DateToByteArray(DateTime date)
{
long longDate = date.ToFileTime();
return BitConverter.GetBytes(longDate);
}
/// <summary>
/// Coverts a long (aka Win32 FileTime) byte array to a DateTime
/// </summary>
/// <param name="bytes">Bytes to convert</param>
/// <returns>DateTime representation of the "long" bytes</returns>
public static DateTime ByteArrayToDate(byte[] bytes)
{
if (bytes.Length != 8)
throw new ArgumentException("bytes");
long longDate = BitConverter.ToInt64(bytes, 0);
return DateTime.FromFileTime(longDate);
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.