/// <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 static string GetSHA512(this Stream s) { using (System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create()) { return(Convert.ToHexString(sha512.ComputeHash(s)).ToLower()); } }
public string HashFile(string path) { sha512 = new SHA512Managed(); calculatedHash = null; hashString = null; FileInfo fi = new FileInfo(path); try { FileStream fs = System.IO.File.OpenRead(path); fs.Position = 0; calculatedHash = sha512.ComputeHash(fs); fs.Close(); hashString = ByteToString(calculatedHash); return hashString; } catch (FileNotFoundException) { // file not found Logger.Write("Error, file not found"); } catch (IOException) { // file could not be accessed // warn user and try again on OK Logger.Write("Error, file not accessible " + fi.Name); } catch (UnauthorizedAccessException) { // no access permission } return null; }
internal static async Task InstallFromStream(Stream stream, Library library, string packagesDirectory, SHA512 sha512) { var packagePathResolver = new DefaultPackagePathResolver(packagesDirectory); var targetPath = packagePathResolver.GetInstallPath(library.Name, library.Version); var targetNuspec = packagePathResolver.GetManifestFilePath(library.Name, library.Version); var targetNupkg = packagePathResolver.GetPackageFilePath(library.Name, library.Version); var hashPath = packagePathResolver.GetHashPath(library.Name, library.Version); // Acquire the lock on a nukpg before we extract it to prevent the race condition when multiple // processes are extracting to the same destination simultaneously await ConcurrencyUtilities.ExecuteWithFileLocked(targetNupkg, async createdNewLock => { // If this is the first process trying to install the target nupkg, go ahead // After this process successfully installs the package, all other processes // waiting on this lock don't need to install it again if (createdNewLock) { Directory.CreateDirectory(targetPath); using (var nupkgStream = new FileStream(targetNupkg, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)) { await stream.CopyToAsync(nupkgStream); nupkgStream.Seek(0, SeekOrigin.Begin); ExtractPackage(targetPath, nupkgStream); } // Fixup the casing of the nuspec on disk to match what we expect var nuspecFile = Directory.EnumerateFiles(targetPath, "*" + NuGet.Constants.ManifestExtension).Single(); if (!string.Equals(nuspecFile, targetNuspec, StringComparison.Ordinal)) { Manifest manifest = null; using (var nuspecStream = File.OpenRead(nuspecFile)) { manifest = Manifest.ReadFrom(nuspecStream, validateSchema: false); manifest.Metadata.Id = library.Name; } // Delete the previous nuspec file File.Delete(nuspecFile); // Write the new manifest using (var targetNuspecStream = File.OpenWrite(targetNuspec)) { manifest.Save(targetNuspecStream); } } stream.Seek(0, SeekOrigin.Begin); var nupkgSHA = Convert.ToBase64String(sha512.ComputeHash(stream)); File.WriteAllText(hashPath, nupkgSHA); } return 0; }); }
/// <summary> /// CheckSum512 method implementation /// </summary> public static byte[] CheckSum512(byte[] value) { byte[] hash = null; using (System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512Cng.Create()) { hash = sha512.ComputeHash(value); } return(hash); }
/// <summary> /// CheckSum512 method implementation /// </summary> public static byte[] CheckSum512(string value) { byte[] hash = null; using (System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512Managed.Create()) { hash = sha512.ComputeHash(Encoding.UTF8.GetBytes(value)); } return(hash); }
public static byte[] SHA512(byte[] input) { if (sha512 == null) { sha512 = System.Security.Cryptography.SHA512.Create(); } return(sha512.ComputeHash(input)); }
// Encrypt a password using SHA512 public static byte[] EncryptPassword(string password) { // Make precalculated, generic rainbow tables ineffective by using a salt password = StaticSaltPassword(password); // Encrypt the password System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create(); return(sha512.ComputeHash(System.Text.Encoding.Unicode.GetBytes(password))); }
public override string StringHashAlgorithm(string value) { System.Security.Cryptography.SHA512 sha = System.Security.Cryptography.SHA512.Create(); byte[] bytes = sha.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 string GetSHA512Hashed(string input) { System.Security.Cryptography.SHA512 sha1 = System.Security.Cryptography.SHA512.Create(); byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input.ToString())); StringBuilder output = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { output.Append(hash[i].ToString("X2")); } return(output.ToString()); }
// sha512 below public static string GetSHA512Hash(string str) { System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create(); byte[] bytes = Encoding.Default.GetBytes(str); byte[] encoded = sha512.ComputeHash(bytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < encoded.Length; i++) { sb.Append(encoded[i].ToString("x2")); } return(sb.ToString()); }
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!"); } } }
/// <summary> /// Return SHA-512 (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 SHA512(string text, Encoding encoding) { if (text == null) { return(null); } #if !NETCF using (System.Security.Cryptography.SHA512 cipher = System.Security.Cryptography.SHA512.Create()) { byte[] array = cipher.ComputeHash(encoding.GetBytes(text)); return(Energy.Base.Hex.ArrayToHex(array).ToLower()); } #endif #if NETCF return(null); #endif }
/// <summary> /// 验证面md5值是否先等 /// </summary> /// <param name="md5Hash"></param> /// <param name="input"></param> /// <param name="hash"></param> /// <returns></returns> private static bool VerifySHA512Hash(SHA512 SHA1Hash, string input, string hash) { // Hash the input. string hashOfInput = GetSHA512Hash(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 GetSha512(string value) { if (value == null) { return(string.Empty); } value = value.Trim(); if (value == string.Empty) { return(string.Empty); } try { System.Security.Cryptography.SHA512 oHash = System.Security.Cryptography.SHA512.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); } }
/// <summary> /// 获取md5值 /// </summary> /// <param name="md5Hash"></param> /// <param name="input"></param> /// <returns></returns> private static string GetSHA512Hash(SHA512 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(); }
public void FIPS186_Test1 (SHA512 hash) { string className = hash.ToString (); byte[] result = { 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }; 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 (SHA512 hash) { string className = hash.ToString (); byte[] result = { 0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda, 0x8c, 0xf4, 0xf7, 0x28, 0x14, 0xfc, 0x14, 0x3f, 0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f, 0x7f, 0xa1, 0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18, 0x50, 0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4, 0x33, 0x1b, 0x99, 0xde, 0xc4, 0xb5, 0x43, 0x3a, 0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26, 0x54, 0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09 }; 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); }
/// <summary> /// Get SHA1 hash from buffer of bytes /// </summary> /// <param name="input_buffer">Input buffer</param> /// <returns>16-byte array of hash</returns> public static byte[] GetSHAHash(byte[] input_buffer, SHAType shaType) { switch (shaType) { case SHAType.SHA1: SHA1 sha1 = new SHA1CryptoServiceProvider(); return(sha1.ComputeHash(input_buffer)); case SHAType.SHA256: System.Security.Cryptography.SHA256 sha256 = System.Security.Cryptography.SHA256.Create(); return(sha256.ComputeHash(input_buffer)); case SHAType.SHA384: System.Security.Cryptography.SHA384 sha384 = System.Security.Cryptography.SHA384.Create(); return(sha384.ComputeHash(input_buffer)); case SHAType.SHA512: System.Security.Cryptography.SHA512 sha512 = System.Security.Cryptography.SHA512.Create(); return(sha512.ComputeHash(input_buffer)); } return(null); }
public void FIPS186_Test3 (SHA512 hash) { string className = hash.ToString (); byte[] result = { 0xe7, 0x18, 0x48, 0x3d, 0x0c, 0xe7, 0x69, 0x64, 0x4e, 0x2e, 0x42, 0xc7, 0xbc, 0x15, 0xb4, 0x63, 0x8e, 0x1f, 0x98, 0xb1, 0x3b, 0x20, 0x44, 0x28, 0x56, 0x32, 0xa8, 0x03, 0xaf, 0xa9, 0x73, 0xeb, 0xde, 0x0f, 0xf2, 0x44, 0x87, 0x7e, 0xa6, 0x0a, 0x4c, 0xb0, 0x43, 0x2c, 0xe5, 0x77, 0xc3, 0x1b, 0xeb, 0x00, 0x9c, 0x5c, 0x2c, 0x49, 0xaa, 0x2e, 0x4e, 0xad, 0xb2, 0x17, 0xad, 0x8c, 0xc0, 0x9b }; 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); }
internal static async Task InstallFromStream(Stream stream, Library library, string packagesDirectory, SHA512 sha512, bool performingParallelInstalls = false) { var packagePathResolver = new DefaultPackagePathResolver(packagesDirectory); var targetPath = packagePathResolver.GetInstallPath(library.Name, library.Version); var targetNuspec = packagePathResolver.GetManifestFilePath(library.Name, library.Version); var targetNupkg = packagePathResolver.GetPackageFilePath(library.Name, library.Version); var hashPath = packagePathResolver.GetHashPath(library.Name, library.Version); // Acquire the lock on a nukpg before we extract it to prevent the race condition when multiple // processes are extracting to the same destination simultaneously await ConcurrencyUtilities.ExecuteWithFileLocked(targetNupkg, async createdNewLock => { // If this is the first process trying to install the target nupkg, go ahead // After this process successfully installs the package, all other processes // waiting on this lock don't need to install it again. if (createdNewLock && !File.Exists(targetNupkg)) { var extractPath = targetPath; if (performingParallelInstalls) { // Extracting to the {id}/{version} has an issue with concurrent installs - when a package has been partially // extracted, the Restore Operation can inadvertly conclude the package is available locally and proceed to read // partially written package contents. To avoid this we'll extract the package to a sibling directory and Move it // to the target path. extractPath = Path.Combine(Path.GetDirectoryName(targetPath), Path.GetRandomFileName()); targetNupkg = Path.Combine(extractPath, Path.GetFileName(targetNupkg)); } var extractDirectory = Directory.CreateDirectory(extractPath); using (var nupkgStream = new FileStream( targetNupkg, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete, bufferSize: 4096, useAsync: true)) { await stream.CopyToAsync(nupkgStream); nupkgStream.Seek(0, SeekOrigin.Begin); ExtractPackage(extractPath, nupkgStream); } // Fixup the casing of the nuspec on disk to match what we expect var nuspecFile = Directory.EnumerateFiles(targetPath, "*" + NuGet.Constants.ManifestExtension).Single(); if (!string.Equals(nuspecFile, targetNuspec, StringComparison.Ordinal)) { Manifest manifest = null; using (var nuspecStream = File.OpenRead(nuspecFile)) { manifest = Manifest.ReadFrom(nuspecStream, validateSchema: false); manifest.Metadata.Id = library.Name; } // Delete the previous nuspec file File.Delete(nuspecFile); // Write the new manifest using (var targetNuspecStream = File.OpenWrite(targetNuspec)) { manifest.Save(targetNuspecStream); } } stream.Seek(0, SeekOrigin.Begin); var nupkgSHA = Convert.ToBase64String(sha512.ComputeHash(stream)); File.WriteAllText(hashPath, nupkgSHA); if (performingParallelInstalls) { extractDirectory.MoveTo(targetPath); } } return 0; }); }
private static unsafe void FillKeyDerivation( ReadOnlySpan <byte> password, ReadOnlySpan <byte> salt, int iterations, string hashAlgorithmName, Span <byte> destination) { SafeBCryptKeyHandle keyHandle; int hashBlockSizeBytes = GetHashBlockSize(hashAlgorithmName); // stackalloc 0 to let compiler know this cannot escape. Span <byte> clearSpan = stackalloc byte[0]; ReadOnlySpan <byte> symmetricKeyMaterial = stackalloc byte[0]; int symmetricKeyMaterialLength; if (password.IsEmpty) { // CNG won't accept a null pointer for the password. symmetricKeyMaterial = stackalloc byte[1]; symmetricKeyMaterialLength = 0; clearSpan = default; } else if (password.Length <= hashBlockSizeBytes) { // Password is small enough to use as-is. symmetricKeyMaterial = password; symmetricKeyMaterialLength = password.Length; clearSpan = default; } else { // RFC 2104: "The key for HMAC can be of any length (keys longer than B bytes are // first hashed using H). // We denote by B the byte-length of such // blocks (B=64 for all the above mentioned examples of hash functions) // // Windows' PBKDF2 will do this up to a point. To ensure we accept arbitrary inputs for // PBKDF2, we do the hashing ourselves. Span <byte> hashBuffer = stackalloc byte[512 / 8]; // 64 bytes is SHA512, the largest digest handled. int hashBufferSize; switch (hashAlgorithmName) { case HashAlgorithmNames.SHA1: hashBufferSize = SHA1.HashData(password, hashBuffer); break; case HashAlgorithmNames.SHA256: hashBufferSize = SHA256.HashData(password, hashBuffer); break; case HashAlgorithmNames.SHA384: hashBufferSize = SHA384.HashData(password, hashBuffer); break; case HashAlgorithmNames.SHA512: hashBufferSize = SHA512.HashData(password, hashBuffer); break; default: Debug.Fail($"Unexpected hash algorithm '{hashAlgorithmName}'"); throw new CryptographicException(); } clearSpan = hashBuffer.Slice(0, hashBufferSize); symmetricKeyMaterial = clearSpan; symmetricKeyMaterialLength = hashBufferSize; } Debug.Assert(symmetricKeyMaterial.Length > 0); NTSTATUS generateKeyStatus; if (Interop.BCrypt.PseudoHandlesSupported) { fixed(byte *pSymmetricKeyMaterial = symmetricKeyMaterial) { generateKeyStatus = Interop.BCrypt.BCryptGenerateSymmetricKey( (nuint)BCryptAlgPseudoHandle.BCRYPT_PBKDF2_ALG_HANDLE, out keyHandle, pbKeyObject: IntPtr.Zero, cbKeyObject: 0, pSymmetricKeyMaterial, symmetricKeyMaterialLength, dwFlags: 0); } } else { if (s_pbkdf2AlgorithmHandle is null) { NTSTATUS openStatus = Interop.BCrypt.BCryptOpenAlgorithmProvider( out SafeBCryptAlgorithmHandle pbkdf2AlgorithmHandle, Internal.NativeCrypto.BCryptNative.AlgorithmName.Pbkdf2, null, BCryptOpenAlgorithmProviderFlags.None); if (openStatus != NTSTATUS.STATUS_SUCCESS) { pbkdf2AlgorithmHandle.Dispose(); CryptographicOperations.ZeroMemory(clearSpan); throw Interop.BCrypt.CreateCryptographicException(openStatus); } // This might race, and that's okay. Worst case the algorithm is opened // more than once, and the ones that lost will get cleaned up during collection. Interlocked.CompareExchange(ref s_pbkdf2AlgorithmHandle, pbkdf2AlgorithmHandle, null); } fixed(byte *pSymmetricKeyMaterial = symmetricKeyMaterial) { generateKeyStatus = Interop.BCrypt.BCryptGenerateSymmetricKey( s_pbkdf2AlgorithmHandle, out keyHandle, pbKeyObject: IntPtr.Zero, cbKeyObject: 0, pSymmetricKeyMaterial, symmetricKeyMaterialLength, dwFlags: 0); } } CryptographicOperations.ZeroMemory(clearSpan); if (generateKeyStatus != NTSTATUS.STATUS_SUCCESS) { keyHandle.Dispose(); throw Interop.BCrypt.CreateCryptographicException(generateKeyStatus); } Debug.Assert(!keyHandle.IsInvalid); ulong kdfIterations = (ulong)iterations; // Previously asserted to be positive. using (keyHandle) fixed(char *pHashAlgorithmName = hashAlgorithmName) fixed(byte *pSalt = salt) fixed(byte *pDestination = destination) { Span <BCryptBuffer> buffers = stackalloc BCryptBuffer[3]; buffers[0].BufferType = CngBufferDescriptors.KDF_ITERATION_COUNT; buffers[0].pvBuffer = (IntPtr)(&kdfIterations); buffers[0].cbBuffer = sizeof(ulong); buffers[1].BufferType = CngBufferDescriptors.KDF_SALT; buffers[1].pvBuffer = (IntPtr)pSalt; buffers[1].cbBuffer = salt.Length; buffers[2].BufferType = CngBufferDescriptors.KDF_HASH_ALGORITHM; buffers[2].pvBuffer = (IntPtr)pHashAlgorithmName; // C# spec: "A char* value produced by fixing a string instance always points to a null-terminated string" buffers[2].cbBuffer = checked ((hashAlgorithmName.Length + 1) * sizeof(char)); // Add null terminator. fixed(BCryptBuffer *pBuffers = buffers) { Interop.BCrypt.BCryptBufferDesc bufferDesc; bufferDesc.ulVersion = Interop.BCrypt.BCRYPTBUFFER_VERSION; bufferDesc.cBuffers = buffers.Length; bufferDesc.pBuffers = (IntPtr)pBuffers; NTSTATUS deriveStatus = Interop.BCrypt.BCryptKeyDerivation( keyHandle, &bufferDesc, pDestination, destination.Length, out uint resultLength, dwFlags: 0); if (deriveStatus != NTSTATUS.STATUS_SUCCESS) { throw Interop.BCrypt.CreateCryptographicException(deriveStatus); } if (destination.Length != resultLength) { Debug.Fail("PBKDF2 resultLength != destination.Length"); throw new CryptographicException(); } } } }
public void FIPS186_e (string testName, SHA512 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 (); }
public void FIPS186_a (string testName, SHA512 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 (); }
public void FIPS186_c (string testName, SHA512 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 (); }
public void FIPS186_b (string testName, SHA512 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 Hash() { hasher = new SHA512Managed(); }
/// <summary>Creates an instance of the default implementation of <see cref="T:System.Security.Cryptography.SHA512" />.</summary> /// <returns>A new instance of <see cref="T:System.Security.Cryptography.SHA512" />.</returns> /// <exception cref="T:System.Reflection.TargetInvocationException">The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.</exception> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" /> /// </PermissionSet> public new static SHA512 Create() { return(SHA512.Create("System.Security.Cryptography.SHA512")); }
IEnumerator Login(string formScreenName, string formPassword) { string formText = ""; string URL = UserBlobManager.GetComponent <UserBlobManager>().ServerURL + "uw.php"; string hash = UserBlobManager.GetComponent <UserBlobManager>().ServerHash; string date = System.DateTime.Now.Year.ToString("D4"); date += System.DateTime.Now.Month.ToString("D2"); date += System.DateTime.Now.Day.ToString("D2"); // encrypt the password byte[] bytes = System.Text.Encoding.ASCII.GetBytes(hash + formPassword); System.Security.Cryptography.SHA512 sha = System.Security.Cryptography.SHA512.Create(); byte[] shaHash = sha.ComputeHash(bytes); string result = ByteArrayToHexString(shaHash); WWWForm form = new WWWForm(); form.AddField("action", "login"); form.AddField("myform_hash", hash); form.AddField("myform_ScreenName", formScreenName); form.AddField("myform_Password", result); form.AddField("myform_Date", date); WWW w = new WWW(URL, form); yield return(w); if (w.error != null) { // connection error print(w.error); if (w.error.Contains("Could not resolve host")) { if (PopUpActive == false) { PopUpOkDialog("Can NOT connect to server.\nPlease check your internet connection.", this.gameObject.GetComponent <UI_Login>(), "WrongScreenNamePassword"); } } } else { formText = w.text; if (formText.Contains("HASH code is different from your app")) { print("Can't connect"); w.Dispose(); if (PopUpActive == false) { PopUpOkDialog("Cant connect to server.", this.gameObject.GetComponent <UI_Login>(), "WrongScreenNamePassword"); } } else { if (formText.Contains("ScreenName or password is wrong.")) { if (PopUpActive == false) { PopUpOkDialog("Screen name or password is wrong.", this.gameObject.GetComponent <UI_Login>(), "WrongScreenNamePassword"); } } if (formText.Contains("Data invalid - cant find name")) { if (PopUpActive == false) { PopUpOkDialog("Screen name is wrong.", this.gameObject.GetComponent <UI_Login>(), "WrongScreenNamePassword"); } } if (formText.Contains("PASSWORD CORRECT")) { print("Login OK"); string[] tempArray = formText.Split('#'); string name = tempArray[1]; string firstName = tempArray[2]; string lastName = tempArray[3]; string email = tempArray[4]; string streetAddress = tempArray[5]; string city = tempArray[6]; string state = tempArray[7]; string zip = tempArray[8]; string gender = tempArray[9]; if (UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.RememberLoginPassword == true) { UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserLogin = name; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserPassword = formPassword; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserFirstName = firstName; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserLastName = lastName; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserEmail = email; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserStreetAddress = streetAddress; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserCity = city; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserState = state; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserZip = zip; UserBlobManager.GetComponent <UserBlobManager>().UserSettingsData.UserGender = gender; UserBlobManager.GetComponent <UserBlobManager>().SaveSettings(); } UserBlobManager.GetComponent <UserBlobManager>().UserDownloadTrainingDataString = ""; UserBlobManager.GetComponent <UserBlobManager>().UserDownloadWorkoutDataString = ""; UserBlobManager.GetComponent <UserBlobManager>().UserDownloadExerciseDataString = ""; UIShare.GetComponent <UI_Share>().UpdateFriendList = true; UIManager.GetComponent <UI_Manager>().SwitchStates("ShareState"); } } } w.Dispose(); }
private LockFileLibrary CreateLockFileLibrary(LocalPackageInfo package, SHA512 sha512, string correctedPackageName) { var lockFileLib = new LockFileLibrary(); // package.Id is read from nuspec and it might be in wrong casing. // correctedPackageName should be the package name used by dependency graph and // it has the correct casing that runtime needs during dependency resolution. lockFileLib.Name = correctedPackageName ?? package.Id; lockFileLib.Version = package.Version; using (var nupkgStream = File.OpenRead(package.ZipPath)) { lockFileLib.Sha512 = Convert.ToBase64String(sha512.ComputeHash(nupkgStream)); nupkgStream.Seek(0, SeekOrigin.Begin); var packageReader = new PackageReader(nupkgStream); // Get package files, excluding directory entries lockFileLib.Files = packageReader.GetFiles().Where(x => !x.EndsWith("/")).ToList(); } return lockFileLib; }
public FileSystemSessionManager(string path) { this.path = path; this.encrypter = new SHA512Managed(); }
public Sha512() { _digest = SHA512.Create(); _digest.Initialize(); }
public static byte[] Sha512(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 (sha512Lock) { if (sha512Alg == null) { sha512Alg = SHA512.Create(); } sha512Alg.Initialize(); foreach (byte[] source in sources) { int offset = 0; while (offset < source.Length) { offset += sha512Alg.TransformBlock(source, offset, source.Length - offset, source, offset); } } sha512Alg.TransformFinalBlock(new byte[0], 0, 0); return sha512Alg.Hash; } }
public void FIPS186_d (string testName, SHA512 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 (); }
/// <summary> /// Gets the SHA512 of the password. /// </summary> /// <param name="password">the password to hash.</param> /// <param name="hashProvider">The hash provider.</param> /// <returns>The computed hash.</returns> private static byte[] GetHash( SecureString password, SHA512 hashProvider) { byte[] encodedText = password.ToEncodedClearText(); try { return hashProvider.ComputeHash(encodedText); } finally { encodedText.Zero(); } }
private static SHA512 pGetSHA512() { if (objSHA512 == null) { return objSHA512 = new SHA512Managed(); } return objSHA512; }
// Initialize the static class static Cryptography() { shaHasher = new SHA512Managed(); md5Hasher = MD5.Create(); encoder = new UTF8Encoding(); }
public static LockFileLibrary CreateLockFileLibraryForProject( Runtime.Project project, IPackage package, SHA512 sha512, IEnumerable<FrameworkName> frameworks, IPackagePathResolver resolver, string correctedPackageName = null) { var lockFileLib = new LockFileLibrary(); // package.Id is read from nuspec and it might be in wrong casing. // correctedPackageName should be the package name used by dependency graph and // it has the correct casing that runtime needs during dependency resolution. lockFileLib.Name = correctedPackageName ?? package.Id; lockFileLib.Version = package.Version; using (var nupkgStream = package.GetStream()) { lockFileLib.Sha = Convert.ToBase64String(sha512.ComputeHash(nupkgStream)); } lockFileLib.Files = package.GetFiles().Select(p => p.Path).ToList(); foreach (var framework in frameworks) { var group = new LockFileFrameworkGroup(); group.TargetFramework = framework; IEnumerable<PackageDependencySet> dependencySet; if (VersionUtility.TryGetCompatibleItems(framework, package.DependencySets, out dependencySet)) { var set = dependencySet.FirstOrDefault()?.Dependencies?.ToList(); if (set != null) { group.Dependencies = set; } } // TODO: Remove this when we do #596 // ASP.NET Core isn't compatible with generic PCL profiles if (!string.Equals(framework.Identifier, VersionUtility.AspNetCoreFrameworkIdentifier, StringComparison.OrdinalIgnoreCase) && !string.Equals(framework.Identifier, VersionUtility.DnxCoreFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)) { IEnumerable<FrameworkAssemblyReference> frameworkAssemblies; if (VersionUtility.TryGetCompatibleItems(framework, package.FrameworkAssemblies, out frameworkAssemblies)) { foreach (var assemblyReference in frameworkAssemblies) { if (!assemblyReference.SupportedFrameworks.Any() && !VersionUtility.IsDesktop(framework)) { // REVIEW: This isn't 100% correct since none *can* mean // any in theory, but in practice it means .NET full reference assembly // If there's no supported target frameworks and we're not targeting // the desktop framework then skip it. // To do this properly we'll need all reference assemblies supported // by each supported target framework which isn't always available. continue; } group.FrameworkAssemblies.Add(assemblyReference); } } } group.RuntimeAssemblies = GetPackageAssemblies(package, framework); string contractPath = Path.Combine("lib", "contract", package.Id + ".dll"); var hasContract = lockFileLib.Files.Any(path => path == contractPath); var hasLib = group.RuntimeAssemblies.Any(); if (hasContract && hasLib && !VersionUtility.IsDesktop(framework)) { group.CompileTimeAssemblies.Add(contractPath); } else if (hasLib) { group.CompileTimeAssemblies.AddRange(group.RuntimeAssemblies); } lockFileLib.FrameworkGroups.Add(group); } var installPath = resolver.GetInstallPath(package.Id, package.Version); foreach (var assembly in lockFileLib.FrameworkGroups.SelectMany(f => f.RuntimeAssemblies)) { var assemblyPath = Path.Combine(installPath, assembly); if (IsAssemblyServiceable(assemblyPath)) { lockFileLib.IsServiceable = true; break; } } return lockFileLib; }
private static SHA512 GetHasher512() { if (_hasher512 == null) { _hasher512 = SHA512Managed.Create(); } return _hasher512; }
/// <summary> /// MD5 is no longer safe. The implementation will now use SHA512 /// Hashes the given byte array /// </summary> /// <param name="input">Byte array to hash</param> public static byte[] CalculateMD5Hash(byte[] input) { using (var hasher = SHA512.Create()) return(hasher.ComputeHash(input)); }
public HashProvider() { _hashCalculator = new SHA512Managed(); }
public override byte[] ByteHashAlgorithm(string value) { System.Security.Cryptography.SHA512 sha = System.Security.Cryptography.SHA512.Create(); byte[] bytes = sha.ComputeHash(System.Text.ASCIIEncoding.UTF8.GetBytes(value)); return(bytes); }