Example #1
0
        static byte[] Compute_NTLMv2(Type2Message type2, string username, string password)
        {
            var ntlm_hash = Compute_NTLM_Password(password);

            var ubytes = Encoding.Unicode.GetBytes(username.ToUpperInvariant());
            var tbytes = Encoding.Unicode.GetBytes(type2.TargetName.ToUpperInvariant());

            var bytes = new byte [ubytes.Length + tbytes.Length];

            ubytes.CopyTo(bytes, 0);
            Array.Copy(tbytes, 0, bytes, ubytes.Length, tbytes.Length);

            var md5          = new HMACMD5(ntlm_hash);
            var ntlm_v2_hash = md5.ComputeHash(bytes);

            Array.Clear(ntlm_hash, 0, ntlm_hash.Length);
            md5.Clear();

            var ntlm_v2_md5 = new HMACMD5(ntlm_v2_hash);

            var now       = DateTime.Now;
            var timestamp = now.Ticks - 504911232000000000;

            var nonce = new byte [8];
            var rng   = RandomNumberGenerator.Create();

            rng.GetBytes(nonce);

            byte[] blob = new byte [28 + type2.TargetInfo.Length];
            blob[0] = 0x01;
            blob[1] = 0x01;

            Buffer.BlockCopy(BitConverterLE.GetBytes(timestamp), 0, blob, 8, 8);

            Buffer.BlockCopy(nonce, 0, blob, 16, 8);
            Buffer.BlockCopy(type2.TargetInfo, 0, blob, 28, type2.TargetInfo.Length);

            var challenge = type2.Nonce;

            var hashInput = new byte [challenge.Length + blob.Length];

            challenge.CopyTo(hashInput, 0);
            blob.CopyTo(hashInput, challenge.Length);

            var blobHash = ntlm_v2_md5.ComputeHash(hashInput);

            var response = new byte [blob.Length + blobHash.Length];

            blobHash.CopyTo(response, 0);
            blob.CopyTo(response, blobHash.Length);

            Array.Clear(ntlm_v2_hash, 0, ntlm_v2_hash.Length);
            ntlm_v2_md5.Clear();
            Array.Clear(nonce, 0, nonce.Length);
            Array.Clear(blob, 0, blob.Length);
            Array.Clear(hashInput, 0, hashInput.Length);
            Array.Clear(blobHash, 0, blobHash.Length);

            return(response);
        }
Example #2
0
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="data">The scope data.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <param name="length">The length bytes.</param>
        /// <returns></returns>
        public OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData data, IPrivacyProvider privacy, byte[] length)
        {
            if (header == null)
            {
                throw new ArgumentNullException(nameof(header));
            }

            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (privacy == null)
            {
                throw new ArgumentNullException(nameof(privacy));
            }

            var key = PasswordToKey(_password, parameters.EngineId.GetRaw());

            using (var md5 = new HMACMD5(key))
            {
                var hash = md5.ComputeHash(ByteTool.PackMessage(length, version, header, parameters, data).ToBytes());
#if NET452
                md5.Clear();
#endif
                var result = new byte[DigestLength];
                Buffer.BlockCopy(hash, 0, result, 0, result.Length);
                return(new OctetString(result));
            }
        }
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="data">The scope data.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <returns></returns>
        public OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData data, IPrivacyProvider privacy)
        {
            if (header == null)
            {
                throw new ArgumentNullException("header");
            }

            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (privacy == null)
            {
                throw new ArgumentNullException("privacy");
            }

            byte[] key = PasswordToKey(_password, parameters.EngineId.GetRaw());
            using (HMACMD5 md5 = new HMACMD5(key))
            {
                byte[] hash = md5.ComputeHash(SnmpMessageExtension.PackMessage(version, header, parameters, data).ToBytes());
                md5.Clear();
                byte[] result = new byte[DigestLength];
                Buffer.BlockCopy(hash, 0, result, 0, result.Length);
                return(new OctetString(result));
            }
        }
Example #4
0
        public static string ComputeHMACHashByAlgorithm(string key, string plainText, string saltText = "", HashAlgorithms algorithm = HashAlgorithms.SHA1, Encoding encoding = null,
                                                        bool useBase64String = false)
        {
            try
            {
                if (string.IsNullOrEmpty(plainText))
                {
                    return(plainText);
                }
                if (string.IsNullOrEmpty(key))
                {
                    key = Utility.GenerateRandomPassword(8);
                }
                if (encoding == null)
                {
                    encoding = Encoding.ASCII;
                }
                var           secretKeyBytes = encoding.GetBytes(key);
                HashAlgorithm hashProvider   = null;
                switch (algorithm)
                {
                default:
                case HashAlgorithms.SHA1:
                    hashProvider = new HMACSHA1(secretKeyBytes);
                    break;

                case HashAlgorithms.SHA256:
                    hashProvider = new HMACSHA256(secretKeyBytes);
                    break;

                case HashAlgorithms.SHA384:
                    hashProvider = new HMACSHA384(secretKeyBytes);
                    break;

                case HashAlgorithms.SHA512:
                    hashProvider = new HMACSHA512(secretKeyBytes);
                    break;

                case HashAlgorithms.MD5:
                    hashProvider = new HMACMD5(secretKeyBytes);
                    break;
                }

                var dataText    = plainText + saltText;
                var dataBytes   = encoding.GetBytes(dataText);
                var hashedBytes = hashProvider.ComputeHash(dataBytes);
                hashProvider.Clear();
                if (useBase64String)
                {
                    return(Convert.ToBase64String(hashedBytes));
                }
                return(string.Concat(Array.ConvertAll(hashedBytes, x => x.ToString("x2"))));
            }
            catch
            {
                return(plainText);
            }
        }
