Example #1
0
        public WardenRandom(byte[] seed)
        {
            Data1 = new byte[0x14];
            Data2 = new byte[0x14];
            Data3 = new byte[0x14];

            int length1 = (int)seed.Length >> 1;
            int length2 = seed.Length - length1;

            byte[] seed1 = new byte[length1];
            byte[] seed2 = new byte[length2];

            for (int i = 0; i < length1; i++)
                seed1[i] = seed[i];
            for (int i = 0; i < length2; i++)
                seed2[i] = seed[i + length1];

            SHA1 sha = new SHA1Managed();
            Data2 = sha.ComputeHash(seed1);
            Data3 = sha.ComputeHash(seed2);

            sha.Initialize();
            sha.TransformBlock(Data2, 0, Data2.Length, Data2, 0);
            sha.TransformBlock(Data1, 0, Data1.Length, Data1, 0);
            sha.TransformFinalBlock(Data3, 0, Data3.Length);

            Data1 = sha.Hash;

            sha.Initialize();
        }
Example #2
0
        public int CreateServerKeyExchangeSign(SecurityParameters sparams, byte[] params_buffer, int params_offset, int params_length, byte[] sign_buffer, int sign_offset)
        {
            byte[] hash;
            using (SHA1Managed sha1 = new SHA1Managed ()) {
                sha1.Initialize ();
                sha1.TransformBlock (sparams.ClientRandom, 0, sparams.ClientRandom.Length, sparams.ClientRandom, 0);
                sha1.TransformBlock (sparams.ServerRandom, 0, sparams.ServerRandom.Length, sparams.ServerRandom, 0);
                sha1.TransformBlock (params_buffer, params_offset, params_length, params_buffer, params_offset);
                sha1.TransformFinalBlock (Utility.EmptyByteArray, 0, 0);
                hash = sha1.Hash;
            }

            // 署名
            byte[] sign = _ecdsa.SignHash (hash);

            // DER形式に変換
            // TODO: 400bit以上の署名サイズに対応させる
            byte der_len = (byte)(sign.Length + 6);
            byte int_len = (byte)(sign.Length >> 1);
            sign_buffer[sign_offset + 0] = 0x30;
            sign_buffer[sign_offset + 1] = (byte)(der_len - 2);
            sign_buffer[sign_offset + 2] = 0x02;
            sign_buffer[sign_offset + 3] = int_len;
            Buffer.BlockCopy (sign, 0, sign_buffer, sign_offset + 4, int_len);
            sign_offset += int_len + 4;
            sign_buffer[sign_offset + 0] = 0x02;
            sign_buffer[sign_offset + 1] = int_len;
            Buffer.BlockCopy (sign, int_len, sign_buffer, sign_offset + 2, int_len);

            return der_len;
        }
