public CryptographicScheme(int keySize) { RSA_Local = new RSACryptoServiceProvider(keySize); RSA_Foreign = new RSACryptoServiceProvider(keySize); HashMD5 = new MD5CryptoServiceProvider(); HashSHA = SHA256.Create(); }
public static byte[] SHA256(byte[] data) { using (System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create()) { return(ComputeHash(sha256, data)); } }
public static string GetSHA256(this Stream s) { using (System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create()) { return(Convert.ToHexString(sha256.ComputeHash(s)).ToLower()); } }
/// <summary> /// Hashes the specified value using utf8 encoding. /// </summary> /// <param name="alg">The SHA256 instance to use.</param> /// <param name="value">The string to hash.</param> /// <returns></returns> public static Sha256 HashData(this crypt.SHA256 alg, string value) { if (alg == null) { throw new ArgumentNullException(nameof(alg)); } if (value is null) { throw new ArgumentNullException(nameof(value)); } if (value.Length == 0) { return(s_empty256); } int maxLen = Encoding.UTF8.GetMaxByteCount(value.Length); // Utf8 is 1-4 bpc byte[] rented = ArrayPool <byte> .Shared.Rent(maxLen); try { int count = Encoding.UTF8.GetBytes(value, 0, value.Length, rented, 0); var span = new ReadOnlySpan <byte>(rented, 0, count); Sha256 sha = HashImpl(alg, span); return(sha); } finally { ArrayPool <byte> .Shared.Return(rented); } }
/// <summary> /// Open file and get it's SHA1 hash /// </summary> /// <param name="file_name">File name (full path)</param> /// <returns>String representation of the SHA1 hash</returns> public static string GetSHAHashFromFile(string file_name, SHAType shaType) { System.IO.FileStream file = new System.IO.FileStream(file_name, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] retVal = null; switch (shaType) { case SHAType.SHA1: System.Security.Cryptography.SHA1 sha1obj = new System.Security.Cryptography.SHA1CryptoServiceProvider(); retVal = sha1obj.ComputeHash(file); break; case SHAType.SHA256: System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create(); retVal = sha256.ComputeHash(file); break; case SHAType.SHA384: System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create(); retVal = sha384.ComputeHash(file); break; case SHAType.SHA512: System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create(); retVal = sha512.ComputeHash(file); break; } file.Close(); return(BitConverter.ToString(retVal).Replace("-", "").ToLower()); }
public SRP6a(string salt, string accountName = "", string passwordVerifier = "") { sha256 = new SHA256Managed(); I = sha256.ComputeHash(Encoding.UTF8.GetBytes(accountName)); N = new byte[] { 0xAB, 0x24, 0x43, 0x63, 0xA9, 0xC2, 0xA6, 0xC3, 0x3B, 0x37, 0xE4, 0x61, 0x84, 0x25, 0x9F, 0x8B, 0x3F, 0xCB, 0x8A, 0x85, 0x27, 0xFC, 0x3D, 0x87, 0xBE, 0xA0, 0x54, 0xD2, 0x38, 0x5D, 0x12, 0xB7, 0x61, 0x44, 0x2E, 0x83, 0xFA, 0xC2, 0x21, 0xD9, 0x10, 0x9F, 0xC1, 0x9F, 0xEA, 0x50, 0xE3, 0x09, 0xA6, 0xE5, 0x5E, 0x23, 0xA7, 0x77, 0xEB, 0x00, 0xC7, 0xBA, 0xBF, 0xF8, 0x55, 0x8A, 0x0E, 0x80, 0x2B, 0x14, 0x1A, 0xA2, 0xD4, 0x43, 0xA9, 0xD4, 0xAF, 0xAD, 0xB5, 0xE1, 0xF5, 0xAC, 0xA6, 0x13, 0x1C, 0x69, 0x78, 0x64, 0x0B, 0x7B, 0xAF, 0x9C, 0xC5, 0x50, 0x31, 0x8A, 0x23, 0x08, 0x01, 0xA1, 0xF5, 0xFE, 0x31, 0x32, 0x7F, 0xE2, 0x05, 0x82, 0xD6, 0x0B, 0xED, 0x4D, 0x55, 0x32, 0x41, 0x94, 0x29, 0x6F, 0x55, 0x7D, 0xE3, 0x0F, 0x77, 0x19, 0xE5, 0x6C, 0x30, 0xEB, 0xDE, 0xF6, 0xA7, 0x86 }; S = salt.ToByteArray(); g = new byte[] { 2 }; BN = N.ToBigInteger(); gBN = g.ToBigInteger(); k = sha256.ComputeHash(N.Combine(g)).ToBigInteger(); v = passwordVerifier.ToByteArray().ToBigInteger(); }
public SRP6a(string salt, string accountName = "", string passwordVerifier = "") { sha256 = new SHA256Managed(); I = sha256.ComputeHash(Encoding.UTF8.GetBytes(accountName)); N = new byte[] { 0xE3, 0x06, 0xEB, 0xC0, 0x2F, 0x1D, 0xC6, 0x9F, 0x5B, 0x43, 0x76, 0x83, 0xFE, 0x38, 0x51, 0xFD, 0x9A, 0xAA, 0x6E, 0x97, 0xF4, 0xCB, 0xD4, 0x2F, 0xC0, 0x6C, 0x72, 0x05, 0x3C, 0xBC, 0xED, 0x68, 0xEC, 0x57, 0x0E, 0x66, 0x66, 0xF5, 0x29, 0xC5, 0x85, 0x18, 0xCF, 0x7B, 0x29, 0x9B, 0x55, 0x82, 0x49, 0x5D, 0xB1, 0x69, 0xAD, 0xF4, 0x8E, 0xCE, 0xB6, 0xD6, 0x54, 0x61, 0xB4, 0xD7, 0xC7, 0x5D, 0xD1, 0xDA, 0x89, 0x60, 0x1D, 0x5C, 0x49, 0x8E, 0xE4, 0x8B, 0xB9, 0x50, 0xE2, 0xD8, 0xD5, 0xE0, 0xE0, 0xC6, 0x92, 0xD6, 0x13, 0x48, 0x3B, 0x38, 0xD3, 0x81, 0xEA, 0x96, 0x74, 0xDF, 0x74, 0xD6, 0x76, 0x65, 0x25, 0x9C, 0x4C, 0x31, 0xA2, 0x9E, 0x0B, 0x3C, 0xFF, 0x75, 0x87, 0x61, 0x72, 0x60, 0xE8, 0xC5, 0x8F, 0xFA, 0x0A, 0xF8, 0x33, 0x9C, 0xD6, 0x8D, 0xB3, 0xAD, 0xB9, 0x0A, 0xAF, 0xEE }; S = salt.ToByteArray(); g = new byte[] { 2 }; BN = N.ToBigInteger(); gBN = g.ToBigInteger(); k = sha256.ComputeHash(N.Combine(g.Fill32Bits())).ReverseUInt32().ToBigInteger(); v = passwordVerifier.ToByteArray().ToBigInteger(); }
//@Brief Comprueba el hash de un archivom con SHA256 //@Param[in] checksum Valor del hash a comparar //@Param[in] sFilePath Fichero a comprobar el hash //@Return Boolean True si la validación es correcta public static bool CheckFile_SHA256(string checksum, string sFilePath) { bool bOK = false; if (System.IO.File.Exists(sFilePath)) { try { System.Security.Cryptography.SHA256 mySHA256 = SHA256Managed.Create(); byte[] hashValue = null; FileInfo fInfo = new FileInfo(sFilePath); FileStream fileStream = fInfo.Open(FileMode.Open); fileStream.Position = 0; hashValue = mySHA256.ComputeHash(fileStream); fileStream.Close(); bOK = checksum == RoutinesLibrary.Data.DataType.StringUtils.ByteArrayToString(hashValue); } catch (Exception ex) { throw (new Exception(System.Reflection.MethodInfo.GetCurrentMethod().ToString() + " . Error: " + ex.Message)); } } return(bOK); }
public StateMachine() { secret = new byte[Parameters.secretLength]; Random rng = new Random(); rng.NextBytes(secret); hasher = new SHA256Managed(); }
public void FIPS186_b(string testName, SHA256 hash, byte[] input, byte[] result) { byte[] output = hash.ComputeHash (input, 0, input.Length); Assert.AreEqual (result, output, testName + ".b.1"); Assert.AreEqual (result, hash.Hash, testName + ".b.2"); // required or next operation will still return old hash hash.Initialize (); }
public static string EncryptPassword(string target) { System.Security.Cryptography.SHA256 hash = System.Security.Cryptography.SHA256.Create(); System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding(); byte[] combined = encoder.GetBytes("p" + target + "d"); hash.ComputeHash(combined); return(Convert.ToBase64String(hash.Hash)); }
static RuntimeTypeBuilder() { AssemblyName = new AssemblyName("__DynamicTypes__"); ModuleBuilder = AppDomain.CurrentDomain .DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess.Run) .DefineDynamicModule(AssemblyName.Name); HashAlgorithm = SHA256.Create(); }
public void FIPS186_c(string testName, SHA256 hash, byte[] input, byte[] result) { MemoryStream ms = new MemoryStream (input); byte[] output = hash.ComputeHash (ms); Assert.AreEqual (result, output, testName + ".c.1"); Assert.AreEqual (result, hash.Hash, testName + ".c.2"); // required or next operation will still return old hash hash.Initialize (); }
/// <summary> /// CheckSum256 method implementation /// </summary> public static byte[] CheckSum256(byte[] value) { byte[] hash = null; using (System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256Cng.Create()) { hash = sha256.ComputeHash(value); } return(hash); }
public static byte[] SHA256(byte[] input) { if (sha256 == null) { sha256 = System.Security.Cryptography.SHA256.Create(); } return(sha256.ComputeHash(input)); }
/// <summary> /// CheckSum256 method implementation /// </summary> public static byte[] CheckSum256(string value) { byte[] hash = null; using (System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create()) { hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(value)); } return(hash); }
public static string SHA256(string str) { using (var provider = SHA256provider.Create()) { byte[] data = provider.ComputeHash(Encoding.UTF8.GetBytes(str)); return(Hex.From(data)); } }
public void FIPS186_d(string testName, SHA256 hash, byte[] input, byte[] result) { byte[] output = hash.TransformFinalBlock (input, 0, input.Length); // LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue ! // AssertEquals( testName + ".d.1", result, output ); Assert.IsNotNull (output, testName + ".d.1"); Assert.AreEqual (result, hash.Hash, testName + ".d.2"); // required or next operation will still return old hash hash.Initialize (); }
public AES() { aes = new AesCryptoServiceProvider (); aes.BlockSize = 128; aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; hashmaker = new SHA256Managed(); }
public static string ConvertSHA256(string value) { System.Security.Cryptography.SHA256 sHA = System.Security.Cryptography.SHA256.Create(); byte[] array = sHA.ComputeHash(System.Text.Encoding.Default.GetBytes(value)); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("x2")); } return(stringBuilder.ToString()); }
public static byte[] DoubleSha256(byte[] text) { lock (sha256Lock) { if (sha256Alg == null) { sha256Alg = SHA256.Create(); } sha256Alg.Initialize(); return sha256Alg.ComputeHash(sha256Alg.ComputeHash(text)); } }
public override string StringHashAlgorithm(string value) { System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create(); byte[] bytes = sha256.ComputeHash(System.Text.ASCIIEncoding.UTF8.GetBytes(value)); StringBuilder sb = new StringBuilder(); foreach (var b in bytes) { sb.Append(b.ToString("x2")); } return(sb.ToString()); }
public static byte[] Hash(byte[] buffer) { if (Sha256 == null) { Sha256 = SHA256.Create(); } //using (SHA256 hash = SHA256.Create()) //{ return Sha256.ComputeHash(buffer); //} }
public void FIPS186_e(string testName, SHA256 hash, byte[] input, byte[] result) { byte[] copy = new byte [input.Length]; for (int i=0; i < input.Length - 1; i++) hash.TransformBlock (input, i, 1, copy, i); byte[] output = hash.TransformFinalBlock (input, input.Length - 1, 1); // LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue ! // AssertEquals (testName + ".e.1", result, output); Assert.IsNotNull (output, testName + ".e.1"); Assert.AreEqual (result, hash.Hash, testName + ".e.2"); // required or next operation will still return old hash hash.Initialize (); }
private static string HashCore(IByteConverter byteConverter, System.Security.Cryptography.SHA256 hasher, string value) { // setup encoding, hash, and read byte array var clearBytes = byteConverter.ConvertToBytes(value).EnsureArray(); // perform hashing operation var hashBytes = hasher.ComputeHash(clearBytes); // convert back to string var result = hashBytes.ToHex(); return(result); }
public static string Criptografador(string text) { byte[] bytes = Encoding.UTF8.GetBytes(text); System.Security.Cryptography.SHA256 MinhaHasher = System.Security.Cryptography.SHA256.Create(); byte[] hash = MinhaHasher.ComputeHash(bytes); string NomeHash = string.Empty; foreach (byte x in hash) { NomeHash += string.Format("{0:x2}", x); } return(NomeHash); }
private static Sha256 HashImpl(crypt.SHA256 alg, ReadOnlySpan <byte> span) { Debug.Assert(alg != null); // Do NOT short-circuit here; rely on call-sites to do so #if !NETSTANDARD2_0 Span <byte> hash = stackalloc byte[Sha256.ByteLength]; alg.TryComputeHash(span, hash, out _); #else var hash = alg.ComputeHash(span.ToArray()); #endif var sha = new Sha256(hash); return(sha); }
public string Encrypt(string password) { using (System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create()) { byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password)); StringBuilder builder = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { builder.Append(bytes[i].ToString("x2")); } return(builder.ToString()); } }
// sha256 below public static string GetSHA256Hash(string str) { System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create(); byte[] bytes = Encoding.Default.GetBytes(str); byte[] encoded = sha256.ComputeHash(bytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < encoded.Length; i++) { sb.Append(encoded[i].ToString("x2")); } return(sb.ToString()); }
private static readonly Sha256 s_empty256 = Sha256.Parse("E3B0C442-98FC1C14-9AFBF4C8-996FB924-27AE41E4-649B934C-A495991B-7852B855"); // Well-known /// <summary> /// Hashes the specified bytes. /// </summary> /// <param name="alg">The SHA256 instance to use.</param> /// <param name="span">The bytes to hash.</param> /// <returns></returns> public static Sha256 HashData(this crypt.SHA256 alg, ReadOnlySpan <byte> span) { if (alg == null) { throw new ArgumentNullException(nameof(alg)); } if (span.Length == 0) { return(s_empty256); } Sha256 sha = HashImpl(alg, span); return(sha); }
public static string GetSHA256Hash(string input) { System.Security.Cryptography.SHA256 sha256 = SHA256.Create(); byte[] inputBytes = Encoding.ASCII.GetBytes(input); byte[] hash = sha256.ComputeHash(inputBytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return(sb.ToString()); }
// SHA256 256bit 암호화 private string ComputeHash(string input) { System.Security.Cryptography.SHA256 algorithm = System.Security.Cryptography.SHA256Managed.Create(); Byte[] inputBytes = Encoding.UTF8.GetBytes(input); Byte[] hashedBytes = algorithm.ComputeHash(inputBytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashedBytes.Length; i++) { sb.Append(String.Format("{0:x2}", hashedBytes[i])); } return(sb.ToString()); }
public void FIPS186_Test1 (SHA256 hash) { string className = hash.ToString (); byte[] result = { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }; byte[] input = Encoding.Default.GetBytes (input1); string testName = className + " 1"; FIPS186_a (testName, hash, input, result); FIPS186_b (testName, hash, input, result); FIPS186_c (testName, hash, input, result); FIPS186_d (testName, hash, input, result); FIPS186_e (testName, hash, input, result); }
public void FIPS186_Test2 (SHA256 hash) { string className = hash.ToString (); byte[] result = { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }; byte[] input = Encoding.Default.GetBytes (input2); string testName = className + " 2"; FIPS186_a (testName, hash, input, result); FIPS186_b (testName, hash, input, result); FIPS186_c (testName, hash, input, result); FIPS186_d (testName, hash, input, result); FIPS186_e (testName, hash, input, result); }
private void CompareBlocks(ShaAlg Algorithm) { if (Algorithm == ShaAlg.SHA256) { byte[] buffer = new byte[639]; byte[] hash1 = new byte[32]; byte[] hash2 = new byte[32]; using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetBytes(buffer); // SHA256 // // test digest using (VTDev.Projects.CEX.Crypto.Digests.SHA256Digest sha1 = new VTDev.Projects.CEX.Crypto.Digests.SHA256Digest()) hash1 = sha1.ComputeHash(buffer); using (System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256Managed.Create()) hash2 = sha.ComputeHash(buffer); if (!Compare.AreEqual(hash1, hash2)) { throw new Exception("SHA512 hash is not equal!"); } } else { // SHA512 // byte[] hash1 = new byte[64]; byte[] hash2 = new byte[64]; byte[] buffer = new byte[377]; using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider()) rng.GetBytes(buffer); // test digest using (VTDev.Projects.CEX.Crypto.Digests.SHA512Digest sha2 = new VTDev.Projects.CEX.Crypto.Digests.SHA512Digest()) hash1 = sha2.ComputeHash(buffer); using (System.Security.Cryptography.SHA512 sha = System.Security.Cryptography.SHA512Managed.Create()) hash2 = sha.ComputeHash(buffer); if (!Compare.AreEqual(hash1, hash2)) { throw new Exception("SHA256 hash is not equal!"); } } }
public static string GetSha256(string value) { if (value == null) { return(string.Empty); } value = value.Trim(); if (value == string.Empty) { return(string.Empty); } try { System.Security.Cryptography.SHA256 oHash = System.Security.Cryptography.SHA256.Create(); byte[] bytInputs = System.Text.Encoding.ASCII.GetBytes(value); byte[] bytHashes = oHash.ComputeHash(bytInputs); // Convert the byte array to hexadecimal string System.Text.StringBuilder oStringBuilder = new System.Text.StringBuilder(); for (int intIndex = 0; intIndex < bytHashes.Length; intIndex++) { oStringBuilder.Append(bytHashes[intIndex].ToString("X2")); // To force the hex string to lower-case letters instead of // upper-case, use he following line instead: // sb.Append(hashBytes[i].ToString("x2")); } return(oStringBuilder.ToString()); //return (System.Web.Security.FormsAuthentication // .HashPasswordForStoringInConfigFile(value, "SHA1")); } catch { return(string.Empty); } }
public static String sha256_hash(String value) { StringBuilder Sb = new StringBuilder(); using (System.Security.Cryptography.SHA256 hash = System.Security.Cryptography.SHA256.Create()) { Encoding enc = Encoding.UTF8; Byte[] result = hash.ComputeHash(enc.GetBytes(value)); foreach (Byte b in result) { Sb.Append(b.ToString("x2")); } } return(Sb.ToString()); }
/// <summary> /// Return SHA-256 (SHA-2) for a string. /// </summary> /// <param name="text">Source text to calculate hash from</param> /// <param name="encoding">Text encoding</param> /// <returns>SHA1 hash in hex format</returns> public static string SHA256(string text, Encoding encoding) { if (text == null) { return(null); } #if !NETCF using (System.Security.Cryptography.SHA256 cipher = System.Security.Cryptography.SHA256.Create()) { byte[] array = cipher.ComputeHash(encoding.GetBytes(text)); return(Energy.Base.Hex.ArrayToHex(array).ToLower()); } #endif #if NETCF return(null); #endif }
private string GetSha256HashString(string prefix, string data, string sufix) { using (SSC.SHA256 sha256Hash = SSC.SHA256.Create()) { StringBuilder hs = new StringBuilder(prefix).Append(data).Append(sufix); byte[] bytes = sha256Hash.ComputeHash( Encoding.UTF8.GetBytes(hs.ToString())); hs = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { hs.Append(bytes[i].ToString("x2")); } return(hs.ToString()); } }
private static string CreateMD5(string input) { // Use input string to calculate MD5 hash using (System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create()) { byte[] inputBytes = Encoding.ASCII.GetBytes(input); byte[] hashBytes = sha256.ComputeHash(inputBytes); // Convert the byte array to hexadecimal string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashBytes.Length; i++) { sb.Append(hashBytes[i].ToString("X2")); } return(sb.ToString().ToLower()); } }
/// <summary> /// 验证面md5值是否先等 /// </summary> /// <param name="md5Hash"></param> /// <param name="input"></param> /// <param name="hash"></param> /// <returns></returns> private static bool VerifySHA256Hash(SHA256 SHA1Hash, string input, string hash) { // Hash the input. string hashOfInput = GetSHA256Hash(SHA1Hash, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, hash)) { return true; } else { return false; } }
public static string CalculateSHA256Hash(string input) { // step 1, calculate MD5 hash from input System.Security.Cryptography.SHA256 sh2 = System.Security.Cryptography.SHA256.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = sh2.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return(sb.ToString().ToUpper().Trim()); }
static void ComputeAndCompare(byte[] original, SHA256 sha265, UnicodeEncoding byteConverter, string data, bool crashIfEqual = false) { byte[] hashed = sha265.ComputeHash(byteConverter.GetBytes(data)); if(original.SequenceEqual(hashed) || !crashIfEqual) { if (crashIfEqual) { throw new InvalidOperationException("YOU SHOULD PLAY ON THE LOTTERY!"); } else { Console.WriteLine("------------"); Console.WriteLine($"Encrypted: {hashed.ToSentence()}"); Console.WriteLine($"'{data}' has same hash?: {original.SequenceEqual(hashed)}"); } } }
public void FIPS186_Test3 (SHA256 hash) { string className = hash.ToString (); byte[] result = { 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7, 0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97, 0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0 }; byte[] input = new byte [1000000]; for (int i = 0; i < 1000000; i++) input[i] = 0x61; // a string testName = className + " 3"; FIPS186_a (testName, hash, input, result); FIPS186_b (testName, hash, input, result); FIPS186_c (testName, hash, input, result); FIPS186_d (testName, hash, input, result); FIPS186_e (testName, hash, input, result); }
/// <summary> /// Hashes the specified stream. /// </summary> /// <param name="alg">The SHA256 instance to use.</param> /// <param name="stream">The stream to hash.</param> /// <returns></returns> public static Sha256 HashData(this crypt.SHA256 alg, Stream stream) { if (alg == null) { throw new ArgumentNullException(nameof(alg)); } if (stream is null) { throw new ArgumentNullException(nameof(stream)); } // Note that length==0 should NOT short-circuit byte[] hash = alg.ComputeHash(stream); var sha = new Sha256(hash); return(sha); }
/// <summary> /// 获取md5值 /// </summary> /// <param name="md5Hash"></param> /// <param name="input"></param> /// <returns></returns> private static string GetSHA256Hash(SHA256 hash, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); }
private static string GetHash(SHA256 shaHash, string input) { // Convert the input string to a byte array and compute the hash. byte[] data = shaHash.ComputeHash(Encoding.Unicode.GetBytes(input)); Debug.WriteLine(string.Format("Key Size before hash: {0} bytes", Encoding.Unicode.GetBytes(input).Length)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(32); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("X2")); } // Return the hexadecimal string. return sBuilder.ToString(); }
//Realize that this is probbly overkill since there is a SHA256 class in crypto already, //Just wanted to help align the Java project and this project so that concepts did not get //Muted and take a backseat to the implementation. //Please remember this is contrived example code to help explain concepts in the whitepaper. public static string generateHash(string value) { string hash = null; try { System.Security.Cryptography.SHA256 md = System.Security.Cryptography.SHA256.Create(); byte[] bytes = md.ComputeHash(Encoding.UTF8.GetBytes(value)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { sb.Append(bytes[i].ToString("x2")); } hash = sb.ToString(); } catch (CryptographicException e) { Console.Write(e.StackTrace); } return(hash); }
/// <summary> /// Hashes the specified bytes. /// </summary> /// <param name="alg">The SHA256 instance to use.</param> /// <param name="bytes">The bytes to hash.</param> /// <returns></returns> public static Sha256 HashData(this crypt.SHA256 alg, byte[] bytes) { if (alg == null) { throw new ArgumentNullException(nameof(alg)); } if (bytes is null) { throw new ArgumentNullException(nameof(bytes)); } if (bytes.Length == 0) { return(s_empty256); } var span = new ReadOnlySpan <byte>(bytes); Sha256 sha = HashImpl(alg, span); return(sha); }
public HandshakeLayer(SecureChannel secureChannel, ConnectionEnd connectionEnd) { m_localHash = SHA256.Create(); m_remoteHash = SHA256.Create(); m_secureChannel = secureChannel; SecurityParameters = new SecurityParameters(); SecurityParameters.Entity = connectionEnd; SecurityParameters.CompressionAlgorithm = CompressionMethod.Null; SecurityParameters.PRFAlgorithm = PRFAlgorithm.SHA256; SecurityParameters.CipherType = CipherType.Block; AllowedCipherSuites = new CipherSuite[] { CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256, CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA, }; VerifyCertificate = c => c.Verify(); }
/// <summary> /// Create a new HandshakeLayer object given a SecureChannel and which end of the connection it is to be. /// </summary> /// <param name="secureChannel">the SecureChannel that comprises the secure functionality of this layer</param> /// <param name="connectionEnd">this specifies which end of the connection - Server or Client</param> public HandshakeLayer(SecureChannel secureChannel, ConnectionEnd connectionEnd) { // SHA256 is a class that computes the SHA-256 (SHA stands for Standard Hashing Algorithm) of it's input. m_localHash = SHA256.Create(); m_remoteHash = SHA256.Create(); m_secureChannel = secureChannel; SecurityParameters = new SecurityParameters(); SecurityParameters.Entity = connectionEnd; SecurityParameters.CompressionAlgorithm = CompressionMethod.Null; SecurityParameters.PRFAlgorithm = PRFAlgorithm.SHA256; SecurityParameters.CipherType = CipherType.Block; AllowedCipherSuites = new[] { CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256, CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256, CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA }; VerifyCertificate = c => c.Verify(); }
public static byte[] Sha256(params byte[][] sources) { if (sources == null) { throw new ArgumentNullException(nameof(sources), "The sources array is null."); } foreach (byte[] source in sources) { if (source == null) { throw new ArgumentNullException(nameof(sources), "The sources array contains null element."); } } lock (sha256Lock) { if (sha256Alg == null) { sha256Alg = SHA256.Create(); } sha256Alg.Initialize(); foreach (byte[] source in sources) { int offset = 0; while (offset < source.Length) { offset += sha256Alg.TransformBlock(source, offset, source.Length - offset, source, offset); } } sha256Alg.TransformFinalBlock(new byte[0], 0, 0); return sha256Alg.Hash; } }
public void Dispose() { if (m_rng != null) { m_rng.Dispose(); m_rng = null; } if (m_remoteHash != null) { m_remoteHash.Dispose(); m_remoteHash = null; } if (m_localHash != null) { m_localHash.Dispose(); m_localHash = null; } if(m_prf != null) { m_prf.Dispose(); m_prf = null; } }
public void FIPS186_a (string testName, SHA256 hash, byte[] input, byte[] result) { byte[] output = hash.ComputeHash (input); AssertEquals (testName + ".a.1", result, output); AssertEquals (testName + ".a.2", result, hash.Hash); // required or next operation will still return old hash hash.Initialize (); }
private void OnFinished(NetMQMessage incomingMessage, OutgoingMessageBag outgoingMessages) { if ( (SecurityParameters.Entity == ConnectionEnd.Client && (!m_secureChannel.ChangeSuiteChangeArrived || m_lastReceivedMessage != HandshakeType.ServerHelloDone || m_lastSentMessage != HandshakeType.Finished)) || (SecurityParameters.Entity == ConnectionEnd.Server && (!m_secureChannel.ChangeSuiteChangeArrived || m_lastReceivedMessage != HandshakeType.ClientKeyExchange || m_lastSentMessage != HandshakeType.ServerHelloDone))) { throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeUnexpectedMessage, "Finished received when expecting another message"); } if (SecurityParameters.Entity == ConnectionEnd.Server) { HashLocal(incomingMessage); } FinishedMessage finishedMessage = new FinishedMessage(); finishedMessage.SetFromNetMQMessage(incomingMessage); m_remoteHash.TransformFinalBlock(new byte[0], 0, 0); byte[] seed = m_remoteHash.Hash; m_remoteHash.Dispose(); m_remoteHash = null; string label; if (SecurityParameters.Entity == ConnectionEnd.Client) { label = ServerFinishedLabel; } else { label = ClientFinshedLabel; } byte[] verifyData = PRF.Get(SecurityParameters.MasterSecret, label, seed, FinishedMessage.VerifyDataLength); if (!verifyData.SequenceEqual(finishedMessage.VerifyData)) { throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeVerifyData, "peer verify data wrong"); } if (SecurityParameters.Entity == ConnectionEnd.Server) { AddFinished(outgoingMessages); } m_done = true; }
private static SHA256 GetHasher() { if (_hasher256 == null) { _hasher256 = new SHA256Managed(); } return _hasher256; }
public SHA256Hasher() { this.sha = SHA256.Create(); }
public UserRepository(HeroesContext context) { _context = context; _sha256 = SHA256Managed.Create(); }
private void AddFinished(OutgoingMessageBag outgoingMessages) { m_localHash.TransformFinalBlock(new byte[0], 0, 0); byte[] seed = m_localHash.Hash; m_localHash.Dispose(); m_localHash = null; string label; if (SecurityParameters.Entity == ConnectionEnd.Server) { label = ServerFinishedLabel; } else { label = ClientFinshedLabel; } FinishedMessage finishedMessage = new FinishedMessage(); finishedMessage.VerifyData = PRF.Get(SecurityParameters.MasterSecret, label, seed, FinishedMessage.VerifyDataLength); NetMQMessage outgoingMessage = finishedMessage.ToNetMQMessage(); outgoingMessages.AddHandshakeMessage(outgoingMessage); m_lastSentMessage = HandshakeType.Finished; if (SecurityParameters.Entity == ConnectionEnd.Client) { HashRemote(outgoingMessage); } }
private string ComputeMangledStringLiteralName(string literal) { string mangledName = SanitizeName(literal); if (mangledName.Length > 30) mangledName = mangledName.Substring(0, 30); if (mangledName != literal) { if (_sha256 == null) _sha256 = SHA256.Create(); var hash = _sha256.ComputeHash(Encoding.UTF8.GetBytes(literal)); mangledName += "_" + BitConverter.ToString(hash).Replace("-", ""); } lock (this) { _mangledStringLiterals = _mangledStringLiterals.Add(literal, mangledName); } return mangledName; }