Example #5
0
        public static string HMACMD5(string sourceText, string key)
        {
            var keyByte     = Encoding.UTF8.GetBytes(key);
            var sourceBytes = Encoding.UTF8.GetBytes(sourceText);

            using (var hmacMd5 = new HMACMD5(keyByte))
            {
                var bytes = hmacMd5.ComputeHash(sourceBytes);
                hmacMd5.Clear();
                return(BitConverter.ToString(bytes).Replace("-", "").ToLower());
            }
        }
Example #6
0
        /// <summary>
        /// Computes a keyed hash for a source file, creates a target file with the keyed hash
        /// prepended to the contents of the source file, then decrypts the file and compares
        /// the source and the decrypted files.
        /// </summary>
        /// <param name="key">The key to use to encode the file</param>
        /// <param name="sourceFile">The file to encrypt complete path</param>
        /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param>
        public void EncodeFile(string key, String sourceFile, String destFile)
        {
            if (sourceFile.IsNullOrWhiteSpace() || !File.Exists(sourceFile))
            {
                throw new FileNotFoundException("Cannot find the specified source file", sourceFile ?? "null");
            }

            if (destFile.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("Please specify the path of the output path", nameof(destFile));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Please specify the key", nameof(key));
            }

            // Create a key using a random number generator. This would be the
            //  secret key shared by sender and receiver.
            byte[] secretkey = key.ToByteArray();

            // Initialize the keyed hash object.
            HMACMD5    myhmacMD5 = new HMACMD5(secretkey);
            FileStream inStream  = new FileStream(sourceFile, FileMode.Open);
            FileStream outStream = new FileStream(destFile, FileMode.Create);

            // Compute the hash of the input file.
            byte[] hashValue = myhmacMD5.ComputeHash(inStream);
            // Reset inStream to the beginning of the file.
            inStream.Position = 0;
            // Write the computed hash value to the output file.
            outStream.Write(hashValue, 0, hashValue.Length);
            // Copy the contents of the sourceFile to the destFile.
            int bytesRead;

            // read 1K at a time
            byte[] buffer = new byte[1024];
            do
            {
                // Read from the wrapping CryptoStream.
                bytesRead = inStream.Read(buffer, 0, 1024);
                outStream.Write(buffer, 0, bytesRead);
            } while (bytesRead > 0);
            myhmacMD5.Clear();
            // Close the streams
            inStream.Close();
            outStream.Close();
        } // end EncodeFile
Example #7
0
        string HmacMD5(string source, string key)
        {
            HMACMD5 hmacmd = new HMACMD5(Encoding.Default.GetBytes(key));

            byte[]        inArray = hmacmd.ComputeHash(Encoding.Default.GetBytes(source));
            StringBuilder sb      = new StringBuilder();

            for (int i = 0; i < inArray.Length; i++)
            {
                sb.Append(inArray[i].ToString("X2"));
            }

            hmacmd.Clear();

            return(sb.ToString().ToLower());
        }
Example #8
0
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <param name="version">The version.</param>
        /// <param name="header">The header.</param>
        /// <param name="parameters">The parameters.</param>
        /// <param name="scopeBytes">The scope bytes.</param>
        /// <param name="privacy">The privacy provider.</param>
        /// <returns></returns>
        private OctetString ComputeHash(VersionCode version, ISegment header, SecurityParameters parameters, ISnmpData scopeBytes, IPrivacyProvider privacy)
        {
            if (scopeBytes == null)
            {
                throw new ArgumentNullException("scopeBytes");
            }

            byte[] key = PasswordToKey(_password, parameters.EngineId.GetRaw());
#if !SILVERLIGHT   //mc++
            using (HMACMD5 md5 = new HMACMD5(key))
            {
                byte[] hash = md5.ComputeHash(SnmpMessageExtension.PackMessage(version, header, parameters, scopeBytes, privacy).ToBytes());
                md5.Clear();
                byte[] result = new byte[DigestLength];
                Array.Copy(hash, result, result.Length);
                return(new OctetString(result));
            }
#endif
            return(null);
        }
Example #9
0
        } //compute hash from arguments and return hash value as string

        private static string GetHMACMD5Hash(string text)
        {
            //create variables for computing hash and making it a string
            UnicodeEncoding UniCode = new UnicodeEncoding();

            byte[]  HashResult;
            byte[]  msg        = UniCode.GetBytes(text);
            HMACMD5 hashString = new HMACMD5();
            string  Str        = "";

            //compute hash with HMACMD5 module and format output as string
            //convert bytes in HashResult to string values
            HashResult = hashString.ComputeHash(msg);
            foreach (byte x in HashResult)
            {
                Str += String.Format("{0:x2}", x);
            }

            //clear excess resource usage
            hashString.Clear();
            return(Str);
        } //compute hash from arguments and return hash value as string
        /// <summary>
        /// Computes the hash.
        /// </summary>
        /// <returns></returns>
        public OctetString ComputeHash(byte[] buffer, OctetString engineId)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (engineId == null)
            {
                throw new ArgumentNullException("engineId");
            }

            var key = PasswordToKey(_password, engineId.GetRaw());

            using (var md5 = new HMACMD5(key))
            {
                var hash = md5.ComputeHash(buffer);
                md5.Clear();
                var result = new byte[DigestLength];
                Buffer.BlockCopy(hash, 0, result, 0, result.Length);
                return(new OctetString(result));
            }
        }