Example #3
0
        private void Update()
        {
            SHA1Managed sha = new SHA1Managed();

            sha.TransformBlock(Data2, 0, Data2.Length, Data2, 0);
            sha.TransformBlock(Data1, 0, Data1.Length, Data1, 0);
            sha.TransformFinalBlock(Data3, 0, Data3.Length);

            Data1 = sha.Hash;
        }
        public void WriteTest() {
            byte[] content = new byte[1024];
            using (var stream = new MemoryStream(content))
            using (var hashAlg = new SHA1Managed())
            using (var outputstream = new MemoryStream()) {
                using (var hashstream = new NonClosingHashStream(outputstream, hashAlg, CryptoStreamMode.Write)) {
                    stream.CopyTo(hashstream);
                }

                Assert.AreEqual(content, outputstream.ToArray());
                hashAlg.TransformFinalBlock(new byte[0], 0, 0);
                Assert.AreEqual(SHA1.Create().ComputeHash(content), hashAlg.Hash);
            }
        }
        public static async void HandleAuthContinuedSession(AuthContinuedSession authContinuedSession, NodeSession session)
        {
            var accountInfo = Manager.Redirect.GetAccountInfo(authContinuedSession.Key);

            // Delete redirect key
            Manager.Redirect.DeleteRedirectKey(authContinuedSession.Key);

            if (accountInfo != null)
            {
                var sha1 = new SHA1Managed();

                var emailBytes = Encoding.UTF8.GetBytes(accountInfo.Item1.Id + "#" + accountInfo.Item2.Index);
                var sessionKeyBytes = accountInfo.Item2.SessionKey.ToByteArray();
                var challengeBytes = BitConverter.GetBytes(session.Challenge);

                sha1.TransformBlock(emailBytes, 0, emailBytes.Length, emailBytes, 0);
                sha1.TransformBlock(sessionKeyBytes, 0, 40, sessionKeyBytes, 0);
                sha1.TransformFinalBlock(challengeBytes, 0, 4);

                if (sha1.Hash.Compare(authContinuedSession.Digest))
                {
                    session.State = SessionState.Authenticated;

                    session.Account = DB.Auth.Single<Account>(a => a.Id == accountInfo.Item2.AccountId);
                    session.GameAccount = accountInfo.Item2;
                    session.Player = new Player(DB.Character.Single<Character>(c => c.Guid == accountInfo.Item3), false);

                    session.Crypt = new Framework.Cryptography.WoW.WoWCrypt();
                    session.Crypt.Initialize(accountInfo.Item2.SessionKey.ToByteArray(), session.ClientSeed, session.ServerSeed);

                    // Resume on the new connection
                    await session.Send(new ResumeComms());

                    session.State = SessionState.InWorld;

                    return;
                }
            }

            session.Dispose();
        }
        protected HgNodeID GetRevlogEntryDataNodeID(HgNodeID firstParentNodeID, HgNodeID secondParentNodeID, byte[] data)
        {
            var parents = new[] {
                Min(firstParentNodeID, secondParentNodeID),
                Max(firstParentNodeID, secondParentNodeID)
            };

            using(var hash = new SHA1Managed())
            {
                hash.Initialize();
                var buffer = new byte[hash.HashSize / 8];
                hash.TransformBlock(parents[0].NodeID, 0, 20, buffer, 0);
                hash.TransformBlock(parents[1].NodeID, 0, 20, buffer, 0);
                hash.TransformFinalBlock(data, 0, data.Length);

                buffer = hash.Hash;

                var node = new HgNodeID(buffer);

                return node;
            } // using
            
        }
Example #7
0
        public void ComputeBlocksWithBlockSize([Values(1, 1024, 324734)]int dataLength) {
            byte[] data = new byte[dataLength];

            using (SHA1Managed sha1 = new SHA1Managed())
            using (SHA1Reuse reuse = new SHA1Reuse()) {
                for (int i = 0; i < 10; ++i) {
                    sha1.TransformBlock(data, 0, dataLength, data, 0);
                    reuse.TransformBlock(data, 0, dataLength, data, 0);
                }

                sha1.TransformFinalBlock(data, dataLength, 0);
                reuse.TransformFinalBlock(data, dataLength, 0);
                Assert.IsTrue(sha1.Hash.SequenceEqual(reuse.Hash));
            }
        }
Example #8
0
        public void ComputeBlocksByEmptyBlockSize() {
            int dataLength = 0;
            byte[] data = new byte[dataLength];

            using (SHA1Managed sha1 = new SHA1Managed())
            using (SHA1Reuse reuse = new SHA1Reuse()) {
                for (int i = 0; i < 10; ++i) {
                    sha1.TransformBlock(data, 0, dataLength, data, 0);
                    reuse.TransformBlock(data, 0, dataLength, data, 0);
                }

                sha1.TransformFinalBlock(data, dataLength, 0);
                reuse.TransformFinalBlock(data, dataLength, 0);
                Assert.IsTrue(sha1.Hash.SequenceEqual(reuse.Hash));
            }
        }
Example #9
0
        public void ComputeBlocksViaClone() {
            int dataLength = 23;
            byte[] data = new byte[dataLength];

            using (SHA1Managed sha1 = new SHA1Managed())
            using (SHA1Managed sha1_1 = new SHA1Managed())
            using (SHA1Reuse reuse = new SHA1Reuse())
            using (SHA1Reuse hash0 = (SHA1Reuse)reuse.Clone()) {
                for (int i = 0; i < 100; i++) {
                    sha1.TransformBlock(data, 0, dataLength, data, 0);
                    sha1_1.TransformBlock(data, 0, dataLength, data, 0);
                    reuse.TransformBlock(data, 0, dataLength, data, 0);
                    hash0.TransformBlock(data, 0, dataLength, data, 0);
                }

                using(var hash1 = hash0.Clone() as HashAlgorithm)
                using(var hash2 = hash0.Clone() as HashAlgorithm)
                using(var hash3 = hash0.Clone() as HashAlgorithm) {
                    sha1.TransformFinalBlock(data, dataLength, 0);
                    reuse.TransformFinalBlock(data, dataLength, 0);
                    hash0.TransformFinalBlock(data, dataLength, 0);
                    Assert.That(sha1.Hash, Is.EqualTo(reuse.Hash));
                    Assert.That(sha1.Hash, Is.EqualTo(hash0.Hash));

                    for (int i = 0; i < 100; i++) {
                        sha1_1.TransformBlock(data, 0, dataLength, data, 0);
                        hash1.TransformBlock(data, 0, dataLength, data, 0);
                        hash2.TransformBlock(data, 0, dataLength, data, 0);
                        hash3.TransformBlock(data, 0, dataLength, data, 0);
                    }

                    hash1.TransformFinalBlock(data, dataLength, 0);
                    hash2.TransformFinalBlock(data, dataLength, 0);
                    hash3.TransformFinalBlock(data, dataLength, 0);
                    sha1_1.TransformFinalBlock(data, dataLength, 0);
                    Assert.That(sha1_1.Hash, Is.EqualTo(hash1.Hash));
                    Assert.That(sha1_1.Hash, Is.EqualTo(hash2.Hash));
                    Assert.That(sha1_1.Hash, Is.EqualTo(hash3.Hash));
                }
           }
        }
Example #10
0
        public void ComputeBlocksViaReuse() {
            int dataLength = 23;
            byte[] data = new byte[dataLength];

            using (SHA1Managed sha1 = new SHA1Managed())
            using (SHA1Reuse reuse = new SHA1Reuse()) {
                SHA1Reuse hash0 = (SHA1Reuse)reuse.Clone();
                sha1.TransformBlock(data, 0, dataLength, data, 0);
                reuse.TransformBlock(data, 0, dataLength, data, 0);
                hash0.TransformBlock(data, 0, dataLength, data, 0);

                SHA1Reuse hash1 = (SHA1Reuse)reuse.Clone();
                sha1.TransformBlock(data, 0, dataLength, data, 0);
                reuse.TransformBlock(data, 0, dataLength, data, 0);
                hash0.TransformBlock(data, 0, dataLength, data, 0);
                hash1.TransformBlock(data, 0, dataLength, data, 0);

                SHA1Reuse hash2 = (SHA1Reuse)reuse.Clone();
                sha1.TransformBlock(data, 0, dataLength, data, 0);
                reuse.TransformBlock(data, 0, dataLength, data, 0);
                hash0.TransformBlock(data, 0, dataLength, data, 0);
                hash1.TransformBlock(data, 0, dataLength, data, 0);
                hash2.TransformBlock(data, 0, dataLength, data, 0);

                SHA1Reuse hash3 = (SHA1Reuse)reuse.Clone();
                sha1.TransformFinalBlock(data, dataLength, 0);
                reuse.TransformFinalBlock(data, dataLength, 0);
                hash0.TransformFinalBlock(data, dataLength, 0);
                hash1.TransformFinalBlock(data, dataLength, 0);
                hash2.TransformFinalBlock(data, dataLength, 0);
                hash3.TransformFinalBlock(data, dataLength, 0);

                Assert.IsTrue(sha1.Hash.SequenceEqual(reuse.Hash));
                Assert.IsTrue(sha1.Hash.SequenceEqual(hash0.Hash));
                Assert.IsTrue(sha1.Hash.SequenceEqual(hash1.Hash));
                Assert.IsTrue(sha1.Hash.SequenceEqual(hash2.Hash));
                Assert.IsTrue(sha1.Hash.SequenceEqual(hash3.Hash));
            }
        }
