public TransformFinalBlock ( byte inputBuffer, int inputOffset, int inputCount ) : byte[] | ||
inputBuffer | byte | |
inputOffset | int | |
inputCount | int | |
리턴 | byte[] |
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; }
/// <summary>Calculates the hash for a Leaf node.</summary> /// <param name="data">The data to hash.</param> /// <param name="offset">Where in the data array to start hashing.</param> /// <param name="count">How many bytes in the data array to hash.</param> /// <returns>The resulting Leaf hash.</returns> protected byte[] LeafHash(byte[] data, int offset, int count) { hashAlgorithm.Initialize(); hashAlgorithm.TransformBlock(new byte[1] { 0 }, 0, 1, null, 0); hashAlgorithm.TransformFinalBlock(data, offset, count); return(hashAlgorithm.Hash); }
public static string Hash(Stream input, HashAlgorithm algorithm) { System.Security.Cryptography.HashAlgorithm hasher = GetAlgorithm(algorithm); byte[] buffer = new byte[StreamBufferSize]; int read; long currentPosition = 0L; long streamLength = input.Length; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { currentPosition += read; #pragma warning disable IDE0045 // Convert to conditional expression if (currentPosition < streamLength) { _ = hasher.TransformBlock(buffer, 0, read, buffer, 0); } else { _ = hasher.TransformFinalBlock(buffer, 0, read); } #pragma warning restore IDE0045 // Convert to conditional expression } byte[] hashBytes = hasher.Hash; string hastStr = hashBytes.ToHex(); return(hastStr); }
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; }
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 (); }
/// <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); }
/// <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; }
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 (); }
//---------------------------------------------------------------------------------- protected override byte[] HashFinal() { if (!_bhashing) { _h1.TransformBlock(_binner, 0, _blocksize, _binner, 0); _bhashing = true; } _h1.TransformFinalBlock(new byte[0], 0, 0); _h2.TransformBlock(_bouter, 0, _blocksize, _bouter, 0); _h2.TransformFinalBlock(_h1.Hash, 0, _h1.Hash.Length); _bhashing = false; return(_h2.Hash); }
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; } } }
/// <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; } }
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); } }
protected override byte[] HashFinal() { if (m_hashing == false) { m_hash1.TransformBlock(m_inner, 0, m_inner.Length, m_inner, 0); m_hashing = true; } // finalize the original hash m_hash1.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0); byte[] hashValue1 = m_hash1.HashValue; // write the outer array m_hash2.TransformBlock(m_outer, 0, m_outer.Length, m_outer, 0); // write the inner hash and finalize the hash m_hash2.TransformBlock(hashValue1, 0, hashValue1.Length, hashValue1, 0); m_hashing = false; m_hash2.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0); return(m_hash2.HashValue); }
private byte[] ComputeBaseValue() { _hash.Initialize(); _hash.TransformBlock(_password, 0, _password.Length, _password, 0); if (_salt != null) { _hash.TransformBlock(_salt, 0, _salt.Length, _salt, 0); } _hash.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0); _baseValue = _hash.Hash; _hash.Initialize(); for (int i = 1; i < (_iterations - 1); i++) { _hash.ComputeHash(_baseValue); _baseValue = _hash.Hash; } return(_baseValue); }
/// <summary>Process the last block of data.</summary> /// <param name="inputBuffer">The block of data to process.</param> /// <param name="inputOffset">Where to start in the block.</param> /// <param name="inputCount">How many bytes need to be processed.</param> /// <returns>The results of the completed hash calculation.</returns> override protected byte[] ProcessFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { lock (syncLock) { if (inputCount > 0) { workingNodes.Add(new HashNode(hashAlgorithm.ComputeHash(inputBuffer, inputOffset, inputCount), Count, (Count + inputCount - 1))); } finalNodes = workingNodes; // Calculate the top hash. hashAlgorithm.Initialize(); foreach (HashNode node in this) { hashAlgorithm.TransformBlock(node.Hash, 0, node.Hash.Length, null, 0); } hashAlgorithm.TransformFinalBlock(new byte[1], 0, 0); return(hashAlgorithm.Hash); } }
/// <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(); } } }
protected override byte[] HashFinal() { if (_disposed) { throw new ObjectDisposedException("HMAC"); } State = 0; Block.Final(); byte[] intermediate = _algo.Hash; byte[] buf = KeySetup(Key, 0x5C); _algo.Initialize(); _algo.TransformBlock(buf, 0, buf.Length, buf, 0); _algo.TransformFinalBlock(intermediate, 0, intermediate.Length); byte[] hash = _algo.Hash; _algo.Initialize(); // zeroize sensitive data Array.Clear(buf, 0, buf.Length); Array.Clear(intermediate, 0, intermediate.Length); return(hash); }
/// <summary> /// Retrieve the hash or HMAC for the data accumulated from prior calls to /// <see cref="AppendData(byte[])"/>, and return to the state the object /// was in at construction. /// </summary> /// <returns>The computed hash or HMAC.</returns> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> public byte[] GetHashAndReset() { if (_disposed) { throw new ObjectDisposedException(typeof(IncrementalHash).Name); } Debug.Assert(_hash != null); if (_resetPending) { // No point in setting _resetPending to false, we're about to set it to true. _hash.Initialize(); } _hash.TransformFinalBlock(Array.Empty <byte>(), 0, 0); byte[] hashValue = _hash.Hash; _resetPending = true; return(hashValue); }
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); } }
public override byte[] GenerateMask(byte[] rgbSeed, int cbReturn) { using (HashAlgorithm hasher = SHA1.Create()) { byte[] rgbCounter = new byte[4]; byte[] rgbT = new byte[cbReturn]; uint counter = 0; for (int ib = 0; ib < rgbT.Length;) { // Increment counter -- up to 2^32 * sizeof(Hash) Helpers.ConvertIntToByteArray(counter++, rgbCounter); hasher.TransformBlock(rgbSeed, 0, rgbSeed.Length, rgbSeed, 0); hasher.TransformFinalBlock(rgbCounter, 0, 4); byte[] hash = hasher.Hash; hasher.Initialize(); Buffer.BlockCopy(hash, 0, rgbT, ib, Math.Min(rgbT.Length - ib, hash.Length)); ib += hasher.Hash.Length; } return(rgbT); } }
/// <summary> /// Uploads the localFileStream to remoteDocument. /// </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> /// <exception cref="CmisSync.Lib.Tasks.UploadFailedException">If upload fails</exception> public virtual IDocument UploadFile( IDocument remoteDocument, Stream localFileStream, Transmission transmission, HashAlgorithm hashAlg, bool overwrite = true, UpdateChecksum update = null) { if (remoteDocument == null) { throw new ArgumentException("remoteDocument can not be null"); } if (localFileStream == null) { throw new ArgumentException("localFileStream can not be null"); } if (transmission == null) { throw new ArgumentException("status can not be null"); } if (hashAlg == null) { throw new ArgumentException("hashAlg can not be null"); } using(NonClosingHashStream hashstream = new NonClosingHashStream(localFileStream, hashAlg, CryptoStreamMode.Read)) using(var transmissionStream = transmission.CreateStream(hashstream)) { ContentStream contentStream = new ContentStream(); contentStream.FileName = remoteDocument.Name; contentStream.MimeType = Cmis.MimeType.GetMIMEType(contentStream.FileName); contentStream.Stream = transmissionStream; try { remoteDocument.SetContentStream(contentStream, overwrite, true); } catch(Exception e) { throw new UploadFailedException(e, remoteDocument); } } hashAlg.TransformFinalBlock(new byte[0], 0, 0); return remoteDocument; }
private static void TransformFinalBlock(HashAlgorithm hash, SecureString secureString) { var bstr = Marshal.SecureStringToBSTR(secureString); try { var passwordChars = new char[secureString.Length]; var passwordCharsHandle = GCHandle.Alloc(passwordChars, GCHandleType.Pinned); try { Marshal.Copy(bstr, passwordChars, 0, passwordChars.Length); var passwordBytes = new byte[secureString.Length * 3]; // worst case for UTF16 to UTF8 encoding var passwordBytesHandle = GCHandle.Alloc(passwordBytes, GCHandleType.Pinned); try { var encoding = new UTF8Encoding(false, true); var length = encoding.GetBytes(passwordChars, 0, passwordChars.Length, passwordBytes, 0); hash.TransformFinalBlock(passwordBytes, 0, length); } finally { Array.Clear(passwordBytes, 0, passwordBytes.Length); passwordBytesHandle.Free(); } } finally { Array.Clear(passwordChars, 0, passwordChars.Length); passwordCharsHandle.Free(); } } finally { Marshal.ZeroFreeBSTR(bstr); } }
static string SaltedCrypt(HashAlgorithm algorithm, byte[] password, byte[] salt) { // If we're under the hash length, assume we only have the salt. int hashLength = algorithm.HashSize / 8; int saltOffset = salt.Length < hashLength ? 0 : hashLength; int saltLength = salt.Length - saltOffset; byte[] saltedHash = new byte[hashLength + saltLength]; try { algorithm.Initialize(); algorithm.TransformBlock(password, 0, password.Length, password, 0); algorithm.TransformBlock(salt, saltOffset, saltLength, salt, saltOffset); algorithm.TransformFinalBlock(new byte[0], 0, 0); Array.Copy(algorithm.Hash, saltedHash, hashLength); Array.Copy(salt, saltOffset, saltedHash, hashLength, saltLength); string crypt = Convert.ToBase64String(saltedHash); return crypt; } finally { algorithm.Clear(); Security.Clear(saltedHash); } }
private void IncrementalTest(HashAlgorithm nonIncAlg, HashAlgorithm IncAlg) { byte[] sample = new byte[10000]; new System.Random().NextBytes(sample); byte[] expectedHash = nonIncAlg.ComputeHash(sample); Assert.AreEqual(true, IncAlg.CanTransformMultipleBlocks, "hash algorithm must say that it can do it"); for(int i=0; i<10000; i+=500) { if (i < 9500) IncAlg.TransformBlock(sample, i, 500, sample, i); else IncAlg.TransformFinalBlock(sample, i, 500); } byte[] actualHash = IncAlg.Hash; Assert.AreEqual(BitConverter.ToString(expectedHash), BitConverter.ToString(actualHash), "Expected and actual hashes do not match"); }
public static bool TestSingleBlock(HashAlgorithm hash, byte[] data, byte[] digest) { hash.Initialize(); hash.TransformFinalBlock(data, 0, data.Length); if (!CompareBytes(hash.Hash, digest)) { Log.Comment("SingleBlock test failed"); return false; } return true; }
public static bool TestMultiBlock(HashAlgorithm hash, byte[] data, byte[] digest) { int pos = 0; hash.Initialize(); while (data.Length - pos >= 1) pos += hash.TransformBlock(data, pos, 1, data, pos); hash.TransformFinalBlock(data, pos, data.Length - pos); if (!CompareBytes(hash.Hash, digest)) { Log.Comment("MultiBlock test failed"); return false; } return true; }
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(); } }
// 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; }
/// <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); } } }
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); }
public (SM2DeriveBytes?Key, byte[] Verifier, byte[] PeerVerifier) DeriveKey( EcPoint peerPubKey, EcPoint peerR, ReadOnlySpan <byte> peerIdent) { if (!_ephemeralKey.Param.Curve.ValidatePoint(peerPubKey)) { throw new CryptographicException(); } if (!_ephemeralKey.Param.Curve.ValidatePoint(peerR)) { throw new CryptographicException(); } var pkBytes = (_ephemeralKey.Param.Curve.BitLength + 7) / 8; var zPeer = SM2.ZValue(_ephemeralKey.Param, _hash, peerIdent, peerPubKey); var w = _ephemeralKey.Param.BitLength; if (_ephemeralKey.Param.N.IsPowerOfTwo) { w -= 1; } w = (ushort)((w >> 1) + (w & 1) - 1); var w2 = (BigInteger)1 << w; var x2 = w2 + (_ephemeralKey.Q.X & (w2 - 1)); var t = (_privateKey + x2 * _ephemeralKey.D) % _ephemeralKey.Param.N; var x1 = w2 + (peerR.X & (w2 - 1)); var vi = _ephemeralKey.Param.Curve.MultiplyAndAdd(1, peerPubKey, x1, peerR, _rng); var v = _ephemeralKey.Param.Curve.ToAffine(_ephemeralKey.Param.Curve.Multiply(_ephemeralKey.Param.H * t, vi, _rng)); if (v.Inf) { return(null, null !, null !); } var za = _responder ? zPeer : _zValue; var zb = _responder ? _zValue : zPeer; var zl = za.Length + zb.Length; var key = new byte[pkBytes * 2 + zl]; var xv = v.X.ToByteArrayUBe(pkBytes); var yv = v.Y.ToByteArrayUBe(pkBytes); xv.CopyTo(key, 0); yv.CopyTo(key, pkBytes); za.CopyTo(key, pkBytes * 2); zb.CopyTo(key, pkBytes * 2 + za.Length); var kdf = new SM2DeriveBytes(key, _hash); var ra = _responder ? peerR : _ephemeralKey.Q; var rb = _responder ? _ephemeralKey.Q : peerR; #if NETSTANDARD2_0 || NETSTANDARD2_1 _hash.Initialize(); _hash.TransformBlock(xv, 0, pkBytes, null, 0); _hash.TransformBlock(za, 0, za.Length, null, 0); _hash.TransformBlock(zb, 0, zb.Length, null, 0); _hash.TransformBlock(ra.X.ToByteArrayUBe(pkBytes), 0, pkBytes, null, 0); _hash.TransformBlock(ra.Y.ToByteArrayUBe(pkBytes), 0, pkBytes, null, 0); _hash.TransformBlock(rb.X.ToByteArrayUBe(pkBytes), 0, pkBytes, null, 0); _hash.TransformFinalBlock(rb.Y.ToByteArrayUBe(pkBytes), 0, pkBytes); var si = _hash.Hash; _hash.Initialize(); key[0] = 2; _hash.TransformBlock(key, 0, 1, null, 0); _hash.TransformBlock(yv, 0, pkBytes, null, 0); _hash.TransformFinalBlock(si, 0, si.Length); var sb = _hash.Hash; _hash.Initialize(); key[0] = 3; _hash.TransformBlock(key, 0, 1, null, 0); _hash.TransformBlock(yv, 0, pkBytes, null, 0); _hash.TransformFinalBlock(si, 0, si.Length); var sa = _hash.Hash; #else var sib = ArrayPool <byte> .Shared.Rent(pkBytes * 5 + zl); xv.CopyTo(sib, 0); za.CopyTo(sib, pkBytes); zb.CopyTo(sib, pkBytes + za.Length); ra.X.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes); ra.Y.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes * 2); rb.X.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes * 3); rb.Y.ToByteArrayUBe(pkBytes).CopyTo(sib, zl + pkBytes * 4); var si = _hash.ComputeHash(sib, 0, pkBytes * 5 + zl); ArrayPool <byte> .Shared.Return(sib); var sbb = ArrayPool <byte> .Shared.Rent(pkBytes + si.Length + 1); yv.CopyTo(sbb, 1); si.CopyTo(sbb, pkBytes + 1); sbb[0] = 2; var sb = _hash.ComputeHash(sbb, 0, pkBytes + si.Length + 1); sbb[0] = 3; var sa = _hash.ComputeHash(sbb, 0, pkBytes + si.Length + 1); ArrayPool <byte> .Shared.Return(sbb); #endif return(kdf, _responder ? sb : sa, _responder ? sa : sb); }
/// <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; }
void FinishDigest(HashAlgorithm algorithm) { algorithm.TransformFinalBlock(new byte[0], 0, 0); }
private void BgWorker_DoWork(object sender, DoWorkEventArgs e) { switch (selectedHash) { case HashAlgo.MD5: Hash = new MD5CryptoServiceProvider(); break; case HashAlgo.SHA1: Hash = new SHA1CryptoServiceProvider(); break; case HashAlgo.SHA256: Hash = new SHA256CryptoServiceProvider(); break; case HashAlgo.SHA384: Hash = new SHA384CryptoServiceProvider(); break; case HashAlgo.SHA512: Hash = new SHA512CryptoServiceProvider(); break; case HashAlgo.RipeMd: Hash = new RIPEMD160Managed(); break; //case HashAlgo.Adler32: // Hash = new Adler32(); // break; case HashAlgo.CRC32: Hash = new CRC32(); break; } try { inFile = new FileStream(FileNameTextBox.Text, FileMode.Open); const int bufSize = 4096; byte[] buffer = new byte[bufSize]; int readBytes = 1; long filePos; long fileLength = inFile.Length; while (readBytes > 0) { int progress; readBytes = inFile.Read(buffer, 0, bufSize); filePos = inFile.Position; if (readBytes == 4096) { Hash.TransformBlock(buffer, 0, bufSize, null, 0); progress = (int)(((float)filePos / (float)fileLength) * 100); } else { Hash.TransformFinalBlock(buffer, 0, readBytes); progress = 100; } BgWorker.ReportProgress(progress); } hashingFinished = true; inFile.Close(); } catch (IOException) { MessageBox.Show("Can't open selected file.", "File Open Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (CryptographicException) { MessageBox.Show("There was an error while processing the file.", "Hashing Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception ex) { MessageBox.Show(ex.Message, ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <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> /// <param name="update">Not or not yet used</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; while ((len = localFileStream.Read(buffer, 0, buffer.Length)) > 0) { hashAlg.TransformBlock(buffer, 0, len, buffer, 0); } } long? fileLength = remoteDocument.ContentStreamLength; // Download content if exists if (fileLength > 0) { long offset = localFileStream.Position; long remainingBytes = (fileLength != null) ? (long)fileLength - offset : this.ChunkSize; try { do { offset += this.DownloadNextChunk(remoteDocument, offset, remainingBytes, transmission, localFileStream, hashAlg); } while(fileLength == null); } catch (DotCMIS.Exceptions.CmisConstraintException) { } } else { transmission.Position = 0; transmission.Length = 0; } hashAlg.TransformFinalBlock(new byte[0], 0, 0); }
internal byte[] GetHash (HashAlgorithm hash) { if (blockNo < 1) ReadFirstBlock (); fs.Position = blockLength; // hash the rest of the file long n; int addsize = 0; // minus any authenticode signature (with 8 bytes header) if (dirSecurityOffset > 0) { // it is also possible that the signature block // starts within the block in memory (small EXE) if (dirSecurityOffset < blockLength) { blockLength = dirSecurityOffset; n = 0; } else { n = dirSecurityOffset - blockLength; } } else if (coffSymbolTableOffset > 0) { fileblock[PEOffset + 12] = 0; fileblock[PEOffset + 13] = 0; fileblock[PEOffset + 14] = 0; fileblock[PEOffset + 15] = 0; fileblock[PEOffset + 16] = 0; fileblock[PEOffset + 17] = 0; fileblock[PEOffset + 18] = 0; fileblock[PEOffset + 19] = 0; // it is also possible that the signature block // starts within the block in memory (small EXE) if (coffSymbolTableOffset < blockLength) { blockLength = coffSymbolTableOffset; n = 0; } else { n = coffSymbolTableOffset - blockLength; } } else { addsize = (int) (fs.Length & 7); if (addsize > 0) addsize = 8 - addsize; n = fs.Length - blockLength; } // Authenticode(r) gymnastics // Hash from (generally) 0 to 215 (216 bytes) int pe = peOffset + 88; hash.TransformBlock (fileblock, 0, pe, fileblock, 0); // then skip 4 for checksum pe += 4; // Continue hashing from (generally) 220 to 279 (60 bytes) hash.TransformBlock (fileblock, pe, 60, fileblock, pe); // then skip 8 bytes for IMAGE_DIRECTORY_ENTRY_SECURITY pe += 68; // everything is present so start the hashing if (n == 0) { // hash the (only) block hash.TransformFinalBlock (fileblock, pe, blockLength - pe); } else { // hash the last part of the first (already in memory) block hash.TransformBlock (fileblock, pe, blockLength - pe, fileblock, pe); // hash by blocks of 4096 bytes long blocks = (n >> 12); int remainder = (int)(n - (blocks << 12)); if (remainder == 0) { blocks--; remainder = 4096; } // blocks while (blocks-- > 0) { fs.Read (fileblock, 0, fileblock.Length); hash.TransformBlock (fileblock, 0, fileblock.Length, fileblock, 0); } // remainder if (fs.Read (fileblock, 0, remainder) != remainder) return null; if (addsize > 0) { hash.TransformBlock (fileblock, 0, remainder, fileblock, 0); hash.TransformFinalBlock (new byte [addsize], 0, addsize); } else { hash.TransformFinalBlock (fileblock, 0, remainder); } } return hash.Hash; }
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); }