本文整理汇总了C#中System.Security.Cryptography.HashAlgorithm.TransformFinalBlock方法的典型用法代码示例。如果您正苦于以下问题:C# HashAlgorithm.TransformFinalBlock方法的具体用法?C# HashAlgorithm.TransformFinalBlock怎么用?C# HashAlgorithm.TransformFinalBlock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.HashAlgorithm
的用法示例。
在下文中一共展示了HashAlgorithm.TransformFinalBlock方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
示例2: GetDigestedBytes
internal byte[] GetDigestedBytes(HashAlgorithm hash)
{
this.m_c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, this.m_ancMgr);
hash.TransformFinalBlock(new byte[0], 0, 0);
byte[] buffer = (byte[]) hash.Hash.Clone();
hash.Initialize();
return buffer;
}
示例3: FIPS186_d
public void FIPS186_d(string testName, HashAlgorithm hash, byte[] input, byte[] result)
{
hash.TransformFinalBlock (input, 0, input.Length);
// LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue !
// AssertEquals( testName + ".d.1", result, output );
Assert.AreEqual (result, hash.Hash, testName + ".d");
// required or next operation will still return old hash
hash.Initialize ();
}
示例4: GetHashValue
/// <summary>
/// Retrieves the string representation of the hash. (Completes the creation of the hash).
/// </summary>
/// <param name="hash">The hashing object.</param>
/// <returns>A string that is the content of the hash.</returns>
internal static string GetHashValue(HashAlgorithm hash)
{
// Finalize the hash
hash.TransformFinalBlock(new byte[0], 0, 0);
var bytes = hash.Hash;
// Convert hash to string
return Convert.ToBase64String(bytes);
}
示例5: Update
/// <summary>
/// Updates a partial checksum with the given data.
/// </summary>
/// <param name="data"></param>
public void Update(ArraySegment<byte> data)
{
finalizedHash = (HashAlgorithm)deepCopy(hash);
hash.TransformBlock(data.Array, data.Offset, data.Count, null, 0);
// We do this here (instead of a null transform) because the SHA0
// implementation seems to fail for short messages if you simply
// transform an empty block later.
finalizedHash.TransformFinalBlock(data.Array, data.Offset, data.Count);
offset += data.Count;
}
示例6: FIPS186_e
public void FIPS186_e(string testName, HashAlgorithm 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);
hash.TransformFinalBlock (input, input.Length - 1, 1);
// LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue !
// AssertEquals (testName + ".e.1", result, output);
Assert.AreEqual (result, hash.Hash, testName + ".e");
// required or next operation will still return old hash
hash.Initialize ();
}
示例7: ComputeHash
public byte[] ComputeHash(FileStream fileStream, HashAlgorithm hashAlgorithm, byte[] buffer)
{
while (true)
{
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead == buffer.Length)
{
hashAlgorithm.TransformBlock(buffer, 0, bytesRead, buffer, 0);
}
else
{
hashAlgorithm.TransformFinalBlock(buffer, 0, bytesRead);
return hashAlgorithm.Hash;
}
}
}
示例8: ComputeHash
/// <summary>
/// Computes a file hash without loading the entire file into memory.
/// </summary>
/// <param name="filePath">Path of the file to hash.</param>
/// <param name="hashAlgorithm">Algorithm to hash in. Example: 'new SHA1CryptoServiceProvider()'</param>
/// <returns></returns>
public static string ComputeHash(string filePath, HashAlgorithm hashAlgorithm)
{
try
{
using (var stream = (Stream)File.Open(filePath, FileMode.Open))
{
int _bufferSize = 4096; // this makes it impossible to change the buffer size while computing
byte[] readAheadBuffer, buffer;
int readAheadBytesRead, bytesRead;
long size, totalBytesRead = 0;
size = stream.Length;
readAheadBuffer = new byte[_bufferSize];
readAheadBytesRead = stream.Read(readAheadBuffer, 0, readAheadBuffer.Length);
totalBytesRead += readAheadBytesRead;
do
{
bytesRead = readAheadBytesRead;
buffer = readAheadBuffer;
readAheadBuffer = new byte[_bufferSize];
readAheadBytesRead = stream.Read(readAheadBuffer, 0, readAheadBuffer.Length);
totalBytesRead += readAheadBytesRead;
if (readAheadBytesRead == 0)
hashAlgorithm.TransformFinalBlock(buffer, 0, bytesRead);
else
hashAlgorithm.TransformBlock(buffer, 0, bytesRead, buffer, 0);
} while (readAheadBytesRead != 0);
}
string hex = "";
foreach (byte b in hashAlgorithm.Hash)
hex += b.ToString("x2");
return hex.ToLower();
}
catch (Exception)
{
return null;
}
}
示例9: CalculateHash
/// <exception cref="IOException">The underlying stream is null or closed. </exception>
/// <exception cref="DirectoryNotFoundException">The specified path is invalid, (for example, it is on an unmapped drive). </exception>
/// <exception cref="UnauthorizedAccessException"><paramref name="path" /> specified a directory.-or- The caller does not have the required permission. </exception>
/// <exception cref="FileNotFoundException">The file specified in <paramref name="path" /> was not found. </exception>
/// <exception cref="CryptographicUnexpectedOperationException"><see cref="F:System.Security.Cryptography.HashAlgorithm.HashValue" /> is null. </exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
/// <exception cref="ArgumentNullException"><paramref name="oldValue" /> is null. </exception>
/// <exception cref="ArgumentException"><paramref name="oldValue" /> is the empty string (""). </exception>
/// <exception cref="Exception">A delegate callback throws an exception.</exception>
/// <exception cref="OperationCanceledException">The token has had cancellation requested.</exception>
public string CalculateHash(string file, HashAlgorithm algorithm, CancellationToken token)
{
byte[] buffer;
byte[] oldBuffer;
int bytesRead;
int oldBytesRead;
long size;
long totalBytesRead = 0;
using (var bufferedStream = new BufferedStream(File.OpenRead(file)))
{
using (algorithm)
{
size = bufferedStream.Length;
buffer = new byte[4096];
bytesRead = bufferedStream.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
do
{
token.ThrowIfCancellationRequested();
oldBytesRead = bytesRead;
oldBuffer = buffer;
buffer = new byte[4096];
bytesRead = bufferedStream.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
if (bytesRead == 0)
{
algorithm.TransformFinalBlock(oldBuffer, 0, oldBytesRead);
}
else
{
algorithm.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0);
}
HashProgressUpdate?.Invoke(this, new ProgressEventArgs((double) totalBytesRead*100/size));
} while (bytesRead != 0);
return BitConverter.ToString(algorithm.Hash).Replace("-", string.Empty).ToUpper();
}
}
}
示例10: TestHash
// tests a hash algorithm instance
public static bool TestHash(HashAlgorithm hash)
{
bool bRes = true;
// decide on the number of passes
int nPasses = m_Rnd.Next(MAX_PASSES) + 1;
Log.Comment("Doing " + nPasses + " passes...");
while (0 != nPasses--)
{
// init the hash object
hash.Initialize();
// create a random data blob
int nSize = m_Rnd.Next(MAX_SIZE);
byte[] abBlob = new byte[nSize];
Log.Comment("Test buffer size is " + nSize);
// first try ComputeHash
byte[] hash1 = hash.ComputeHash(abBlob);
// Log.Comment("Hash1:");
// PrintByteArray(hash1);
// now try stream
hash.Initialize();
byte[] hash2 = hash.TransformFinalBlock(abBlob, 0, abBlob.Length);
//CryptoStream cs = new CryptoStream(CryptoStream.Null, hash, CryptoStreamMode.Write);
//cs.Write(abBlob, 0, abBlob.Length);
//cs.Close();
//byte[] hash2 = hash.Hash;
// Log.Comment("Hash2:");
// PrintByteArray(hash2);
if (Compare(hash1, hash2))
{
Log.Comment(" OK.");
}
else
{
bRes = false;
Log.Comment(" FAILED. Hashes are different.");
}
}
return bRes;
}
示例11: Reset
public override void Reset ()
{
state = 0;
position = 0;
hashnumber = 0;
hash = HashAlgorithm.Create (HashNameValue);
if (SaltValue != null) {
hash.TransformBlock (password, 0, password.Length, password, 0);
hash.TransformFinalBlock (SaltValue, 0, SaltValue.Length);
initial = hash.Hash;
}
else
initial = hash.ComputeHash (password);
}
示例12: DownloadFile
/// <summary>
/// Downloads the file and returns the SHA-1 hash of the content of the saved file
/// </summary>
/// <param name="remoteDocument">Remote document.</param>
/// <param name="localFileStream">Local taget file stream.</param>
/// <param name="transmission">Transmission status.</param>
/// <param name="hashAlg">Hash algoritm, which should be used to calculate hash of the uploaded stream content</param>
/// <exception cref="IOException">On any disc or network io exception</exception>
/// <exception cref="DisposeException">If the remote object has been disposed before the dowload is finished</exception>
/// <exception cref="AbortException">If download is aborted</exception>
/// <exception cref="CmisException">On exceptions thrown by the CMIS Server/Client</exception>
public void DownloadFile(
IDocument remoteDocument,
Stream localFileStream,
Transmission transmission,
HashAlgorithm hashAlg,
UpdateChecksum update = null)
{
byte[] buffer = new byte[8 * 1024];
int len;
if (localFileStream.Length > 0) {
localFileStream.Seek(0, SeekOrigin.Begin);
while ((len = localFileStream.Read(buffer, 0, buffer.Length)) > 0) {
hashAlg.TransformBlock(buffer, 0, len, buffer, 0);
}
}
long offset = localFileStream.Position;
long? fileLength = remoteDocument.ContentStreamLength;
if (fileLength <= offset) {
transmission.Length = fileLength.GetValueOrDefault();
transmission.Position = offset;
hashAlg.TransformFinalBlock(new byte[0], 0, 0);
return;
}
DotCMIS.Data.IContentStream contentStream = null;
if (offset > 0) {
long remainingBytes = (long)fileLength - offset;
transmission.Length = remoteDocument.ContentStreamLength;
transmission.Position = offset;
contentStream = remoteDocument.GetContentStream(remoteDocument.ContentStreamId, offset, remainingBytes);
} else {
contentStream = remoteDocument.GetContentStream();
}
using (var transmissionStream = transmission.CreateStream(localFileStream))
using (CryptoStream hashstream = new CryptoStream(transmissionStream, hashAlg, CryptoStreamMode.Write))
using (Stream remoteStream = contentStream != null ? contentStream.Stream : new MemoryStream(0)) {
transmission.Length = remoteDocument.ContentStreamLength;
transmission.Position = offset;
int written = 0;
while ((len = remoteStream.Read(buffer, 0, buffer.Length)) > 0) {
lock (this.disposeLock) {
if (this.disposed) {
transmission.Status = TransmissionStatus.ABORTED;
throw new ObjectDisposedException(transmission.Path);
}
try {
hashstream.Write(buffer, 0, len);
hashstream.Flush();
written += len;
} catch (Exception) {
this.UpdateHash(hashAlg, localFileStream.Length, update);
throw;
}
if (written >= 1024 * 1024) {
this.UpdateHash(hashAlg, localFileStream.Length, update);
written = 0;
}
}
}
if (written > 0) {
this.UpdateHash(hashAlg, localFileStream.Length, update);
}
}
}
示例13: UploadFile
/// <summary>
/// Uploads the file.
/// Resumes an upload if the given localFileStream.Position is larger than zero.
/// </summary>
/// <returns>
/// The new CMIS document.
/// </returns>
/// <param name='remoteDocument'>
/// Remote document where the local content should be uploaded to.
/// </param>
/// <param name='localFileStream'>
/// Local file stream.
/// </param>
/// <param name='transmission'>
/// Transmission status where the uploader should report its uploading status.
/// </param>
/// <param name='hashAlg'>
/// Hash alg which should be used to calculate a checksum over the uploaded content.
/// </param>
/// <param name='overwrite'>
/// If true, the local content will overwrite the existing content.
/// </param>
/// <param name="update">Is called on every new chunk, if not <c>null</c>.</param>
/// <exception cref="CmisSync.Lib.Tasks.UploadFailedException">
/// Contains the last successful remote document state. This is needed for continue a failed upload.
/// </exception>
public override IDocument UploadFile(
IDocument remoteDocument,
Stream localFileStream,
Transmission transmission,
HashAlgorithm hashAlg,
bool overwrite = true,
UpdateChecksum update = null)
{
IDocument result = remoteDocument;
for (long offset = localFileStream.Position; offset < localFileStream.Length; offset += this.ChunkSize) {
bool isFirstChunk = offset == 0;
bool isLastChunk = (offset + this.ChunkSize) >= localFileStream.Length;
using (var hashstream = new NonClosingHashStream(localFileStream, hashAlg, CryptoStreamMode.Read))
using (var chunkstream = new ChunkedStream(hashstream, this.ChunkSize))
using (var offsetstream = new OffsetStream(chunkstream, offset))
using (var transmissionStream = transmission.CreateStream(offsetstream)) {
transmission.Length = localFileStream.Length;
transmission.Position = offset;
chunkstream.ChunkPosition = offset;
ContentStream contentStream = new ContentStream();
contentStream.FileName = remoteDocument.Name;
contentStream.MimeType = Cmis.MimeType.GetMIMEType(remoteDocument.Name);
if (isLastChunk) {
contentStream.Length = localFileStream.Length - offset;
} else {
contentStream.Length = this.ChunkSize;
}
contentStream.Stream = transmissionStream;
try {
if (isFirstChunk && result.ContentStreamId != null && overwrite) {
result.DeleteContentStream(true);
}
result.AppendContentStream(contentStream, isLastChunk, true);
HashAlgorithmReuse reuse = hashAlg as HashAlgorithmReuse;
if (reuse != null && update != null) {
using (HashAlgorithm hash = (HashAlgorithm)reuse.Clone()) {
hash.TransformFinalBlock(new byte[0], 0, 0);
update(hash.Hash, result.ContentStreamLength.GetValueOrDefault());
}
}
} catch (Exception e) {
if (e is FileTransmission.AbortException) {
throw;
}
if (e.InnerException is FileTransmission.AbortException) {
throw e.InnerException;
}
throw new UploadFailedException(e, result);
}
}
}
hashAlg.TransformFinalBlock(new byte[0], 0, 0);
return result;
}
示例14: UnsaltedCrypt
static string UnsaltedCrypt(HashAlgorithm algorithm, byte[] password)
{
try
{
algorithm.Initialize();
algorithm.TransformBlock(password, 0, password.Length, password, 0);
algorithm.TransformFinalBlock(new byte[0], 0, 0);
string crypt = Convert.ToBase64String(algorithm.Hash);
return crypt;
}
finally
{
algorithm.Clear();
}
}
示例15: Reset
public override void Reset ()
{
#if NET_2_0
state = 0;
#else
// note: Reset doesn't change state
#endif
position = 0;
hashnumber = 0;
hash = HashAlgorithm.Create (HashNameValue);
if (SaltValue != null) {
hash.TransformBlock (password, 0, password.Length, password, 0);
hash.TransformFinalBlock (SaltValue, 0, SaltValue.Length);
initial = hash.Hash;
}
else
initial = hash.ComputeHash (password);
}