Example #11
0
        private static string Hash(Bitmap image)
        {
            SHA1Managed sha1 = new SHA1Managed();

            int width = image.Width;
            int height = image.Height;
            bool disposeImage = false;

            if (image.PixelFormat != PixelFormat.Format32bppArgb) {
                Bitmap newImage = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(image)) {
                    g.DrawImage(image, 0, 0);
                }
                image = newImage;
                disposeImage = true;
            }

            BitmapData imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            IntPtr scan0 = imageData.Scan0;
            byte[] data = new byte[imageData.Stride];

            for (int y = 0; y < height; y++) {
                Marshal.Copy(scan0 + y * imageData.Stride, data, 0, data.Length);
                sha1.TransformBlock(data, 0, data.Length, null, 0);
            }

            image.UnlockBits(imageData);

            sha1.TransformBlock(BitConverter.GetBytes(width), 0, 4, null, 0);
            sha1.TransformBlock(BitConverter.GetBytes(height), 0, 4, null, 0);

            sha1.TransformFinalBlock(new byte[0], 0, 0);

            if (disposeImage)
                image.Dispose();

            return BitConverter.ToString(sha1.Hash, 0, 16);
        }
Example #12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="outputStream"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        /// <exception></exception>
        public static string DecryptStream(Stream inputStream, Stream outputStream, string Password)
        {
            byte[] encryptionAlgorithmBytes = new byte[10];
            inputStream.Read(encryptionAlgorithmBytes, 0, 10);
            if (!"AESV1     ".Equals(Encoding.ASCII.GetString(encryptionAlgorithmBytes)))
            {
                throw new Exception("The encryption algorithm used to encrypt this file is not supported.");
            }

            byte[] keySizeBytes = new byte[2];
            inputStream.Read(keySizeBytes, 0, 2);
            int keySize = System.BitConverter.ToInt16(keySizeBytes, 0);

            byte[] blockSizeBytes = new byte[2];
            inputStream.Read(blockSizeBytes, 0, 2);
            int blockSize = System.BitConverter.ToInt16(blockSizeBytes, 0);

            byte[] saltBytes = new byte[24];
            inputStream.Read(saltBytes, 0, 24);
            string salt = Encoding.ASCII.GetString(saltBytes);

            byte[] initVectorBytes = new byte[blockSize / 8];
            inputStream.Read(initVectorBytes, 0, blockSize / 8);

            byte[] fileLengthReportedBytes = new byte[8];
            inputStream.Read(fileLengthReportedBytes, 0, 8);
            long fileLengthReported = System.BitConverter.ToInt64(fileLengthReportedBytes, 0);

            byte[] hashAlgorithmBytes = new byte[10];
            inputStream.Read(hashAlgorithmBytes, 0, 10);
            if (!"SHA1V1    ".Equals(Encoding.ASCII.GetString(hashAlgorithmBytes)))
            {
                throw new Exception("The hash algorithm used to sign this file is not supported.");
            }

            long dataFileLength = inputStream.Length - 56 - (blockSize / 8);

            int streamBlockSize = 0x1000;

            System.Security.Cryptography.RijndaelManaged rijndaelProvider = new RijndaelManaged();
            rijndaelProvider.KeySize = keySize;
            rijndaelProvider.BlockSize = blockSize;
            rijndaelProvider.Key = CreateKeyFromPassword(Password, keySize, salt);
            rijndaelProvider.IV = initVectorBytes;
            rijndaelProvider.Mode = CipherMode.CBC;

            System.Security.Cryptography.SHA1Managed sha1Provider = new SHA1Managed();
            byte[] hashValueBytes = new byte[160 / 8];
            byte[] reportedHashValueBytes = new byte[160 / 8];

            System.Security.Cryptography.CryptoStream cryptoStream = new CryptoStream(inputStream, rijndaelProvider.CreateDecryptor(), CryptoStreamMode.Read);

            byte[] outputBytes = new byte[streamBlockSize];
            long inputPosition = 0;

            while (inputPosition < dataFileLength) //use data file length rather than self-reported length - in case someone messed with it and tries to get some sort of overflow error going.
            {
                cryptoStream.Read(outputBytes, 0, streamBlockSize);

                if (inputPosition + streamBlockSize < fileLengthReported)
                {
                    outputStream.Write(outputBytes, 0, streamBlockSize);
                    sha1Provider.TransformBlock(outputBytes, 0, streamBlockSize, null, 0); //the "transformed" output is irrelevant for SHA1
                }
                else
                {
                    long remainingDataSize = (fileLengthReported - inputPosition);

                    if (remainingDataSize > 0)
                    {
                        outputStream.Write(outputBytes, 0, (int)remainingDataSize);
                        sha1Provider.TransformBlock(outputBytes, 0, (int)remainingDataSize, null, 0); //the "transformed" output is irrelevant for SHA1

                        //get what we can of the original/reported hash, out of that last file data block.
                        for (int i = 0; (i + remainingDataSize < streamBlockSize) && (i < reportedHashValueBytes.Length); i++)
                        {
                            reportedHashValueBytes[i] = outputBytes[i + remainingDataSize];
                        }
                    }
                    else if (remainingDataSize + reportedHashValueBytes.Length > 0)
                    {
                        //if spillover into the next block, get the remainder of the original/reported hash.
                        for (int i = 0; (i < streamBlockSize) && (i - remainingDataSize < reportedHashValueBytes.Length); i++)
                        {
                            reportedHashValueBytes[i - remainingDataSize] = outputBytes[i];
                        }
                    }
                    //otherwise it is unexpected extra file padding that we ignore.
                }

                inputPosition += streamBlockSize;
            }

            cryptoStream.Close();
            cryptoStream.Dispose();
            bool hashFailure = false;
            sha1Provider.TransformFinalBlock(outputBytes, 0, 0);
            hashValueBytes = sha1Provider.Hash;
            if (reportedHashValueBytes != null
                && hashValueBytes != null
                && reportedHashValueBytes.Length == hashValueBytes.Length)
            {
                for (int i = 0; i < hashValueBytes.Length; i++)
                {
                    if (hashValueBytes[i] != reportedHashValueBytes[i])
                        hashFailure = true;
                }
            }
            else
                hashFailure = true;

            if (hashFailure)
            {
                throw new DecryptionHashCheckException();
            }

            return BitConverter.ToString(hashValueBytes);
        }
