using System.Security.Cryptography; using System.Text; namespace ServiceShared.Crypto { public static class SHA512 { /// /// Encrypts a string value in SHA512 hash /// /// string value that should be encrypted in SHA512 hash /// Returns SHA512 hash public static string Encrypt(string value) { string result = null; try { byte[] bytes = Encoding.UTF8.GetBytes(value); using (System.Security.Cryptography.SHA512 hash = System.Security.Cryptography.SHA512.Create()) { byte[] hashedInputBytes = hash.ComputeHash(bytes); StringBuilder hashedInputStringBuilder = new StringBuilder(128); foreach (var b in hashedInputBytes) { hashedInputStringBuilder.Append(b.ToString("X2")); } result = hashedInputStringBuilder.ToString().ToLower(); } } catch { result = null; } return result; } /// /// Generates SHA512 HMAC Hash with key /// /// message that should be signed by sha512 hmac /// key that should be used for signing /// SHA512 HMAC public static string HMAC(string message, byte[] key) { string result = null; try { StringBuilder hash = new StringBuilder(); byte[] messageBytes = Encoding.UTF8.GetBytes(message); using (HMACSHA512 hmac = new HMACSHA512(key)) { byte[] hashValue = hmac.ComputeHash(messageBytes); foreach (var theByte in hashValue) { hash.Append(theByte.ToString("x2")); } } return hash.ToString(); } catch { result = null; } return result; } /// /// Validates HMAC with message and key /// /// HMAC from the partner /// message that should be signed by sha512 hmac /// key that should be used for signing /// returns true if success public static bool isValidAuthenticationCode(string hmac, string message, byte[] key) { return (hmac != null && HMAC(message, key) == hmac); } } }