本文整理汇总了C#中System.Security.Cryptography.SHA256Managed类的典型用法代码示例。如果您正苦于以下问题:C# SHA256Managed类的具体用法?C# SHA256Managed怎么用?C# SHA256Managed使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
SHA256Managed类属于System.Security.Cryptography命名空间,在下文中一共展示了SHA256Managed类的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.IO;
using System.Security.Cryptography;
public class HashDirectory
{
public static void Main(String[] args)
{
if (args.Length < 1)
{
Console.WriteLine("No directory selected.");
return;
}
string directory = args[0];
if (Directory.Exists(directory))
{
// Create a DirectoryInfo object representing the specified directory.
var dir = new DirectoryInfo(directory);
// Get the FileInfo objects for every file in the directory.
FileInfo[] files = dir.GetFiles();
// Initialize a SHA256 hash object.
using (SHA256 mySHA256 = SHA256.Create())
{
// Compute and print the hash values for each file in directory.
foreach (FileInfo fInfo in files)
{
try {
// Create a fileStream for the file.
FileStream fileStream = fInfo.Open(FileMode.Open);
// Be sure it's positioned to the beginning of the stream.
fileStream.Position = 0;
// Compute the hash of the fileStream.
byte[] hashValue = mySHA256.ComputeHash(fileStream);
// Write the name and hash value of the file to the console.
Console.Write($"{fInfo.Name}: ");
PrintByteArray(hashValue);
// Close the file.
fileStream.Close();
}
catch (IOException e) {
Console.WriteLine($"I/O Exception: {e.Message}");
}
catch (UnauthorizedAccessException e) {
Console.WriteLine($"Access Exception: {e.Message}");
}
}
}
}
else
{
Console.WriteLine("The directory specified could not be found.");
}
}
// Display the byte array in a readable format.
public static void PrintByteArray(byte[] array)
{
for (int i = 0; i < array.Length; i++)
{
Console.Write($"{array[i]:X2}");
if ((i % 4) == 3) Console.Write(" ");
}
Console.WriteLine();
}
}