Example #13
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="outputStream"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public static string EncryptStream(Stream inputStream, Stream outputStream, string Password)
        {
            int keySize = 128;
            int blockSize = 256;
            int streamBlockSize = 0x1000;
            string salt = "*hw@o1$9kj}az|y83j'nsl_=";

            System.Security.Cryptography.RijndaelManaged rijndaelProvider = new RijndaelManaged();
            rijndaelProvider.KeySize = keySize;
            rijndaelProvider.BlockSize = blockSize;
            rijndaelProvider.Key = CreateKeyFromPassword(Password, keySize, salt);
            rijndaelProvider.GenerateIV();
            rijndaelProvider.Mode = CipherMode.CBC;

            System.Security.Cryptography.SHA1Managed sha1Provider = new SHA1Managed();
            byte[] hashValueBytes = new byte[160 / 8];

            //Write out encryption algorithm
            outputStream.Write(Encoding.ASCII.GetBytes("AESV1     "), 0, 10);
            //key size
            outputStream.Write(System.BitConverter.GetBytes((short)keySize), 0, 2);
            //block size
            outputStream.Write(System.BitConverter.GetBytes((short)blockSize), 0, 2);
            //salt (questionable?)
            outputStream.Write(Encoding.ASCII.GetBytes(salt), 0, 24);

            //IV
            outputStream.Write(rijndaelProvider.IV, 0, blockSize / 8);

            //Original File Size
            long inputLength = inputStream.Length;
            byte[] fileLengthBytes = System.BitConverter.GetBytes(inputLength);
            outputStream.Write(fileLengthBytes, 0, 8);

            //Hash Algorithm
            outputStream.Write(Encoding.ASCII.GetBytes("SHA1V1    "), 0, 10);

            System.Security.Cryptography.CryptoStream outStream = new CryptoStream(outputStream, rijndaelProvider.CreateEncryptor(), CryptoStreamMode.Write);

            byte[] inputBytes = new byte[streamBlockSize];

            long inputPosition = 0;

            while (inputPosition < inputLength)
            {
                if (inputPosition + streamBlockSize < inputLength)
                {
                    inputStream.Read(inputBytes, 0, streamBlockSize);
                    outStream.Write(inputBytes, 0, streamBlockSize);
                    sha1Provider.TransformBlock(inputBytes, 0, streamBlockSize, null, 0); //the "transformed" output is irrelevant for SHA1
                }
                else
                {
                    inputStream.Read(inputBytes, 0, (int)(inputLength - inputPosition));
                    outStream.Write(inputBytes, 0, (int)(inputLength - inputPosition));
                    sha1Provider.TransformBlock(inputBytes, 0, (int)(inputLength - inputPosition), null, 0);  //the "transformed" output is irrelevant for SHA1
                }

                inputPosition = inputPosition + streamBlockSize;
            }

            //Hash value - in the encrypted content (so no information leakage from hash)
            sha1Provider.TransformFinalBlock(inputBytes, 0, 0);
            hashValueBytes = sha1Provider.Hash;
            outStream.Write(hashValueBytes, 0, 160 / 8);
            outStream.FlushFinalBlock();

            outStream.Close();
            outStream.Dispose();

            return BitConverter.ToString(hashValueBytes);
        }
