Skip to content

Instantly share code, notes, and snippets.

@Anime4000
Last active February 3, 2018 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Anime4000/c1a8800223cd924c0c66f7e3d28d76c7 to your computer and use it in GitHub Desktop.
Save Anime4000/c1a8800223cd924c0c66f7e3d28d76c7 to your computer and use it in GitHub Desktop.
Calculate Object into SHA256, use for blockchain database
using System.Text;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
class Compute
{
public static string BlockHash(object obj)
{
using (SHA256Managed sha256 = new SHA256Managed())
{
var hash = sha256.ComputeHash(ObjectByte(obj));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
private static byte[] ObjectByte(object obj)
{
var bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment