本文整理汇总了C#中System.Security.Cryptography.HashAlgorithm.ComputeHash方法的典型用法代码示例。如果您正苦于以下问题:C# HashAlgorithm.ComputeHash方法的具体用法?C# HashAlgorithm.ComputeHash怎么用?C# HashAlgorithm.ComputeHash使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.HashAlgorithm
的用法示例。
在下文中一共展示了HashAlgorithm.ComputeHash方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestSha
private bool TestSha(HashAlgorithm alg1, HashAlgorithm alg2)
{
string tstStr = "This is a string that I will be getting the hash of!";
byte[] testHash = System.Text.UTF8Encoding.UTF8.GetBytes(tstStr);
byte[] hash1 = alg1.ComputeHash(testHash, 0, testHash.Length);
byte[] hash2 = alg1.ComputeHash(testHash, 0, testHash.Length);
byte[] hash3 = alg1.ComputeHash(testHash, 0, testHash.Length - 1);
byte[] hash4 = alg2.ComputeHash(testHash);
byte[] hash5 = alg2.ComputeHash(testHash, 0, testHash.Length - 1);
if (hash1.Length != (alg1.HashSize/8)) throw new Exception();
bool res1 = true, res2 = true, res3 = true, res4 = true;
for (int i = 0; i < hash1.Length; i++)
{
res1 &= (hash1[i] == hash2[i]);
res2 &= (hash1[i] == hash3[i]);
res3 &= (hash1[i] == hash4[i]);
res4 &= (hash3[i] == hash5[i]);
}
return res1 && !res2 && res3 && res4;
}
示例2: DoubleDigest
public static byte[] DoubleDigest(byte[] input, int offset, int length)
{
_digest.Dispose();
_digest = new SHA256CryptoServiceProvider();
byte[] first = _digest.ComputeHash(input, offset, length);
return _digest.ComputeHash(first);
}
示例3: Chunk
public List<RdcSignature> Chunk(Stream stream, int averagChunkBitLength, int minChunk, int maxChunk, int window)
{
hashAlg = MD5.Create();
hashBuffer = new byte[maxChunk];
hashLength = 0;
int mask = (1 << averagChunkBitLength) - 1;
List<RdcSignature> signatures = new List<RdcSignature>();
long length = stream.Length;
long lastStart = 0;
// get the initial hash window //
int hash = inithash(window, stream);
long position = window; //position starts at window size
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while (position < length)
{
// chunk boundry is found and chunk is sufficiently large
if ((hash & mask) == 0 && hashLength >= minChunk)
{
lastStart = position;
signatures.Add(new RdcSignature(position, (ushort)hashLength, hashAlg.ComputeHash(hashBuffer, 0, hashLength)));
hashLength = 0;
}
else if (position - lastStart + 1 >= maxChunk) // force a break if the chunk is large enough
{
lastStart = position;
signatures.Add(new RdcSignature(position, (ushort)hashLength, hashAlg.ComputeHash(hashBuffer, 0, hashLength)));
hashLength = 0;
}
// next window's hash //
hash = nexthash(hash, stream);
/////////////////////////
position++;
//if (position % REPORT_BOUNDRY == 0) {
// Console.WriteLine("{0}ms", stopwatch.ElapsedMilliseconds);
// stopwatch.Restart();
//}
}
//If we didn't have a break on the last position of the file
if (hashLength > 0)
{
lastStart = position;
signatures.Add(new RdcSignature(position, (ushort)hashLength, hashAlg.ComputeHash(hashBuffer, 0, hashLength)));
hashLength = 0;
}
return signatures;
}
示例4: ComputeHash
/// <summary>Compute hash on input stream</summary>
/// <param name="input">The stream to compute hash on.</param>
/// <param name="algorithm"> </param>
/// <returns>The hash as a hexadecimal String.</returns>
public static string ComputeHash(this Stream input, HashAlgorithm algorithm)
{
if (input == null)
throw new ArgumentNullException("input");
#if !SILVERLIGHT
var stream = new BufferedStream(input, 1024 * 8);
byte[] data = algorithm.ComputeHash(stream);
return ToHex(data);
#else
byte[] data = algorithm.ComputeHash(input);
return ToHex(data);
#endif
}
示例5: CalculateHash
/// <summary>
/// File content hash calculation
/// </summary>
/// <example>
/// <code>
/// // Implementation of <see cref="CalculateSha256Hash"/>
/// public static QuickIOHashResult CalculateSha256Hash( QuickIOPathInfo pathInfo )
/// {
/// using ( var fs = OpenRead( pathInfo ) )
/// using ( var hashAlgorithm = SHA256.Create( ) )
/// {
/// return CalculateHash( hashAlgorithm, fs );
/// }
/// }
/// </code>
/// </example>
/// <returns><see cref="QuickIOHashResult"/></returns>
public static QuickIOHashResult CalculateHash( HashAlgorithm hashAlgorithm, Stream stream )
{
Contract.Requires( hashAlgorithm != null );
Contract.Requires( stream != null );
return new QuickIOHashResult( hashAlgorithm.ComputeHash( stream ) );
}
示例6: StartTests
protected int StartTests(HashAlgorithm hash, byte[] input, byte[] result)
{
try {
byte[] ch = hash.ComputeHash(input, 0, input.Length);
if (!ArrayEquals(ch, result))
AddError("HB-ST1");
} catch {
AddError("HB-ST2");
}
try {
// feed input byte-by-byte
for(int i = 0; i < input.Length - 1; i++) {
hash.TransformBlock(input, i, 1, input, i);
}
if (input.Length > 0)
hash.TransformFinalBlock(input, input.Length - 1, 1);
else
hash.TransformFinalBlock(input, 0, 0);
if (!ArrayEquals(hash.Hash, result)) {
AddError("HB-ST3");
Console.WriteLine(Encoding.ASCII.GetString(input));
}
} catch {
AddError("HB-ST4");
} finally {
hash.Initialize();
}
return 4;
}
示例7: ValidateChecksum
public static bool ValidateChecksum(HashAlgorithm hashAlgorithm, Stream checksumFile, string filenameToCheck, Stream fileToCheck)
{
// Find the checksum...
string checksum = null;
using (var checksumFileReader = new StreamReader(checksumFile, Encoding.ASCII, false, 256, true))
{
while (checksum == null)
{
var line = checksumFileReader.ReadLine();
if (line == null)
break;
line = line.Trim();
var parts = line.Split(new[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
throw new ArgumentException("Invalid format of input file");
if (parts[1] == filenameToCheck)
checksum = parts[0];
}
}
if (checksum == null)
throw new ArgumentException($"Could not find checksum for file {filenameToCheck} in checksumFile");
byte[] hash = hashAlgorithm.ComputeHash(fileToCheck);
var formattedHash = FormatHash(hash);
return formattedHash == checksum;
}
示例8: GetHashFromFile
public static string GetHashFromFile(string fileName, HashAlgorithm algorithm)
{
using (var stream = new BufferedStream(File.OpenRead(fileName), 100000))
{
return BitConverter.ToString(algorithm.ComputeHash(stream)).Replace("-", string.Empty);
}
}
示例9: GetHashFile
private static String GetHashFile(String filename, HashAlgorithm hash)
{
FileStream fs = null;
try
{
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
Int64 currentPos = fs.Position;
fs.Seek(0, SeekOrigin.Begin);
StringBuilder sb = new StringBuilder();
foreach (Byte b in hash.ComputeHash(fs))
{
sb.Append(b.ToString("X2"));
}
fs.Close();
return sb.ToString();
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
string error = ex.Message;
return "";
}
}
示例10: ComputeHash
/// <summary>
/// Generates a hash for the given plain text value and returns a
/// base64-encoded result.
/// </summary>
/// <param name="text">Plaintext value to be hashed. The function does not check whether this parameter is null.</param>
/// <param name="hashAlgorithm">Hash algorithm to be used.</param>
/// <returns>Hash value formatted as a base64-encoded string.</returns>
/// <exception cref="System.InvalidOperationException"></exception>
/// <exception cref="System.ArgumentNullException"></exception>
/// <exception cref="System.Text.EncoderFallbackException"></exception>
/// <exception cref="System.ObjectDisposedException"></exception>
/// <exception cref="System.ArgumentException"></exception>
public static string ComputeHash(string text, HashAlgorithm hashAlgorithm)
{
Refresh();
if (hashAlgorithm == null)
throw new ArgumentNullException("hashAlgorithm");
return Convert.ToBase64String(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(text)));
}
示例11: CreateHash
private static string CreateHash(
HashAlgorithm algo,
byte[] value)
{
return HexDigest(
algo.ComputeHash(value));
}
示例12: ToBase64Hash
public static string ToBase64Hash(this string inputString, Encoding encoding, HashAlgorithm algo)
{
var inputBuffer = encoding.GetBytes(inputString);
var outputBuffer = algo.ComputeHash(inputBuffer, 0, inputBuffer.Length);
return Convert.ToBase64String(outputBuffer);
}
示例13: Hash
private static string Hash(string str, HashAlgorithm hashAlgorithm)
{
if (string.IsNullOrEmpty(str)) return str;
byte[] s = hashAlgorithm.ComputeHash(UnicodeEncoding.UTF8.GetBytes(str));
return BitConverter.ToString(s);
}
示例14: HashString
public static string HashString(string inputString, string salt, HashAlgorithm algorithm)
{
if (inputString == null)
{
throw new ArgumentException("inputString cannot be null.");
}
if (algorithm == null)
{
throw new ArgumentException("algorithm cannot be null.");
}
if (salt == null)
{
throw new ArgumentException("saltString cannot be null.");
}
//Mix password with salt.
byte[] stringWithSalt = System.Text.Encoding.UTF8.GetBytes(inputString + salt);
//Compute hash.
byte[] hashedBytes = algorithm.ComputeHash(stringWithSalt);
// Convert hashed password bytes to string and remove "-".
string hashedString = BitConverter.ToString(hashedBytes).Replace("-", string.Empty);
// Return hashed password string in lowercase.
return hashedString.ToLower();
}
示例15: HashFile
public static Tuple<byte[], string> HashFile(HashAlgorithm ha, string file)
{
using (var fs = File.OpenRead(file))
{
return new Tuple<byte[], string>(ha.ComputeHash(fs), file);
}
}