Example #14
0
        /// <summary>
        /// hash length is 40 unicode chars
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string Sha1(this string dt)
        {
            byte[] data = Encoding.UTF8.GetBytes(dt);
            using (HashAlgorithm sha = new SHA1Managed())
            {
                sha.TransformFinalBlock(data, 0, data.Length);
                var sb = new StringBuilder();
                foreach (byte bit in sha.Hash)
                {
                    sb.Append(bit.ToString("x2"));

                }
                return sb.ToString();
            }
        }
        /// <summary>
        /// Uploads the file content to the remote document.
        /// </summary>
        /// <returns>The SHA-1 hash of the uploaded file content.</returns>
        /// <param name="localFile">Local file.</param>
        /// <param name="doc">Remote document.</param>
        /// <param name="transmissionManager">Transmission manager.</param>
        /// <param name="transmissionEvent">File Transmission event.</param>
        /// <param name="mappedObject">Mapped object saved in <c>Storage</c></param>
        protected byte[] UploadFileWithPWC(IFileInfo localFile, ref IDocument doc, Transmission transmission, IMappedObject mappedObject = null) {
            byte[] checksum = null;
            var docPWC = this.LoadRemotePWCDocument(doc, ref checksum);

            using (var file = localFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) {
                if (checksum != null) {
                    // check PWC checksum for integration
                    using (var hashAlg = new SHA1Managed()) {
                        int bufsize = 8 * 1024;
                        byte[] buffer = new byte[bufsize];
                        for (long offset = 0; offset < docPWC.ContentStreamLength.GetValueOrDefault();) {
                            int readsize = bufsize;
                            if (readsize + offset > docPWC.ContentStreamLength.GetValueOrDefault()) {
                                readsize = (int)(docPWC.ContentStreamLength.GetValueOrDefault() - offset);
                            }

                            readsize = file.Read(buffer, 0, readsize);
                            hashAlg.TransformBlock(buffer, 0, readsize, buffer, 0);
                            offset += readsize;
                            if (readsize == 0) {
                                break;
                            }
                        }

                        hashAlg.TransformFinalBlock(new byte[0], 0, 0);
                        if (!hashAlg.Hash.SequenceEqual(checksum)) {
                            docPWC.DeleteContentStream();
                        }

                        file.Seek(0, SeekOrigin.Begin);
                    }
                }

                byte[] hash = null;
                var uploader = FileTransmission.ContentTaskUtils.CreateUploader(this.TransmissionStorage.ChunkSize);
                using (var hashAlg = new SHA1Reuse()) {
                    try {
                        using (var hashstream = new NonClosingHashStream(file, hashAlg, CryptoStreamMode.Read)) {
                            int bufsize = 8 * 1024;
                            byte[] buffer = new byte[bufsize];
                            for (long offset = 0; offset < docPWC.ContentStreamLength.GetValueOrDefault();) {
                                int readsize = bufsize;
                                if (readsize + offset > docPWC.ContentStreamLength.GetValueOrDefault()) {
                                    readsize = (int)(docPWC.ContentStreamLength.GetValueOrDefault() - offset);
                                }

                                readsize = hashstream.Read(buffer, 0, readsize);
                                offset += readsize;
                                if (readsize == 0) {
                                    break;
                                }
                            }
                        }

                        var document = doc;
                        uploader.UploadFile(docPWC, file, transmission, hashAlg, false, (byte[] checksumUpdate, long length) => this.SaveRemotePWCDocument(localFile, document, docPWC, checksumUpdate, transmission));
                        hash = hashAlg.Hash;
                    } catch (Exception ex) {
                        transmission.FailedException = ex;
                        throw;
                    }
                }

                this.TransmissionStorage.RemoveObjectByRemoteObjectId(doc.Id);

                var properties = new Dictionary<string, object>();
                properties.Add(PropertyIds.LastModificationDate, localFile.LastWriteTimeUtc);
                doc = this.Session.GetObject(docPWC.CheckIn(true, properties, null, string.Empty)) as IDocument;

                // Refresh is required, or DotCMIS will use cached one only
                doc.Refresh();

                transmission.Status = TransmissionStatus.FINISHED;
                return hash;
            }
        }
Example #16
0
File: Helper.cs Project: shana/moon
		static byte [] HashStream (Stream stream, int length)
		{
			stream.Position = 0;
			byte [] buffer = new byte [BlockSize];
			using (SHA1Managed digest = new SHA1Managed ()) {
				while (length > 0) {
					int len = stream.Read (buffer, 0, System.Math.Min (length, BlockSize));
					if (len == length)
						digest.TransformFinalBlock (buffer, 0, len);
					else
						digest.TransformBlock (buffer, 0, len, null, 0);
					length -= len;
				}
				return digest.Hash;
			}
		}
        public void PrepareResumeWithLongerLocalStream() {
            byte[] localContent = new byte[this.successfulLength];
            using (RandomNumberGenerator random = RandomNumberGenerator.Create()) {
                random.GetBytes(localContent);
            }

            byte[] localHash = new SHA1Managed().ComputeHash(localContent);

            using (MemoryStream stream = new MemoryStream())
            using (HashAlgorithm hashAlg = new SHA1Managed()) {
                stream.Write(localContent, 0, (int)this.successfulLength);
                stream.Write(localContent, 0, (int)this.successfulLength);
                stream.Seek(0, SeekOrigin.Begin);
                ContentTaskUtils.PrepareResume(this.successfulLength, stream, hashAlg);
                hashAlg.TransformFinalBlock(new byte[0], 0, 0);
                Assert.AreEqual(localHash, hashAlg.Hash);
            }
        }
        public void PrepareResumeWithExactFittingStream() {
            byte[] localContent = new byte[this.successfulLength];
            using (RandomNumberGenerator random = RandomNumberGenerator.Create()) {
                random.GetBytes(localContent);
            }

            byte[] localHash = new SHA1Managed().ComputeHash(localContent);

            using (MemoryStream stream = new MemoryStream(localContent))
            using (HashAlgorithm hashAlg = new SHA1Managed()) {
                ContentTaskUtils.PrepareResume(this.successfulLength, stream, hashAlg);
                hashAlg.TransformFinalBlock(new byte[0], 0, 0);
                Assert.AreEqual(localHash, hashAlg.Hash);
            }
        }
 public void PrepareResumeDoesNotChangeHashOnZeroLengthInputStream() {
     byte[] localContent = new byte[0];
     byte[] localHash = new SHA1Managed().ComputeHash(localContent);
     using (MemoryStream stream = new MemoryStream(localContent))
     using (HashAlgorithm hashAlg = new SHA1Managed()) {
         ContentTaskUtils.PrepareResume(0, stream, hashAlg);
         hashAlg.TransformFinalBlock(new byte[0], 0, 0);
         Assert.AreEqual(localHash, hashAlg.Hash);
     }
 }
Example #20
0
        public bool IsReconnectProofValid(PacketIn packet, AuthenticationInfo authInfo)
        {
            //md5 hash of account name and secure random
            byte[] md5Hash = packet.ReadBytes(16);

            //byte[20] sha1 hash of accountname, md5 from above, reconnectProof, byte[40] sessionkey
            byte[] shaHash1 = packet.ReadBytes(20);
            //byte[20] sha1 hash of md5 from above and byte[20] (all zero)
            byte[] shaHash2 = packet.ReadBytes(20);

            byte[] username = Encoding.ASCII.GetBytes(m_srp.Username);

            var sha = new SHA1Managed();
            sha.TransformBlock(username, 0, username.Length, username, 0);
            sha.TransformBlock(md5Hash, 0, md5Hash.Length, md5Hash, 0);
            sha.TransformBlock(ReconnectProof, 0, ReconnectProof.Length, ReconnectProof, 0);
            sha.TransformBlock(authInfo.SessionKey, 0, authInfo.SessionKey.Length, authInfo.SessionKey, 0);
            byte[] hash = sha.TransformFinalBlock(new byte[0], 0, 0);

            for (int i = 0; i < 20; i++)
            {
                if (shaHash1[i] != hash[i])
                    return false;
            }
            return true;
        }
        // Compute hash bit by bit to avoid over using resources #49
        // http://blog.cincura.net/233439-computehashasync-for-sha1/

        public static async Task<string> ComputeHashAsync(Stream inputStream)
        {
            const int BufferSize = 4096;
            SHA1Managed sha1 = new SHA1Managed();

            var buffer = new byte[BufferSize];
            var streamLength = inputStream.Length;

            while (true)
            {
                var read = await inputStream.ReadAsync(buffer, 0, BufferSize).ConfigureAwait(false);
                if (inputStream.Position == streamLength)
                {
                    sha1.TransformFinalBlock(buffer, 0, read);
                    break;
                }
                sha1.TransformBlock(buffer, 0, read, default(byte[]), default(int));
            }
            return BitConverter.ToString(sha1.Hash).Replace("-", string.Empty);
        }