Exemple #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["x_amount"] == null)
        {
            Response.Redirect("Donate_form.aspx");

        }
        else
        {

            StringBuilder sb = new StringBuilder();
            // x_login^x_fp_sequence^x_fp_timestamp^x_amount^x_currency
            x_login.Value = "WSP-VENTU-58IQZwAhPQ";//x_login
            Random random = new Random();
            x_fp_sequence.Value = (random.Next(0, 1000)).ToString();
            x_test_request.Value = "true";
            x_show_form.Value = "PAYMENT_FORM";
            TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));

            int timestamp = (int)t.TotalSeconds;
            x_fp_timestamp.Value = timestamp.ToString();

            x_amount.Value = (string)Session["x_amount"];

            //String x_currency = "USD"; // default empty

            sb.Append(x_login.Value)
                .Append("^")
                .Append(x_fp_sequence.Value)
                .Append("^")
                .Append(x_fp_timestamp.Value)
                .Append("^")
                .Append(x_amount.Value)
                .Append("^")
                .Append("");

            // Convert string to array of bytes.
            byte[] data = Encoding.UTF8.GetBytes(sb.ToString());

            // key
            byte[] key = Encoding.UTF8.GetBytes("F1pnOOMHVFRaBe_0gMwl");//transaction_key

            // Create HMAC-SHA1 Algorithm;
            HMACMD5 hmac = new HMACMD5(key);

            // Create HMAC-SHA1 Algorithm;
            // HMACSHA1 hmac = new HMACSHA1(key);

            // Compute hash.
            byte[] hashBytes = hmac.ComputeHash(data);

            // Convert to HEX string.
            x_fp_hash.Value = System.BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
            Session["x_amount"] = null;
        }
    }
Exemple #2
0
    public static bool authenticateUser(string userName, string passWord)
    {
        Users kayttajat = new Users();

        Serialisointi.deSerialisoiKayttajat(HttpContext.Current.Server.MapPath("~/App_Data/Kayttajat.xml"), ref kayttajat);

        byte[] saltBytes = new byte[] { 12, 254, 62, 6, 7, 42, 2, 96 };
        byte[] saltedHashBytesUserName = new HMACMD5(saltBytes).ComputeHash(Encoding.UTF8.GetBytes(userName));
        byte[] saltedHashBytesPassword = new HMACMD5(saltBytes).ComputeHash(Encoding.UTF8.GetBytes(passWord));

        string saltedHashStringUserName = Convert.ToBase64String(saltedHashBytesUserName);
        string saltedHashStringPassword = Convert.ToBase64String(saltedHashBytesPassword);

        for (int i = 0; i < kayttajat.kayttajat.Count; i++)
        {
            if (saltedHashStringUserName == kayttajat.kayttajat[i].UserName && saltedHashStringPassword == kayttajat.kayttajat[i].Password)
            {
                return true;
            }
        }
        return false;
    }
    public static bool authenticateUser(string userName, string passWord)
    {
        string path = ConfigurationManager.AppSettings["path_teht3_kayttajat"];

        Kayttajat kayttajat = new Kayttajat();

        BLteht3.DeSerialisoiKayttajat(path, ref kayttajat);

        byte[] saltBytes = new byte[] { 12, 254, 62, 6, 7, 42, 2, 96 };
        byte[] saltedHashBytesUserName = new HMACMD5(saltBytes).ComputeHash(Encoding.UTF8.GetBytes(userName));
        byte[] saltedHashBytesPassword = new HMACMD5(saltBytes).ComputeHash(Encoding.UTF8.GetBytes(passWord));

        string saltedHashStringUserName = Convert.ToBase64String(saltedHashBytesUserName);
        string saltedHashStringPassword = Convert.ToBase64String(saltedHashBytesPassword);

        for (int i = 0; i < kayttajat.User.Count; i++)
        {
            if (saltedHashStringUserName == kayttajat.User[i].UserName && saltedHashStringPassword == kayttajat.User[i].Password)
            {
                return true;
            }
        }
        return false;
    }
Exemple #4
0
        public static byte[] MakeHMAC(byte[] key, byte[] data)
        {
            HMACMD5 hmac = new HMACMD5(key);

            return(hmac.ComputeHash(data));
        }
Exemple #5
0
        /// <summary>
        /// 获取Hash后的字节数组
        /// </summary>
        /// <param name="type">哈希类型</param>
        /// <param name="key">key</param>
        /// <param name="bytes">原字节数组</param>
        /// <returns></returns>
        public static byte[] GetHashedBytes(HashType type, byte[] bytes, byte[] key)
        {
            if (null == bytes)
            {
                return(bytes);
            }

            HashAlgorithm algorithm = null;

            try
            {
                if (key == null)
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = MD5.Create();
                        break;

                    case HashType.SHA1:
                        algorithm = SHA1.Create();
                        break;

                    case HashType.SHA256:
                        algorithm = SHA256.Create();
                        break;

                    case HashType.SHA384:
                        algorithm = SHA384.Create();
                        break;

                    case HashType.SHA512:
                        algorithm = SHA512.Create();
                        break;

                    default:
                        algorithm = MD5.Create();
                        break;
                    }
                }
                else
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = new HMACMD5(key);
                        break;

                    case HashType.SHA1:
                        algorithm = new HMACSHA1(key);
                        break;

                    case HashType.SHA256:
                        algorithm = new HMACSHA256(key);
                        break;

                    case HashType.SHA384:
                        algorithm = new HMACSHA384(key);
                        break;

                    case HashType.SHA512:
                        algorithm = new HMACSHA512(key);
                        break;

                    default:
                        algorithm = new HMACMD5(key);
                        break;
                    }
                }
                return(algorithm.ComputeHash(bytes));
            }
            finally
            {
                algorithm?.Dispose();
            }
        }
Exemple #6
0
 public void SetHash(byte[] login, byte[] hash)
 {
     LoginMD5 = new HMACMD5(login);
     Hash     = hash;
 }
Exemple #7
0
        internal override void OnLogin(string login, string password)
        {
            string command = String.Empty;
            string result  = String.Empty;
            string tag     = GetTag();
            string key;

            switch (AuthMethod)
            {
            case AuthMethods.CRAMMD5:
                command = tag + "AUTHENTICATE CRAM-MD5";
                result  = SendCommandGetResponse(command);
                // retrieve server key
                key = result.Replace("+ ", "");
                key = System.Text.Encoding.Default.GetString(Convert.FromBase64String(key));
                // calcul hash
                using (var kMd5 = new HMACMD5(System.Text.Encoding.ASCII.GetBytes(password)))
                {
                    byte[] hash1 = kMd5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(key));
                    key    = BitConverter.ToString(hash1).ToLower().Replace("-", "");
                    result = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(login + " " + key));
                    result = SendCommandGetResponse(result);
                }
                break;

            case AuthMethods.Login:
                command = tag + "LOGIN " + login.QuoteString() + " " + password.QuoteString();
                result  = SendCommandGetResponse(command);
                break;

            case AuthMethods.SaslOAuth:
                string sasl   = "user="******"\x01" + "auth=Bearer " + password + "\x01" + "\x01";
                string base64 = Convert.ToBase64String(Encoding.GetBytes(sasl));
                command = tag + "AUTHENTICATE XOAUTH2 " + base64;
                result  = SendCommandGetResponse(command);
                break;

            default:
                throw new NotSupportedException();
            }

            if (!result.StartsWith(tag + "OK"))
            {
                if (result.StartsWith("+ ") && result.EndsWith("=="))
                {
                    string jsonErr = Utilities.DecodeBase64(result.Substring(2), System.Text.Encoding.UTF7);
                    throw new Exception(jsonErr);
                }
                else
                {
                    throw new Exception(result);
                }
            }

            //if (Supports("COMPRESS=DEFLATE")) {
            //  SendCommandCheckOK(GetTag() + "compress deflate");
            //  _Stream0 = _Stream;
            // // _Reader = new System.IO.StreamReader(new System.IO.Compression.DeflateStream(_Stream0, System.IO.Compression.CompressionMode.Decompress, true), System.Text.Encoding.Default);
            // // _Stream = new System.IO.Compression.DeflateStream(_Stream0, System.IO.Compression.CompressionMode.Compress, true);
            //}

            if (Supports("X-GM-EXT-1"))
            {
                _FetchHeaders = "X-GM-MSGID X-GM-THRID X-GM-LABELS ";
            }
        }
Exemple #8
0
        internal static Tuple <string, int, int> GetTotpCode(string url)
        {
            var uri = new Uri(url);

            if (uri.Scheme != "otpauth")
            {
                return(null);
            }

            string secret    = null;
            var    algorithm = "SHA1";
            var    digits    = 6;
            var    period    = 30;
            var    coll      = HttpUtility.ParseQueryString(uri.Query);

            foreach (var key in coll.AllKeys)
            {
                switch (key)
                {
                case "secret":
                    secret = coll[key];
                    break;

                case "algorithm":
                    algorithm = coll[key];
                    break;

                case "digits":
                    int.TryParse(coll[key], out digits);
                    break;

                case "period":
                    int.TryParse(coll[key], out period);
                    break;
                }
            }

            if (string.IsNullOrEmpty(secret))
            {
                return(null);
            }

            var tmBase = DateTimeOffset.Now.ToUnixTimeMilliseconds() / 1000;
            var tm     = tmBase / period;
            var msg    = BitConverter.GetBytes(tm);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(msg);
            }

            var secretBytes = Base32ToBytes(secret.ToUpperInvariant());

            HMAC hmac = null;

            switch (algorithm)
            {
            case "SHA1":
                hmac = new HMACSHA1(secretBytes);
                break;

            case "SHA256":
                hmac = new HMACSHA256(secretBytes);
                break;

            case "MD5":
                hmac = new HMACMD5(secretBytes);
                break;
            }

            if (hmac == null)
            {
                return(null);
            }

            var digest    = hmac.ComputeHash(msg);
            var offset    = digest[digest.Length - 1] & 0x0f;
            var codeBytes = new byte[4];

            Array.Copy(digest, offset, codeBytes, 0, codeBytes.Length);
            codeBytes[0] &= 0x7f;
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(codeBytes);
            }

            var codeInt = BitConverter.ToInt32(codeBytes, 0);

            codeInt %= Enumerable.Repeat(10, digits).Aggregate(1, (a, b) => a * b);
            var codeStr = codeInt.ToString();

            while (codeStr.Length < digits)
            {
                codeStr = "0" + codeStr;
            }

            return(Tuple.Create(codeStr, (int)(tmBase % period), period));
        }
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="byteData">
        /// Plaintext value to be hashed.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", "SHA512", "HMACMD5", "HMACSHA1", "HMACSHA256",
        ///  "HMACSHA512" (if any other value is specified  MD5 will be used).
        ///
        /// HMAC algorithms uses Hash-based Message Authentication Code.
        /// The HMAC process mixes a secret key with the message data, hashes
        /// the result with the hash function, mixes that hash value with
        /// the secret key again, and then applies the hash function
        /// a second time. HMAC hashes are fixed lenght and generally
        /// much longer than non-HMAC hashes of the same type.
        ///
        /// https://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha256(v=vs.110).aspx
        ///
        /// This value is case-insensitive.
        /// </param>
        /// <param name="saltBytes">
        /// Optional but recommended salt bytes to apply to the hash. If not passed the
        /// raw encoding is used. If salt is nullthe raw algorithm is used (useful for
        /// file hashes etc.) HMAC versions REQUIRE that salt is passed.
        /// </param>
        /// <param name="useBinHex">if true returns the data as BinHex byte pair string. Otherwise Base64 is returned.</param>
        /// <returns>
        /// Hash value formatted as a base64-encoded or BinHex stringstring.
        /// </returns>
        public static string ComputeHash(byte[] byteData,
                                         string hashAlgorithm,
                                         byte[] saltBytes,
                                         bool useBinHex = false)
        {
            if (byteData == null)
            {
                return(null);
            }

            // Convert plain text into a byte array.
            byte[] plainTextWithSaltBytes;

            if (saltBytes != null)
            {
                // Allocate array, which will hold plain text and salt.
                plainTextWithSaltBytes =
                    new byte[byteData.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < byteData.Length; i++)
                {
                    plainTextWithSaltBytes[i] = byteData[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[byteData.Length + i] = saltBytes[i];
                }
            }
            else
            {
                plainTextWithSaltBytes = byteData;
            }

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            case "HMACMD5":
                hash = new HMACMD5(saltBytes);
                break;

            case "HMACSHA1":
                hash = new HMACSHA1(saltBytes);
                break;

            case "HMACSHA256":
                hash = new HMACSHA256(saltBytes);
                break;

            case "HMACSHA512":
                hash = new HMACSHA512(saltBytes);
                break;

            default:
                // default to MD5
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);


            hash.Dispose();

            if (useBinHex)
            {
                return(BinaryToBinHex(hashBytes));
            }

            return(Convert.ToBase64String(hashBytes));
        }
Exemple #10
0
        static void Main(string[] args)
        {
            con("MachineKey Generator v0.1 for ASP.NET / xsiteman WebForms Application");
            con("");

            string _decKeyMode = "AES";
            string _hashMode   = "HMACSHA512";

            if (args.Length != 0)
            {
                if ((args.Length != 2) || (args[0] == "-h") || (args[0] == "--help"))
                {
                    error(-1);
                }

                if ((args[0] != "AES") && (args[0] != "DES") && (args[0] != "3DES"))
                {
                    error(1);
                }
                if ((args[1] != "MD5") && (args[1] != "SHA1") && (args[1] != "HMACSHA256") && (args[1] != "HMACSHA384") && (args[1] != "HMACSHA512"))
                {
                    error(2);
                }

                _decKeyMode = args[0];
                _hashMode   = args[1];

                con("FOUND OPTIONS: " + args[0] + ", " + args[1]);
            }
            else
            {
                con("USING DEFAULTS: AES + HMACSHA512");
            }

            con("");

            string _decKey;
            string _hashKey;

            switch (_decKeyMode)
            {
            case "3DES":
                TripleDESCryptoServiceProvider _3DES = new TripleDESCryptoServiceProvider();
                _3DES.GenerateKey();
                _decKey = BinToHexStr(_3DES.Key);
                _3DES.Dispose();
                break;

            case "DES":
                DESCryptoServiceProvider _DES = new DESCryptoServiceProvider();
                _DES.GenerateKey();
                _decKey = BinToHexStr(_DES.Key);
                _DES.Dispose();
                break;

            default:
                AesCryptoServiceProvider _AES = new AesCryptoServiceProvider();
                _AES.GenerateKey();
                _decKey = BinToHexStr(_AES.Key);
                _AES.Dispose();
                break;
            }

            switch (_hashMode)
            {
            case "MD5":
                HMACMD5 _MD5 = new HMACMD5();
                _hashKey = BinToHexStr(_MD5.Key);
                _MD5.Dispose();
                break;

            case "SHA1":
                HMACSHA1 _SHA1 = new HMACSHA1();
                _hashKey = BinToHexStr(_SHA1.Key);
                _SHA1.Dispose();
                break;

            case "SHA256":
                HMACSHA256 _SHA256 = new HMACSHA256();
                _hashKey = BinToHexStr(_SHA256.Key);
                _SHA256.Dispose();
                break;

            case "SHA384":
                HMACSHA384 _SHA384 = new HMACSHA384();
                _hashKey = BinToHexStr(_SHA384.Key);
                _SHA384.Dispose();
                break;

            default:
                HMACSHA512 _SHA512 = new HMACSHA512();
                _hashKey = BinToHexStr(_SHA512.Key);
                _SHA512.Dispose();
                break;
            }


            string _mkstring = string.Concat("<machineKey decryption=\"", _decKeyMode, "\" decryptionKey=\"", _decKey, "\" validation=\"", _hashMode, "\" validationKey=\"", _hashKey, "\" />");

            con(_mkstring);
        }
Exemple #11
0
 protected override byte[] HashDataOneShot(byte[] key, byte[] source) =>
 HMACMD5.HashData(key, source);
Exemple #12
0
        ////////////////////////////////////////////////////////////////////////////////
        //
        ////////////////////////////////////////////////////////////////////////////////
        internal Boolean Authenticate(String domain, String username, String hash)
        {
            String NTLMSSP = BitConverter.ToString(recieve).Replace("-", "");
            Int32  index   = NTLMSSP.IndexOf("4E544C4D53535000") / 2;

            UInt16 wDomain = BitConverter.ToUInt16(recieve.Skip(index + 12).Take(2).ToArray(), 0);
            UInt16 wtarget = BitConverter.ToUInt16(recieve.Skip(index + 40).Take(2).ToArray(), 0);

            sessionId = recieve.Skip(44).Take(8).ToArray();
            Byte[] bServerChallenge = recieve.Skip(index + 24).Take(8).ToArray();
            Int32  start            = index + 56 + wDomain;
            Int32  end = index + 55 + wDomain + wtarget;

            Byte[] details = recieve.Skip(start).Take(end - start + 1).ToArray();
            Byte[] bTime   = details.Skip(details.Length - 12).Take(8).ToArray();

            Int32 j = 0;

            Byte[] bHash = new Byte[hash.Length / 2];
            for (Int32 i = 0; i < hash.Length; i += 2)
            {
                bHash[j++] = (Byte)((Char)Convert.ToInt16(hash.Substring(i, 2), 16));
            }

            Byte[] bHostname      = Encoding.Unicode.GetBytes(Environment.MachineName);
            Byte[] hostnameLength = BitConverter.GetBytes(bHostname.Length).Take(2).ToArray();

            Byte[] bDomain      = Encoding.Unicode.GetBytes(domain);
            Byte[] domainLength = BitConverter.GetBytes(bDomain.Length).Take(2).ToArray();

            Byte[] bUsername      = Encoding.Unicode.GetBytes(username);
            Byte[] usernameLength = BitConverter.GetBytes(bUsername.Length).Take(2).ToArray();

            Byte[] domainOffset   = { 0x40, 0x00, 0x00, 0x00 };
            Byte[] usernameOffset = BitConverter.GetBytes(bDomain.Length + 64);
            Byte[] hostnameOffset = BitConverter.GetBytes(bDomain.Length + bUsername.Length + 64);
            Byte[] lmOffset       = BitConverter.GetBytes(bDomain.Length + bUsername.Length + bHostname.Length + 64);
            Byte[] ntOffset       = BitConverter.GetBytes(bDomain.Length + bUsername.Length + bHostname.Length + 88);

            String usernameTarget = username.ToUpper();

            Byte[] bUsernameTarget = Encoding.Unicode.GetBytes(usernameTarget);
            bUsernameTarget = Combine.combine(bUsernameTarget, bDomain);

            Byte[] NetNTLMv2Hash;
            using (HMACMD5 hmac = new HMACMD5())
            {
                hmac.Key      = bHash;
                NetNTLMv2Hash = hmac.ComputeHash(bUsernameTarget);
            }

            Byte[] bClientChallenge = new Byte[8];
            Random random           = new Random();

            for (Int32 i = 0; i < 8; i++)
            {
                bClientChallenge[i] = (Byte)random.Next(0, 255);
            }

            Byte[] blob = Combine.combine(new Byte[] { 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, bTime);
            blob = Combine.combine(blob, bClientChallenge);
            blob = Combine.combine(blob, new Byte[] { 0x00, 0x00, 0x00, 0x00 });
            blob = Combine.combine(blob, details);
            blob = Combine.combine(blob, new Byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });

            Byte[] bServerChallengeAndBlob = Combine.combine(bServerChallenge, blob);
            Byte[] NetNTLMv2Response;
            using (HMACMD5 hmacMD5 = new HMACMD5())
            {
                hmacMD5.Key       = NetNTLMv2Hash;
                NetNTLMv2Response = hmacMD5.ComputeHash(bServerChallengeAndBlob);
            }

            if (signing)
            {
                using (HMACMD5 hmacMD5 = new HMACMD5())
                {
                    hmacMD5.Key = NetNTLMv2Hash;
                    sessionKey  = hmacMD5.ComputeHash(NetNTLMv2Response);
                }
            }

            NetNTLMv2Response = Combine.combine(NetNTLMv2Response, blob);
            Byte[] NetNTLMv2ResponseLength = BitConverter.GetBytes(NetNTLMv2Response.Length).Take(2).ToArray();

            Byte[] sessionKeyOffset = BitConverter.GetBytes(bDomain.Length + bUsername.Length + bHostname.Length + NetNTLMv2Response.Length + 88);

            Byte[] NetNTLMSSPResponse = { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x03, 0x00, 0x00, 0x00 };
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, new Byte[] { 0x18, 0x00 });
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, new Byte[] { 0x18, 0x00 });
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, lmOffset);

            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, NetNTLMv2ResponseLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, NetNTLMv2ResponseLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, ntOffset);

            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, domainLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, domainLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, domainOffset);

            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, usernameLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, usernameLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, usernameOffset);

            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, hostnameLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, hostnameLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, hostnameOffset);

            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, sessionKeyLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, sessionKeyLength);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, sessionKeyOffset);

            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, flags);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, bDomain);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, bUsername);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, bHostname);
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, new Byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 });
            NetNTLMSSPResponse = Combine.combine(NetNTLMSSPResponse, NetNTLMv2Response);

            SMB2Header header = new SMB2Header();

            header.SetCommand(new Byte[] { 0x01, 0x00 });
            header.SetCreditsRequested(new Byte[] { 0x1f, 0x00 });
            header.SetMessageID(++messageId);
            header.SetProcessID(processId);
            header.SetTreeId(treeId);
            header.SetSessionID(sessionId);
            Byte[] bHeader = header.GetHeader();

            NTLMSSPAuth ntlmSSPAuth = new NTLMSSPAuth();

            ntlmSSPAuth.SetNetNTLMResponse(NetNTLMSSPResponse);
            Byte[] bNTLMSSPAuth = ntlmSSPAuth.GetNTLMSSPAuth();

            SMB2SessionSetupRequest sessionSetup = new SMB2SessionSetupRequest();

            sessionSetup.SetSecurityBlob(bNTLMSSPAuth);
            Byte[] bData = sessionSetup.GetSMB2SessionSetupRequest();

            NetBIOSSessionService sessionService = new NetBIOSSessionService();

            sessionService.SetHeaderLength(bHeader.Length);
            sessionService.SetDataLength(bData.Length);
            Byte[] bSessionService = sessionService.GetNetBIOSSessionService();

            Byte[] send = Combine.combine(Combine.combine(bSessionService, bHeader), bData);
            streamSocket.Write(send, 0, send.Length);
            streamSocket.Flush();
            streamSocket.Read(recieve, 0, recieve.Length);

            Byte[] status = recieve.Skip(12).Take(4).ToArray();
            if (status.SequenceEqual(new Byte[] { 0x00, 0x00, 0x00, 0x00 }))
            {
                Console.WriteLine("[+] {0} Login Successful to {1}", username, system);
                return(true);
            }

            Console.WriteLine("[-] {0} Login Failed to {1}", username, system);
            Console.WriteLine("[-] Status: {0}", BitConverter.ToString(status));
            return(false);
        }
Exemple #13
0
        /// <summary>
        /// Get the correct HashAlgorithm, depends if you need a key for the hash or not
        /// </summary>
        /// <param name="p_hashType">Type of Hash</param>
        /// <param name="p_key">Key to use for the Hash</param>
        /// <returns></returns>
        private static HashAlgorithm GetHashAlgorithm(HashType p_hashType, string p_key = null)
        {
            HashAlgorithm SHhash = null;

            switch (p_hashType)
            {
            case HashType.MD5:
                if (String.IsNullOrEmpty(p_key))
                {
                    SHhash = MD5.Create();
                }
                else
                {
                    SHhash = new HMACMD5(GetBytes(p_key));
                }
                break;

            case HashType.SHA1:
                if (String.IsNullOrEmpty(p_key))
                {
                    SHhash = SHA1.Create();
                }
                else
                {
                    SHhash = new HMACSHA1(GetBytes(p_key));
                }
                break;

            case HashType.SHA256:
                if (String.IsNullOrEmpty(p_key))
                {
                    SHhash = SHA256.Create();
                }
                else
                {
                    SHhash = new HMACSHA256(GetBytes(p_key));
                }
                break;

            case HashType.SHA384:
                if (String.IsNullOrEmpty(p_key))
                {
                    SHhash = SHA384.Create();
                }
                else
                {
                    SHhash = new HMACSHA384(GetBytes(p_key));
                }
                break;

            case HashType.SHA512:
                if (String.IsNullOrEmpty(p_key))
                {
                    SHhash = SHA512.Create();
                }
                else
                {
                    SHhash = new HMACSHA512(GetBytes(p_key));
                }
                break;

            default:
                throw new InvalidOperationException($"Unknown hash type \"{p_hashType}\"");
            }

            return(SHhash);
        }
        public void addElement(String s)
        {
            //word=binascii.a2b_qp(qgram) # convert to binary

            String mykey = "zuxujesw";

            byte[] keyBytes = Encoding.UTF8.GetBytes(mykey);
            String hex1     = "";
            String hex2     = "";

            try {
                HMACSHA1 mac = new HMACSHA1(keyBytes);
                mac.Initialize();
                byte[] inputBytes = new byte[s.Length];
                for (var i = 0; i < s.Length; i++)
                {
                    inputBytes.SetValue(Convert.ToByte(s[i]), i);//Encoding.UTF8.GetBytes(s);
                }
                byte[] digest = mac.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
                hex1 = BitConverter.ToString(digest).Replace("-", string.Empty);
            } catch (Exception ex) {
                Console.Error.WriteLine("HMACSHA1: Hash error: " + ex.Message);
            }
            try {
                HMACMD5 mac = new HMACMD5(keyBytes);
                mac.Initialize();
                byte[] inputBytes = Encoding.UTF8.GetBytes(s);
                byte[] digest     = mac.TransformFinalBlock(inputBytes, 0, inputBytes.Length);
                hex2 = BitConverter.ToString(digest).Replace("-", string.Empty);
            } catch (Exception ex) {
                Console.Error.WriteLine("HMACMD5: Hash error: " + ex.Message);
            }
            // convert hash key to integer
            BigInteger h1 = BigInteger.Parse(hex1, NumberStyles.AllowHexSpecifier);
            BigInteger h2 = BigInteger.Parse(hex2, NumberStyles.AllowHexSpecifier);

            for (int i = 0; i < k; i++)
            {
                BigInteger bigi = new BigInteger(i);
                //BigInteger res = h2.multiply(bigi).add(h1).mod(new BigInteger(this.bitSetSize + ""));
                BigInteger res      = (h2 * bigi + h1) % new BigInteger(this.bitSetSize);
                int        position = (int)res;
                if (!bitset.get(position))
                {
                    bitsSet++;
                }
                if (bitset.get(position))
                {
                    if (cols[position] == 0)
                    {
                        cols[position] = 1;
                    }
                    else
                    {
                        cols[position] = cols[position] + 1;
                    }
                }
                bitset.set(position);
            }
            numberOfAddedElements++;
        }
Exemple #15
0
 public SshHmacMd5()
     : base()
 {
     _algorithm = new HMACMD5();
 }
Exemple #16
0
        public static string Hmacmd5(string key, string sessionId)
        {
            var md5 = new HMACMD5(Encoding.UTF8.GetBytes(key));

            return(BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(sessionId))).Replace("-", "").ToLower());
        }
        public void Create_Incorrect()
        {
            var x = HMACMD5.Create();

            Assert.AreEqual("SHA1", x.HashName, "https://connect.microsoft.com/VisualStudio/feedback/details/838731/all-hmac-create-methods-return-an-instance-of-hmacmd5");
        }
Exemple #18
0
        public byte[] ExpandMD5(byte[] secret, byte[] seed, int length)
        {
            int hashLength = 16;
            int iterations = (int)(length / hashLength);
            if ((length % hashLength) > 0)
            {
                iterations++;
            }

            ByteBuffer resMacs = new ByteBuffer();
            byte[] bAofi = seed;

            for (int i = 1; i <= iterations; i++)
            {
                ByteBuffer hcseed = new ByteBuffer();
                HMACMD5 md51 = new HMACMD5(secret);

                byte[] bNextAofi = md51.ComputeHash(bAofi); /// A(1) = HMAC_hash(secret, A(0)),
                /// A(2) = HMAC_hash(secret, A(1)),
                /// etc

                HMACMD5 md52 = new HMACMD5(secret);
                byte[] bComputeNextHashOver = new byte[16 + seed.Length];
                Array.Copy(bNextAofi, 0, bComputeNextHashOver, 0, 16);
                Array.Copy(seed, 0, bComputeNextHashOver, 16, seed.Length);
                byte[] bTotalHashThisIteration = md52.ComputeHash(bComputeNextHashOver);
                resMacs.AppendData(bTotalHashThisIteration); /// Append it to our total buffer

                bAofi = bNextAofi; /// use next loop

            }

            byte[] res = resMacs.GetNSamples(length);

            return res;
        }
Exemple #19
0
 protected override byte[] HashDataOneShot(ReadOnlySpan <byte> key, ReadOnlySpan <byte> source) =>
 HMACMD5.HashData(key, source);
Exemple #20
0
        } // end EncodeFile

        /// <summary>
        /// Decrypt the encoded file and compare to original file. It returns false if the file is corrupted.
        /// </summary>
        /// <param name="key">The key used to encode the file</param>
        /// <param name="sourceFile">The file to decrypt complete path</param>
        /// <param name="destFile">Destination file complete path. If the file doesn't exist, it creates it</param>
        /// <returns></returns>
        public bool DecodeFile(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 hmacMD5 = new HMACMD5(secretkey);

            // Create an array to hold the keyed hash value read from the file.
            byte[] storedHash = new byte[hmacMD5.HashSize / 8];
            // Create a FileStream for the source file.
            FileStream inStream = new FileStream(sourceFile, FileMode.Open);

            // Read in the storedHash.
            inStream.Read(storedHash, 0, storedHash.Length);
            // Compute the hash of the remaining contents of the file.
            // The stream is properly positioned at the beginning of the content,
            // immediately after the stored hash value.
            byte[] computedHash = hmacMD5.ComputeHash(inStream);
            // compare the computed hash with the stored value
            int i;

            for (i = 0; i < storedHash.Length; i++)
            {
                if (computedHash[i] != storedHash[i])
                {
                    inStream.Close();
                    return(false);
                }
            }

            FileStream outStream = new FileStream(destFile, FileMode.Create);

            // Reset inStream to the beginning of the file.
            inStream.Position = i;
            // 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);
            // Close the streams
            inStream.Close();
            outStream.Close();
            return(true);
        } //end DecodeFile
Exemple #21
0
 protected override int HashDataOneShot(ReadOnlySpan <byte> key, ReadOnlySpan <byte> source, Span <byte> destination) =>
 HMACMD5.HashData(key, source, destination);
Exemple #22
0
 /// <summary>
 /// Calculates an MD5 hash signature.
 /// </summary>
 /// <param name="input">The message for which a signature will be generated</param>
 /// <param name="key">The secret key to use to sign the message</param>
 /// <returns>The HMAC signature.</returns>
 public static byte[] HMACMD5(byte[] input, byte[] key)
 {
     using HMACMD5 hmac = new HMACMD5(key);
     return(hmac.ComputeHash(input));
 }
Exemple #23
0
 protected override bool TryHashDataOneShot(ReadOnlySpan <byte> key, ReadOnlySpan <byte> source, Span <byte> destination, out int written) =>
 HMACMD5.TryHashData(key, source, destination, out written);
Exemple #24
0
        static void Main(string[] args)
        {
            //{// define the URL to send an SMS
            //const string ACCESS_KEY = "ADqezQmETQf9tjoikYYcsUnY";
            ////const string MESSAGE = "HelloWorld";
            ////const string TO_PHONE_NUMBER = "33612345678";
            //Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            // TSTAMP = unixTimestamp.ToString;
            //string URL =
            //    "https://api.boxis.net/?" +
            //    "returntype=xml&" +
            //    "sender_name=boxis.net&" +
            //    "recipients[1]=41765464985&" +
            //    "content=HelloWordl&" +
            //    "encoding=UTF-8&" +
            //    "version=1.0&" +
            //    "[email protected]&" +
            //    "timestamp="+unixTimestamp.ToString()+"&" +
            //    "authcode=" + unixTimestamp.ToString() + ACCESS_KEY+"&" +
            //    "section=sms&"+
            //    "action=sendSMS";


            //    // XmlDocument allowed to query a xml document with xpath expression
            //    XmlDocument xmldoc = new XmlDocument();
            //    xmldoc.Load(URL);
            //    Console.WriteLine("Status Message=" + xmldoc.SelectSingleNode("/response/status/status_msg").InnerText);


            //  parametres iniciaux
            //+ apiAccessKey +
            //"&to=" + phoneNumber + "&content=" + textContent;

            Int32  unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            String apiAccessKey  = "hNpArSGaXwhQ9KZTeha96fOK";
            var    auth          = Encoding.UTF8.GetBytes(unixTimestamp + apiAccessKey);
            //byte[] key = Encoding.ASCII.GetBytes(unixTimestamp + apiAccessKey);

            var md5 = new HMACMD5(auth);

            //MD5 md5 = MD5.Create();

            //byte[] inputBytes = Encoding.UTF8.GetBytes(auth);

            //var hash = md5.GetHashCode(auth);

            // step 2, convert byte array to hex string

            //StringBuilder sb = new StringBuilder();

            //for (int i = 0; i < hash.Length; i++)
            //{

            //    sb.Append(hash[i].ToString("X2"));

            //}

            //var h = hash;

            String url = "https://api.boxis.net/?" +
                         "returntype=xml&" +
                         "sender_name=boxis.net&" +
                         "recipients[1]=41765464985&" +
                         "content=HelloWordl&" +
                         "encoding=UTF-8&" +
                         "version=1.0&" +
                         "[email protected]&" +
                         "timestamp=" + unixTimestamp +
                         "&authcode=" + md5.ToString() +
                         "&section=sms&" +
                         "action=sendSMS";

            // Envoie requêt
            WebClient client = new WebClient();
            String    result = client.DownloadString(url);

            Console.WriteLine("Result : " + result);

            // Parse return XML
            XmlDocument document = new XmlDocument();

            document.LoadXml(result);
            Console.WriteLine("Status code : "
                              + document.GetElementsByTagName("status_code").ToString());
            Console.WriteLine("Status message : "
                              + document.GetElementsByTagName("status_msg").ToString());
            Console.Read();
        }
Exemple #25
0
 public static byte[] ComputeHmacMd5(byte[] key, byte[] toBeHashed)
 {
     using var hmacMd5 = new HMACMD5(key);
     return(hmacMd5.ComputeHash(toBeHashed));
 }
        public static byte[] GetAuthenticateMessage(byte[] securityBlob, string domainName, string userName, string password, AuthenticationMethod authenticationMethod, out byte[] sessionKey)
        {
            sessionKey = null;
            bool useGSSAPI = false;
            SimpleProtectedNegotiationTokenResponse inputToken = null;

            try
            {
                inputToken = SimpleProtectedNegotiationToken.ReadToken(securityBlob, 0) as SimpleProtectedNegotiationTokenResponse;
            }
            catch
            {
            }

            ChallengeMessage challengeMessage;

            if (inputToken != null)
            {
                challengeMessage = GetChallengeMessage(inputToken.ResponseToken);
                useGSSAPI        = true;
            }
            else
            {
                challengeMessage = GetChallengeMessage(securityBlob);
            }

            if (challengeMessage == null)
            {
                return(null);
            }

            DateTime time = DateTime.UtcNow;

            byte[] clientChallenge = new byte[8];
            new Random().NextBytes(clientChallenge);

            AuthenticateMessage authenticateMessage = new AuthenticateMessage();

            // https://msdn.microsoft.com/en-us/library/cc236676.aspx
            authenticateMessage.NegotiateFlags = NegotiateFlags.Sign |
                                                 NegotiateFlags.NTLMSessionSecurity |
                                                 NegotiateFlags.AlwaysSign |
                                                 NegotiateFlags.Version |
                                                 NegotiateFlags.Use128BitEncryption |
                                                 NegotiateFlags.Use56BitEncryption;
            if ((challengeMessage.NegotiateFlags & NegotiateFlags.UnicodeEncoding) > 0)
            {
                authenticateMessage.NegotiateFlags |= NegotiateFlags.UnicodeEncoding;
            }
            else
            {
                authenticateMessage.NegotiateFlags |= NegotiateFlags.OEMEncoding;
            }

            if ((challengeMessage.NegotiateFlags & NegotiateFlags.KeyExchange) > 0)
            {
                authenticateMessage.NegotiateFlags |= NegotiateFlags.KeyExchange;
            }

            if (authenticationMethod == AuthenticationMethod.NTLMv1)
            {
                authenticateMessage.NegotiateFlags |= NegotiateFlags.LanManagerSessionKey;
            }
            else
            {
                authenticateMessage.NegotiateFlags |= NegotiateFlags.ExtendedSessionSecurity;
            }

            authenticateMessage.UserName    = userName;
            authenticateMessage.DomainName  = domainName;
            authenticateMessage.WorkStation = Environment.MachineName;
            byte[] sessionBaseKey;
            byte[] keyExchangeKey;
            if (authenticationMethod == AuthenticationMethod.NTLMv1 || authenticationMethod == AuthenticationMethod.NTLMv1ExtendedSessionSecurity)
            {
                if (authenticationMethod == AuthenticationMethod.NTLMv1)
                {
                    authenticateMessage.LmChallengeResponse = NTLMCryptography.ComputeLMv1Response(challengeMessage.ServerChallenge, password);
                    authenticateMessage.NtChallengeResponse = NTLMCryptography.ComputeNTLMv1Response(challengeMessage.ServerChallenge, password);
                }
                else // NTLMv1ExtendedSessionSecurity
                {
                    authenticateMessage.LmChallengeResponse = ByteUtils.Concatenate(clientChallenge, new byte[16]);
                    authenticateMessage.NtChallengeResponse = NTLMCryptography.ComputeNTLMv1ExtendedSessionSecurityResponse(challengeMessage.ServerChallenge, clientChallenge, password);
                }
                // https://msdn.microsoft.com/en-us/library/cc236699.aspx
                sessionBaseKey = new MD4().GetByteHashFromBytes(NTLMCryptography.NTOWFv1(password));
                byte[] lmowf = NTLMCryptography.LMOWFv1(password);
                keyExchangeKey = NTLMCryptography.KXKey(sessionBaseKey, authenticateMessage.NegotiateFlags, authenticateMessage.LmChallengeResponse, challengeMessage.ServerChallenge, lmowf);
            }
            else // NTLMv2
            {
                NTLMv2ClientChallenge clientChallengeStructure = new NTLMv2ClientChallenge(time, clientChallenge, challengeMessage.TargetInfo);
                byte[] clientChallengeStructurePadded          = clientChallengeStructure.GetBytesPadded();
                byte[] ntProofStr = NTLMCryptography.ComputeNTLMv2Proof(challengeMessage.ServerChallenge, clientChallengeStructurePadded, password, userName, domainName);

                authenticateMessage.LmChallengeResponse = NTLMCryptography.ComputeLMv2Response(challengeMessage.ServerChallenge, clientChallenge, password, userName, challengeMessage.TargetName);
                authenticateMessage.NtChallengeResponse = ByteUtils.Concatenate(ntProofStr, clientChallengeStructurePadded);

                // https://msdn.microsoft.com/en-us/library/cc236700.aspx
                byte[] responseKeyNT = NTLMCryptography.NTOWFv2(password, userName, domainName);
                sessionBaseKey = new HMACMD5(responseKeyNT).ComputeHash(ntProofStr);
                keyExchangeKey = sessionBaseKey;
            }
            authenticateMessage.Version = NTLMVersion.Server2003;

            // https://msdn.microsoft.com/en-us/library/cc236676.aspx
            if ((challengeMessage.NegotiateFlags & NegotiateFlags.KeyExchange) > 0)
            {
                sessionKey = new byte[16];
                new Random().NextBytes(sessionKey);
                authenticateMessage.EncryptedRandomSessionKey = RC4.Encrypt(keyExchangeKey, sessionKey);
            }
            else
            {
                sessionKey = keyExchangeKey;
            }

            if (useGSSAPI)
            {
                SimpleProtectedNegotiationTokenResponse outputToken = new SimpleProtectedNegotiationTokenResponse();
                outputToken.ResponseToken = authenticateMessage.GetBytes();
                return(outputToken.GetBytes());
            }
            else
            {
                return(authenticateMessage.GetBytes());
            }
        }
        public void TestNTLMv2KeyExchangeMIC()
        {
            byte[] responseKeyNT = NTLMCryptography.NTOWFv2("Password", "User", "TAL-VM6");
            byte[] type1         = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01, 0x00, 0x00, 0x00, 0x97, 0x82, 0x08, 0xe2,
                                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                                0x0a, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x0f };
            byte[] type2 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x02, 0x00, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00,
                                        0x38, 0x00, 0x00, 0x00, 0x15, 0x82, 0x8a, 0xe2, 0x63, 0x74, 0x79, 0x77, 0xe1, 0xea, 0x35, 0x51,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x60, 0x00, 0x48, 0x00, 0x00, 0x00,
                                        0x06, 0x00, 0x71, 0x17, 0x00, 0x00, 0x00, 0x0f, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00,
                                        0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00, 0x02, 0x00, 0x10, 0x00, 0x54, 0x00, 0x41, 0x00,
                                        0x4c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00, 0x01, 0x00, 0x10, 0x00,
                                        0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00,
                                        0x04, 0x00, 0x10, 0x00, 0x54, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00,
                                        0x31, 0x00, 0x30, 0x00, 0x03, 0x00, 0x10, 0x00, 0x54, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x2d, 0x00,
                                        0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00, 0x07, 0x00, 0x08, 0x00, 0x1f, 0x8a, 0xd4, 0xff,
                                        0x01, 0x91, 0xd2, 0x01, 0x00, 0x00, 0x00, 0x00 };
            byte[] type3 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x03, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00,
                                        0x7c, 0x00, 0x00, 0x00, 0x02, 0x01, 0x02, 0x01, 0x94, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x0e, 0x00,
                                        0x58, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x66, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x0e, 0x00,
                                        0x6e, 0x00, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x96, 0x01, 0x00, 0x00, 0x15, 0x82, 0x88, 0xe2,
                                        0x0a, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x0f, 0x82, 0x3c, 0xff, 0x48, 0xa9, 0x03, 0x13, 0x4c,
                                        0x33, 0x3c, 0x09, 0x87, 0xf3, 0x16, 0x59, 0x89, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00,
                                        0x56, 0x00, 0x4d, 0x00, 0x36, 0x00, 0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x54, 0x00,
                                        0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                        0x00, 0x00, 0x00, 0x00, 0xb3, 0x06, 0x65, 0xe3, 0x9f, 0x03, 0xe1, 0xc3, 0xd8, 0x28, 0x7c, 0x9c,
                                        0x35, 0x0d, 0x32, 0x4c, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x8a, 0xd4, 0xff,
                                        0x01, 0x91, 0xd2, 0x01, 0x77, 0x71, 0x91, 0x94, 0xb1, 0x6e, 0x66, 0x28, 0x00, 0x00, 0x00, 0x00,
                                        0x02, 0x00, 0x10, 0x00, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00,
                                        0x31, 0x00, 0x30, 0x00, 0x01, 0x00, 0x10, 0x00, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00,
                                        0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00, 0x04, 0x00, 0x10, 0x00, 0x54, 0x00, 0x61, 0x00,
                                        0x6c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00, 0x03, 0x00, 0x10, 0x00,
                                        0x54, 0x00, 0x61, 0x00, 0x6c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00,
                                        0x07, 0x00, 0x08, 0x00, 0x1f, 0x8a, 0xd4, 0xff, 0x01, 0x91, 0xd2, 0x01, 0x06, 0x00, 0x04, 0x00,
                                        0x02, 0x00, 0x00, 0x00, 0x08, 0x00, 0x30, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                        0x01, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x19, 0x0d, 0x73, 0xca, 0x97, 0x30, 0x2a, 0xa7,
                                        0x7a, 0x1f, 0xb6, 0xad, 0xe2, 0xe5, 0x4a, 0x59, 0x4a, 0x93, 0x7e, 0x37, 0xcd, 0x0c, 0xd7, 0x90,
                                        0x25, 0xc4, 0xaf, 0x8a, 0x17, 0x99, 0x69, 0x56, 0x0a, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x1a, 0x00,
                                        0x63, 0x00, 0x69, 0x00, 0x66, 0x00, 0x73, 0x00, 0x2f, 0x00, 0x54, 0x00, 0x61, 0x00, 0x6c, 0x00,
                                        0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x31, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x71, 0x7c, 0xce, 0x0b, 0x92, 0x46, 0x46, 0x0d, 0x5b, 0x3b,
                                        0x11, 0xb4, 0xde, 0x86, 0x28, 0x11 };

            byte[] serverChallenge = new ChallengeMessage(type2).ServerChallenge;
            AuthenticateMessage authenticateMessage = new AuthenticateMessage(type3);

            byte[] ntProofStr         = ByteReader.ReadBytes(authenticateMessage.NtChallengeResponse, 0, 16);
            byte[] sessionBaseKey     = new HMACMD5(responseKeyNT).ComputeHash(ntProofStr);
            byte[] exportedSessionKey = GetExportedSessionKey(sessionBaseKey, authenticateMessage, serverChallenge, null);

            // https://msdn.microsoft.com/en-us/library/cc236695.aspx
            const int micFieldOffset = 72;

            ByteWriter.WriteBytes(type3, micFieldOffset, new byte[16]);
            byte[] temp     = ByteUtils.Concatenate(ByteUtils.Concatenate(type1, type2), type3);
            byte[] mic      = new HMACMD5(exportedSessionKey).ComputeHash(temp);
            byte[] expected = new byte[] { 0x82, 0x3c, 0xff, 0x48, 0xa9, 0x03, 0x13, 0x4c, 0x33, 0x3c, 0x09, 0x87, 0xf3, 0x16, 0x59, 0x89 };

            Assert.True(ByteUtils.AreByteArraysEqual(mic, expected));
        }
        /// <summary>
        /// Calculates keyed md5 hash from specifieed text and with specified hash key.
        /// </summary>
        /// <param name="hashKey"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string HmacMd5(string hashKey, string text)
        {
            HMACMD5 kMd5 = new HMACMD5(Encoding.Default.GetBytes(text));

            return(Encoding.Default.GetString(kMd5.ComputeHash(Encoding.ASCII.GetBytes(hashKey))));
        }
Exemple #29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb1 = new StringBuilder();

        // x_login^x_fp_sequence^x_fp_timestamp^x_amount^x_currency
        //x_login.Value = "HCO-NONE-471";//x_login
        if (!String.IsNullOrEmpty(Request.QueryString["orderid"]))
        {
            XInvoiceNum = Request.QueryString["orderid"];
        }
        else
        {
            XInvoiceNum = SessionOrderId.ToString();
        }
        Random random = new Random();

        XFpSequence = (random.Next(0, 1000)).ToString();
        //x_test_request.Value = "false";
        //x_show_form.Value = "PAYMENT_FORM";
        TimeSpan t         = (DateTime.UtcNow - new DateTime(1970, 1, 1));
        int      timestamp = (int)t.TotalSeconds;

        XFpTimeStamp = timestamp.ToString();
        if (!String.IsNullOrEmpty(Request.QueryString["total"]))
        {
            XAmount = Request.QueryString["total"];
        }
        else
        {
            XAmount = SessionUserOrderTotal.ToString();
        }
        //String x_currency = "USD"; // default empty


        sb1.Append(XLogin)
        .Append("^")
        .Append(XFpSequence)
        .Append("^")
        .Append(XFpTimeStamp)
        .Append("^")
        .Append(XAmount)
        .Append("^")
        .Append("");

        // Convert string to array of bytes.
        byte[] data = Encoding.UTF8.GetBytes(sb1.ToString());

        // key
        byte[] key = Encoding.UTF8.GetBytes(XTransactionKey);//transaction_key

        // Create HMAC-SHA1 Algorithm;
        HMACMD5 hmac = new HMACMD5(key);

        // Create HMAC-SHA1 Algorithm;
        //HMACSHA1 hmac = new HMACSHA1(key);

        // Compute hash.
        byte[] hashBytes = hmac.ComputeHash(data);

        // Convert to HEX string.
        XFpHash = System.BitConverter.ToString(hashBytes).Replace("-", "").ToLower();

        if (String.IsNullOrEmpty(Request.QueryString["orderid"]))
        {
            SessionUserOrder      = null;
            SessionOrderId        = 0;
            SessionUserOrderTotal = 0;
        }
    }
		static byte[] ComputeNtlmV2 (Type2Message type2, string username, string password, string domain)
		{
			var ntlm_hash = ComputeNtlmPassword (password);

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

			var bytes = new byte[ubytes.Length + tbytes.Length];
			ubytes.CopyTo (bytes, 0);
			Array.Copy (tbytes, 0, bytes, ubytes.Length, tbytes.Length);

			byte[] ntlm_v2_hash;

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

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

			using (var md5 = new HMACMD5 (ntlm_v2_hash)) {
				var now = DateTime.Now;
				var timestamp = now.Ticks - 504911232000000000;
				var nonce = new byte[8];

				using (var rng = RandomNumberGenerator.Create ())
					rng.GetBytes (nonce);

				var targetInfo = type2.EncodedTargetInfo;
				var blob = new byte[28 + 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 (targetInfo, 0, blob, 28, 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 = 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);
				Array.Clear (hashInput, 0, hashInput.Length);
				Array.Clear (blobHash, 0, blobHash.Length);
				Array.Clear (nonce, 0, nonce.Length);
				Array.Clear (blob, 0, blob.Length);

				return response;
			}
		}
        public static byte[] ComputeMd5Hmac(byte[] key, byte[] input)
        {
            HMACMD5 hmacMd5 = new HMACMD5(key);

            return(hmacMd5.ComputeHash(input));
        }
        /// <summary>
        /// Calculates keyed md5 hash from specifieed text and with specified hash key.
        /// </summary>
        /// <param name="hashKey">MD5 key.</param>
        /// <param name="text">Text to hash.</param>
        /// <returns>Returns MD5 hash.</returns>
        private byte[] HmacMd5(string hashKey, string text)
        {
            HMACMD5 kMd5 = new HMACMD5(Encoding.Default.GetBytes(text));

            return(kMd5.ComputeHash(Encoding.ASCII.GetBytes(hashKey)));
        }
 private string HMAC_SHA1(string key, string message)
 {
     System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(key);
     HMACMD5 hmacmd5 = new HMACMD5(keyByte);
     HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
     byte[] messageBytes = encoding.GetBytes(message);
     byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
     return ByteToString(hashmessage);
 }
 public override void SetUp()
 {
     algo     = new HMACMD5();
     algo.Key = new byte [8];
     hash     = algo;
 }
Exemple #35
0
    /// <summary>
    /// 改变控制板信息
    /// </summary>
    /// <param name="gameIdx"></param>
    /// <param name="mainVersion"></param>
    /// <param name="subVersion"></param>
    /// <returns></returns>
    bool _UsbThread_ChangeMCUInfo(int gameIdx,int mainVersion,int subVersion)
    {
#if MOBILE_EDITION
        return false;
#endif
        byte[] tmpOutputBuff = new byte[LenOuputBuf];
        byte[] tmpInputBuff = new byte[LenInputBuf];
        //List<InputPackage> tmpRecivePack = new List<InputPackage>();
        byte[] plainDatasFromMCU = new byte[16];//来之MCU的明文
        uint numWrite = 0;
        uint readCount = 0;
        //发出修改MCU请求
        tmpOutputBuff[1] = tmpOutputBuff[tmpOutputBuff.Length - 1] = 0xF1;
        tmpOutputBuff[2] = 1; 
        mWriteOL.Clear();
        Win32Usb.WriteFile(mIOHandler, tmpOutputBuff, (uint)tmpOutputBuff.Length, ref numWrite, ref mWriteOL);
 
        if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) != 0)//返回超时
            return false;
        //MCU返回挑战信息
        mReadOL.Clear();
        Win32Usb.ReadFile(mIOHandler, tmpInputBuff, (uint)tmpInputBuff.Length, ref readCount, ref mReadOL);

        //bool verfySucess = true;
        if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) != 0)//读取超时
            return false;
        if (tmpInputBuff[1] != tmpInputBuff[tmpInputBuff.Length - 1] || tmpInputBuff[1] != 0xF1)//返回验证
            return false;

        //回应MCU的挑战信息,并设置控制板信息
        Array.Copy(tmpInputBuff,2,plainDatasFromMCU,0,plainDatasFromMCU.Length);
        HMACMD5 cryptor = new HMACMD5(System.Text.Encoding.ASCII.GetBytes("FX20120927YIDINGYAOCHANGAEF51FM2"));
        byte[] challengeAnswer = cryptor.ComputeHash(plainDatasFromMCU);
        Array.Clear(tmpOutputBuff, 0, tmpOutputBuff.Length);
        tmpOutputBuff[1] = tmpOutputBuff[tmpOutputBuff.Length - 1] = 0xF1;
        tmpOutputBuff[2] = 2;
        tmpOutputBuff[3] = (byte)gameIdx;//游戏序号
        Array.Copy(System.BitConverter.GetBytes((ushort)mainVersion),0,tmpOutputBuff,4,2);//设置版本号
        Array.Copy(System.BitConverter.GetBytes((ushort)subVersion),0,tmpOutputBuff,6,2);//设置版本号
        Array.Copy(challengeAnswer, 0, tmpOutputBuff, 8, challengeAnswer.Length);
        mWriteOL.Clear();
        Win32Usb.WriteFile(mIOHandler, tmpOutputBuff, (uint)tmpOutputBuff.Length, ref numWrite, ref mWriteOL);

        if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) != 0)//写超时
            return false;

        //等待设置是否成功
        mReadOL.Clear();
        Win32Usb.ReadFile(mIOHandler, tmpInputBuff, (uint)tmpInputBuff.Length, ref readCount, ref mReadOL);
        if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) != 0)//读取超时
            return false;
        if (tmpInputBuff[1] != tmpInputBuff[tmpInputBuff.Length - 1]
            || tmpInputBuff[1] != 0xF1
            || tmpInputBuff[2] != 0x55
            || tmpInputBuff[3] != 0xAA)//返回修改结果
            return false;
        return true;
        
    }
        /// <summary>
        /// Continues authentication process.
        /// </summary>
        /// <param name="serverResponse">Server sent SASL response.</param>
        /// <returns>Returns challenge request what must be sent to server or null if authentication has completed.</returns>
        /// <exception cref="ArgumentNullException">Is raised when <b>serverResponse</b> is null reference.</exception>
        /// <exception cref="InvalidOperationException">Is raised when this method is called when authentication is completed.</exception>
        public override byte[] Continue(byte[] serverResponse)
        {
            if (serverResponse == null)
            {
                throw new ArgumentNullException("serverResponse");
            }
            if (m_IsCompleted)
            {
                throw new InvalidOperationException("Authentication is completed.");
            }

            /* RFC 2195 2. Challenge-Response Authentication Mechanism.
             *  The authentication type associated with CRAM is "CRAM-MD5".
             *
             *  The data encoded in the first ready response contains an
             *  presumptively arbitrary string of random digits, a timestamp, and the
             *  fully-qualified primary host name of the server.  The syntax of the
             *  unencoded form must correspond to that of an RFC 822 'msg-id'
             *  [RFC822] as described in [POP3].
             *
             *  The client makes note of the data and then responds with a string
             *  consisting of the user name, a space, and a 'digest'.  The latter is
             *  computed by applying the keyed MD5 algorithm from [KEYED-MD5] where
             *  the key is a shared secret and the digested text is the timestamp
             *  (including angle-brackets).
             *
             *  This shared secret is a string known only to the client and server.
             *  The `digest' parameter itself is a 16-octet value which is sent in
             *  hexadecimal format, using lower-case ASCII characters.
             *
             *  When the server receives this client response, it verifies the digest
             *  provided.  If the digest is correct, the server should consider the
             *  client authenticated and respond appropriately.
             *
             *  Example:
             *      The examples in this document show the use of the CRAM mechanism with
             *      the IMAP4 AUTHENTICATE command [IMAP-AUTH].  The base64 encoding of
             *      the challenges and responses is part of the IMAP4 AUTHENTICATE
             *      command, not part of the CRAM specification itself.
             *
             *      S: * OK IMAP4 Server
             *      C: A0001 AUTHENTICATE CRAM-MD5
             *      S: + PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2UucmVzdG9uLm1jaS5uZXQ+
             *      C: dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
             *      S: A0001 OK CRAM authentication successful
             *
             *      In this example, the shared secret is the string
             *      'tanstaaftanstaaf'.  Hence, the Keyed MD5 digest is produced by
             *      calculating
             *
             *      MD5((tanstaaftanstaaf XOR opad),
             *          MD5((tanstaaftanstaaf XOR ipad),
             *          <*****@*****.**>))
             *
             *      where ipad and opad are as defined in the keyed-MD5 Work in
             *      Progress [KEYED-MD5] and the string shown in the challenge is the
             *      base64 encoding of <*****@*****.**>. The
             *      shared secret is null-padded to a length of 64 bytes. If the
             *      shared secret is longer than 64 bytes, the MD5 digest of the
             *      shared secret is used as a 16 byte input to the keyed MD5
             *      calculation.
             *
             *      This produces a digest value (in hexadecimal) of
             *
             *          b913a602c7eda7a495b4e6e7334d3890
             *
             *      The user name is then prepended to it, forming
             *
             *          tim b913a602c7eda7a495b4e6e7334d3890
             *
             *      Which is then base64 encoded to meet the requirements of the IMAP4
             *      AUTHENTICATE command (or the similar POP3 AUTH command), yielding
             *
             *      dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw
             */

            if (m_State == 0)
            {
                m_State++;
                m_IsCompleted = true;

                HMACMD5 kMd5         = new HMACMD5(Encoding.UTF8.GetBytes(m_Password));
                string  passwordHash = Net_Utils.ToHex(kMd5.ComputeHash(serverResponse)).ToLower();

                return(Encoding.UTF8.GetBytes(m_UserName + " " + passwordHash));
            }
            else
            {
                throw new InvalidOperationException("Authentication is completed.");
            }
        }
Exemple #37
0
    void Thread_Recive()
    {
#if MOBILE_EDITION
        return;
#endif
        try
        {
        InputCmdTrans = new int[LenInputDataPerCtrller, 2];

        for (int i = 0; i != LenInputDataPerCtrller; ++i)
            InputCmdTrans[i, 0] = i;

        InputCmdTrans[0,1] = (int)InputCmd.InCoin;
        InputCmdTrans[1,1] = (int)InputCmd.BtnE;
        InputCmdTrans[2,1] = (int)InputCmd.OutTicket;
        InputCmdTrans[3,1] = (int)InputCmd.OutCoin;
        InputCmdTrans[4,1] = (int)InputCmd.Up;
        InputCmdTrans[5,1] = (int)InputCmd.Down;
        InputCmdTrans[6,1] = (int)InputCmd.Left;
        InputCmdTrans[7,1] = (int)InputCmd.Right;
        InputCmdTrans[8,1] = (int)InputCmd.BtnA;
        InputCmdTrans[9,1] = (int)InputCmd.BtnB;
        InputCmdTrans[10,1] = (int)InputCmd.BtnC;
        InputCmdTrans[11,1] = (int)InputCmd.BtnD;
        //取消,左,右,小游戏,确定,下
        BackStageInputCmdTrans = new int[12];
        BackStageInputCmdTrans[0] = (int)InputCmd.Up;
        BackStageInputCmdTrans[1] = (int)InputCmd.BtnB;
        BackStageInputCmdTrans[2] = (int)InputCmd.Left;
        BackStageInputCmdTrans[3] = (int)InputCmd.Right;
        BackStageInputCmdTrans[4] = (int)InputCmd.BtnC;
        BackStageInputCmdTrans[5] = (int)InputCmd.BtnA;
        BackStageInputCmdTrans[6] = (int)InputCmd.Down;
 
        if (mOutputBuff == null)
            mOutputBuff = new BitArray((LenOuputBuf - 1) * 8 );//输入bitarray 减少一字节.以便.复制的时候向右移位
 

        BitArray tmpBA = null;//当前InputBitArray
        byte[] tmpOutputBuff = new byte[LenOuputBuf];
        byte[] tmpInputBuff = new byte[LenInputBuf];
        byte[] tmpPreInputBuff = new byte[LenInputBuf]; 
        List<InputPackage> tmpRecivePack = new List<InputPackage>();


        if (mOuttingCoinTag == null)
            mOuttingCoinTag = new Dictionary<int, OutBountyElapse>();
        if (mOuttingTicketTag == null)
            mOuttingTicketTag = new Dictionary<int, OutBountyElapse>();
        List<int> tmpListI = new List<int>();
      
        int offsetRead = 8;//读缓冲向右移8 bit
        uint numWrite = 0;
        uint readCount = 0;
        mRndObj = new System.Random();
        //读取一次状态
        mWriteOL.Clear();
        Array.Clear(tmpOutputBuff, 0, tmpOutputBuff.Length);
        
        Win32Usb.WriteFile(mIOHandler, tmpOutputBuff, (uint)tmpOutputBuff.Length, ref numWrite, ref mWriteOL);

        if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)//读取
        {
            Win32Usb.ReadFile(mIOHandler, tmpInputBuff, (uint)tmpInputBuff.Length, ref readCount, ref mReadOL);

            //接收包
            if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)
            {
                mInputBuff = new BitArray(tmpInputBuff);

#if RECORE_INITSTATE
                mInputBuffInit = new BitArray(tmpInputBuff);
#endif
                //初始化控制板状态
                for (int i = OfsInput_ControlBoardState + offsetRead; i != OfsInput_ControlBoardState + offsetRead + NumControlBoard; ++i)
                {
                    tmpRecivePack.Add(new InputPack_CtrlBoardState(InputPackCmd.CtrlBoardConnectState
                        , 0, i - OfsInput_ControlBoardState - offsetRead, mInputBuff[i]));//控制板状态
                }
                
                _FlushInputPackToMainThread(tmpRecivePack);
            }
            Thread.Sleep(100);
        }

#region 测试程序
        /*
        bool enableOutCoin = false;
        
        while (mThreadLoopRecive && mIOHandler != IntPtr.Zero)
        {
            mWriteOL.Clear();
            Array.Clear(tmpOutputBuff, 0, tmpOutputBuff.Length);


            mOutputBuff[0 * LenOuputDataPerCtrller + OfsOutput_OutCoin] = enableOutCoin;
            enableOutCoin = !enableOutCoin;
            mOutputBuff.CopyTo(tmpOutputBuff, 1);

            Win32Usb.WriteFile(mIOHandler, tmpOutputBuff, (uint)tmpOutputBuff.Length, ref numWrite, ref mWriteOL);

            if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)//发送完成
            {
                Thread.Sleep(1);
                
                Win32Usb.ReadFile(mIOHandler, tmpInputBuff, (uint)tmpInputBuff.Length, ref readCount, ref mReadOL);

                //接收包
                if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)//接收完成
                {
                    mInputBuff = new BitArray(tmpInputBuff);

                    //Thread.Sleep(1);

                    //初始化控制板状态
                    //for (int i = OfsInput_ControlBoardState + offsetRead; i != OfsInput_ControlBoardState + offsetRead + NumControlBoard; ++i)
                    //{
                    //    tmpRecivePack.Add(new InputPack_CtrlBoardState(InputPackCmd.CtrlBoardConnectState
                    //        , 0, i - OfsInput_ControlBoardState - offsetRead, mInputBuff[i]));//控制板状态
                    //}

                    //_FlushInputPackToMainThread(tmpRecivePack);
                }
                

            }
        }
        */
#endregion


        while (mThreadLoopRecive && mIOHandler != IntPtr.Zero)
        {
            if (Evt_HSThread_FrameStart != null)
                Evt_HSThread_FrameStart();

            

            if (Monitor.TryEnter(mSendPack_ThreadLock))
            {
                List<OutputPackage> tempList = mPackToSendST;

                mPackToSendST = mPackToSendMT;
                mPackToSendMT = tempList;
                Monitor.Exit(mSendPack_ThreadLock);
            } 
            
            foreach (OutputPackage pack in mPackToSendST)
            {
                   
                switch (pack.Cmd)
                {
                    case OutputPackCmd.OutCoin:
                        mOutputBuff[pack.CtrllerIdx * LenOuputDataPerCtrller + OfsOutput_OutCoin] = ((OutputPack_OutBounty)pack).Enable;

                        if (!mOuttingCoinTag.ContainsKey(pack.CtrllerIdx))
                            mOuttingCoinTag.Add(pack.CtrllerIdx, new OutBountyElapse(DateTime.Now.Ticks));
                        else
                            Debug.LogWarning("重复出币调用");
                        break;
                    case OutputPackCmd.OutTicket:
                        mOutputBuff[pack.CtrllerIdx * LenOuputDataPerCtrller + OfsOutput_OutTicket] = ((OutputPack_OutBounty)pack).Enable;
                        if (!mOuttingTicketTag.ContainsKey(pack.CtrllerIdx))
                            mOuttingTicketTag.Add(pack.CtrllerIdx, new OutBountyElapse(DateTime.Now.Ticks));
                        else
                            Debug.LogWarning("重复出票调用");
                        break;
                    case OutputPackCmd.FlashLight:
                        { 
                            OutputPack_Light lightPack = (OutputPack_Light)pack; 
                            if (lightPack.LightIdx == 0)
                                mOutputBuff[pack.CtrllerIdx * LenOuputDataPerCtrller + OfsOutput_Light0] = lightPack.IsOn;
                            else
                                mOutputBuff[pack.CtrllerIdx * LenOuputDataPerCtrller + OfsOutput_Light1] = lightPack.IsOn;

                        }
                        break;
                    case OutputPackCmd.RequestMCUInfo:
                        {

                            tmpOutputBuff[1] = tmpOutputBuff[tmpOutputBuff.Length - 1] = 1;

                            System.Random randObj = new System.Random();
                            int challengeNum = randObj.Next(int.MinValue, int.MaxValue); //发出要求MCU验证的数字
                            System.Array.Copy(System.BitConverter.GetBytes(challengeNum), 0, tmpOutputBuff, 2, 4);

                            mWriteOL.Clear();
                            Win32Usb.WriteFile(mIOHandler, tmpOutputBuff, (uint)tmpOutputBuff.Length, ref numWrite, ref mWriteOL);
         
                            if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)//读取
                            {
                                Win32Usb.ReadFile(mIOHandler, tmpInputBuff, (uint)tmpInputBuff.Length, ref readCount, ref mReadOL);
                                bool verfySucess = true;
                                if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read,true) == 0)
                                {
                                            
                                    if (tmpInputBuff[1] == tmpInputBuff[tmpInputBuff.Length - 1] && tmpInputBuff[1] == 1)
                                    {
                                        HMACMD5 cryptor = new HMACMD5(System.Text.Encoding.ASCII.GetBytes("yidingyaochang"));
                                        byte[] challengeAnswer = cryptor.ComputeHash(System.BitConverter.GetBytes(challengeNum));
                                        for (int i = 0; i != challengeAnswer.Length; ++i)
                                        {
                                            if (challengeAnswer[i] != tmpInputBuff[7 + i])
                                            { 
                                                verfySucess = false;
                                                break;
                                            }
                                        }
                                                
                                               
                                    }
                                    else//验证失败
                                    {
                                        verfySucess = false;
                                    }
                                }
                                else//验证失败
                                {
                                    verfySucess = false;
                                }

                                if (verfySucess)
                                {
                                    tmpRecivePack.Add(new InputPack_MCUInfo(InputPackCmd.MCUInfo, 0, true,
                                        tmpInputBuff[2],//游戏序号
                                        System.BitConverter.ToUInt16(tmpInputBuff, 3),//主版本号
                                        System.BitConverter.ToUInt16(tmpInputBuff, 5)//副版本号
                                        ));
                                }
                                else
                                {
                                    tmpRecivePack.Add(new InputPack_MCUInfo(InputPackCmd.MCUInfo, 0, false, -1, 0, 0));
                                }
                                _FlushInputPackToMainThread(tmpRecivePack);
                            } 
                        }
                        break;
                    case OutputPackCmd.EditMCUInfo:
                        {
                            OutputPack_EditMCUInfo op = (OutputPack_EditMCUInfo)pack;

                            bool result = _UsbThread_ChangeMCUInfo(op.GameIdx, op.MainVersion, op.SubVersion);

                            tmpRecivePack.Add(new InputPack_ResultEditMCUInfo(InputPackCmd.ResultEditMCUInfo, 0, result));
                            _FlushInputPackToMainThread(tmpRecivePack);
                        }
                        break;

                    case OutputPackCmd.ReadWriteRequest://有读写请求的,直接进行读取处理
                        {
                            OutputPack_ReadWriteRequest p = (OutputPack_ReadWriteRequest)pack;
                            //包标识
                            tmpOutputBuff[1] = 0xf2;
                            //读写标记
                            tmpOutputBuff[2] = (byte)(p.IsWrite ?  1 : 0);
                            //地址
                            Array.Copy(System.BitConverter.GetBytes(p.Address), 0, tmpOutputBuff, 3, 4);
                            //数据长度
                            tmpOutputBuff[7] = p.DataLength;
                            //数据
                            if(p.Data != null)
                                Array.Copy(p.Data, 0, tmpOutputBuff, 8, p.DataLength);
                            //随机数填充
                            Byte[] tmpByte = new byte[5];
                            mRndObj.NextBytes(tmpByte);
                            Array.Copy(tmpByte, 0, tmpOutputBuff, 24, 5);
                            //校验码
                            Array.Clear(tmpByte,0,5);
                            for (int i = 0; i != 4; ++i)
                            {
                                for (int j = 0; j != 7; ++j)
                                {
                                    tmpByte[i] ^= tmpOutputBuff[j * 4 + i + 1];
                                }
                            }
                            Array.Copy(tmpByte, 0, tmpOutputBuff, 29, 4);
                            //Debug.Log(string.Format("adress:{0:d} len:{1:d}  ", p.Address, p.DataLength));
                            //Debug.Log("w");
                            //发出消息
                            mWriteOL.Clear();

                            Win32Usb.WriteFile(mIOHandler, tmpOutputBuff, (uint)tmpOutputBuff.Length, ref numWrite, ref mWriteOL);
                                

                            //读取消息
                            if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)//读取
                            {
                                Win32Usb.ReadFile(mIOHandler, tmpInputBuff, (uint)tmpInputBuff.Length, ref readCount, ref mReadOL);
                                if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)
                                {
                                    //验证包是否正常
                                    if(tmpInputBuff[1] != 0xF2)
                                        goto BREAK_THIS_SWITCH;
                                    //校验码是否正确
                                    Byte[] tmpByte4 = new byte[4];
                                    for (int i = 0; i != 4; ++i)
                                    {
                                        for (int j = 0; j != 7; ++j)
                                        {
                                            tmpByte4[i] ^= tmpInputBuff[j * 4 + i + 1];
                                        }
                                            
                                    }
                                    for(int i = 0; i != 4; ++i)
                                    {
                                        if(tmpByte4[i] != tmpInputBuff[29+i])
                                            goto BREAK_THIS_SWITCH;
                                    }

                                    //Array.Copy(tmpInputBuff, 3, tmpByte4, 0, 4);
                                    uint adress = System.BitConverter.ToUInt32(tmpInputBuff,3);
                                    byte dataLen = tmpInputBuff[7];
                                    byte[] dataOut = null;
                                    if(tmpInputBuff[2] == 0)//读取标记
                                    {
                                        dataOut = new byte[dataLen];
                                        Array.Copy(tmpInputBuff,9,dataOut,0,dataLen);
                                    }
                                    //开始组包
                                    tmpRecivePack.Add(new InputPack_ResultReadWrite(InputPackCmd.ResultReadWrite
                                        , tmpInputBuff[2] == 0 ? false : true,//读写标记
                                        adress,//地址
                                        dataLen,//包长度
                                        tmpInputBuff[8],//读写结果
                                        dataOut//包
                                        ));
                                    //Debug.Log(string.Format("adress:{0:d}  datalen{1:d}  resultcode:{2:d}  ",adress,dataLen,tmpInputBuff[8]));
                                    _FlushInputPackToMainThread(tmpRecivePack);
                                    
                                }
                            }
                        }
                        BREAK_THIS_SWITCH: 
                        break;

                }

            }

            mPackToSendST.Clear();
            
            //发出数据
            mOutputBuff.CopyTo(tmpOutputBuff, 1);
            mWriteOL.Clear();
            Win32Usb.WriteFile(mIOHandler, tmpOutputBuff, (uint)tmpOutputBuff.Length, ref numWrite, ref mWriteOL);
            //Thread.Sleep(5);
            if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) != 0)//读超时
            {
                
                goto TAG_INPUT_PROCESS;//读超时,则跳过缺币检测
            }
            
            //缺币检测(提高扫描速度)
            tmpListI.Clear();
            foreach (KeyValuePair<int, OutBountyElapse> kvp in mOuttingCoinTag)
            {
                if (DateTime.Now.Ticks - kvp.Value.Time > Timeout_Outbounty)//超时放入删除列表
                    tmpListI.Add(kvp.Key);
            }

            foreach (int ctrlIdx in tmpListI)
            {
                tmpRecivePack.Add(new InputPackage(InputPackCmd.LackCoin, ctrlIdx));//发送包
                mOutputBuff[ctrlIdx * LenOuputDataPerCtrller + OfsOutput_OutCoin] = false;//关闭出币口
                mOuttingCoinTag.Remove(ctrlIdx);
            }

            //缺票处理
            tmpListI.Clear();
            foreach (KeyValuePair<int, OutBountyElapse> kvp in mOuttingTicketTag)
            {
                if (DateTime.Now.Ticks - kvp.Value.Time > Timeout_Outbounty)//超时放入删除列表
                    tmpListI.Add(kvp.Key);
            }

            foreach (int ctrlIdx in tmpListI)
            {
                tmpRecivePack.Add(new InputPackage(InputPackCmd.LackTicket, ctrlIdx));
                mOutputBuff[ctrlIdx * LenOuputDataPerCtrller + OfsOutput_OutTicket] = false;//关闭出票口
                mOuttingTicketTag.Remove(ctrlIdx);
            }
 

        TAG_INPUT_PROCESS:
            //接收数据
            mReadOL.Clear(); 
            Win32Usb.ReadFile(mIOHandler, tmpInputBuff, (uint)tmpInputBuff.Length, ref readCount, ref mReadOL);
            //接收包 
            if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)
            {
                //检测有变化
                #region 检查接受内容是否有变化,没有变化则跳过(这里先对字节循环,而不是比特,提高效率)

                int idxValid = 0;//验证到的索引
                for(idxValid = 0; idxValid != tmpPreInputBuff.Length;++idxValid)
                {
                    if(tmpPreInputBuff[idxValid] != tmpInputBuff[idxValid])
                    {
                        break;
                    }
                }
                if (idxValid == tmpPreInputBuff.Length)//前一帧包与当前包一致
                {
                    //goto TAG_BREAK_INPUT;
                }
                else
                {
                    tmpInputBuff.CopyTo(tmpPreInputBuff, 0);
                }
                #endregion

                tmpBA = new BitArray(tmpInputBuff);
                
                int validDataEnd = LenInputDataPerCtrller * NumCtrller + offsetRead;
                for (int i = offsetRead; i != validDataEnd; ++i)
                {
                    if (tmpBA[i] != mInputBuff[i])
                    {
                        int ctrlIdx = (i - offsetRead) / LenInputDataPerCtrller;
                        InputCmd dataIdx = (InputCmd)InputCmdTrans[((i - offsetRead) % LenInputDataPerCtrller), ctrlIdx % 2];
                        switch (dataIdx)
                        {
                            case InputCmd.Up:
                            case InputCmd.Down:
                            case InputCmd.Left:
                            case InputCmd.Right:
                            case InputCmd.BtnA:
                            case InputCmd.BtnB:
                            case InputCmd.BtnC:
                            case InputCmd.BtnD:
                            case InputCmd.BtnE:
                                {
                                    if (FuncHSThread_AddKeyPress == null)
                                    {
                                        InputPack_Key pack = new InputPack_Key(InputPackCmd.Key, ctrlIdx, dataIdx, tmpBA[i]);
                                        tmpRecivePack.Add(pack);
                                    }
                                    else
                                    {
                                        if (FuncHSThread_AddKeyPress(ctrlIdx, dataIdx , tmpBA[i]))
                                        {
                                            InputPack_Key pack = new InputPack_Key(InputPackCmd.Key, ctrlIdx, dataIdx, tmpBA[i]);
                                            tmpRecivePack.Add(pack);
                                        }
                                    }
                                    
                                    //InputPack_Key pack = new InputPack_Key(InputPackCmd.Key, ctrlIdx, dataIdx, tmpBA[i]);
                                    //tmpRecivePack.Add(pack);
                                }
                                break;
                            case InputCmd.InCoin:
                                {
                                    if (tmpBA[i])
                                    {
                                        InputPackage pack = new InputPackage(InputPackCmd.InsertCoin, ctrlIdx);
                                        tmpRecivePack.Add(pack);
                                    }
                                }
                                break;
                            case InputCmd.OutCoin:
                                {
#if RECORE_INITSTATE
                                    if (tmpBA[i] == mInputBuffInit[i])
#else
                                    if (tmpBA[i])
#endif
                                    {
                                        InputPackage pack = new InputPackage(InputPackCmd.OutCoin, ctrlIdx);
                                        tmpRecivePack.Add(pack);
                                        //重置出币 
                                        mOutputBuff[pack.CtrllerIdx * LenOuputDataPerCtrller + OfsOutput_OutCoin] = false;
                                        mOuttingCoinTag.Remove(pack.CtrllerIdx);
                                    }
                                }
                                break;
                            case InputCmd.OutTicket:
                                {
#if RECORE_INITSTATE
                                    if (tmpBA[i] == mInputBuffInit[i])
#else
                                    if (tmpBA[i])
#endif
                                    {

                                        InputPackage pack = new InputPackage(InputPackCmd.OutTicket, ctrlIdx);
                                        tmpRecivePack.Add(pack);
                                        //重置出票
                                        mOutputBuff[pack.CtrllerIdx * LenOuputDataPerCtrller + OfsOutput_OutTicket] = false;
                                        mOuttingTicketTag.Remove(pack.CtrllerIdx);
                                    }
                                }
                                break;
                        }//switch


                    }//if (tmpBA[i] != mInputBuff[i])判断是否改变了

                }//for (int i = 0; i != validData; ++i)每个有效数据循环,
                //控制板状态
               
                for (int i = OfsInput_ControlBoardState + offsetRead; i != OfsInput_ControlBoardState + offsetRead + NumControlBoard; ++i)
                {
                    if (tmpBA[i] != mInputBuff[i])
                    {
                        tmpRecivePack.Add(new InputPack_CtrlBoardState(InputPackCmd.CtrlBoardConnectState
                        , 0, i - OfsInput_ControlBoardState - offsetRead, tmpBA[i]));//控制板状态
                    }
                    
                }
 
                //Debug.Log("pBA[257]=" + tmpBA[257]);
                //后台按键判断 //上,取消,左,右,小游戏,确定,下
                for (int i = OfsInput_BsKeyStartBit + offsetRead; i != OfsInput_BsKeyEndBit + offsetRead; ++i)
                {
                    if (tmpBA[i] != mInputBuff[i])
                    {
                        InputPack_Key pack = new InputPack_Key(InputPackCmd.Key, 21, (InputCmd)BackStageInputCmdTrans[i - OfsInput_BsKeyStartBit - offsetRead], tmpBA[i]);
                        tmpRecivePack.Add(pack);
                    }
                }

                mInputBuff = tmpBA;
                foreach (InputPackage p in mInputPackageFromPlugin)
                {
                    tmpRecivePack.Add(p);
                }
                mInputPackageFromPlugin.Clear();
                _FlushInputPackToMainThread(tmpRecivePack);
            //TAG_BREAK_INPUT: ;

            }//if (Win32Usb.WaitForSingleObjectEx(mIOHandler, Timeout_Read, true) == 0)//等待读取超时
             
        }//while //线程while循环   
        }//try
        catch (System.TimeoutException)
        {
            Debug.LogError("time out");
        }
        catch (System.Exception ex)
        {
            Debug.LogError("SerialThreadUpdate Exception:" + ex.Message);
        }
        finally
        {
            Debug.Log("thread exit");
        }
    }
    private string SaltHashString(string str)
    {
        byte[] saltBytes = new byte[] { 12, 254, 62, 6, 7, 42, 2, 96 };
        byte[] saltedHashBytesStr= new HMACMD5(saltBytes).ComputeHash(Encoding.UTF8.GetBytes(str));

        return Convert.ToBase64String(saltedHashBytesStr);
    }
        private void button1_Click(object sender, EventArgs e)
        {
            if (radioButton1.Checked == true)
            {
                richTextBox2.Text = "";
                if (checkBox1.Checked == true)
                {
                    if (label5.Text != "" && label6.Text != "")
                    {
                        String str = Microsoft.VisualBasic.Interaction.InputBox("Enter the secret key:", "Enter key (* 10 characters atleast)");
                        bool   f   = false;
                        if (str.Length < 10)
                        {
                            f = true;
                        }
                        if (f)
                        {
                            MessageBox.Show("Please enter a key of 10+ characters!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                        else
                        {
                            if (comboBox1.SelectedIndex == 0)
                            {
                                Dictionary <int, char> B64 = new Dictionary <int, char>();
                                Dictionary <char, int> B46 = new Dictionary <char, int>();
                                for (int i = 0; i < 128; i++)
                                {
                                    B64[i] = (char)(128 + i);
                                    B46[(char)(128 + i)] = i;
                                }
                                Byte[] key = new Byte[str.Length];
                                for (int i = 0; i < str.Length; i++)
                                {
                                    key[i] = (byte)str[i];
                                    //  System.Console.Write((char)key[i]);
                                }
                                //System.Console.WriteLine();
                                int        b;
                                FileStream fs  = new FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
                                FileStream fs1 = new FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create);
                                int        k   = 0;
                                while ((b = fs.ReadByte()) != -1)
                                {
                                    //                                System.Console.WriteLine((char)b);
                                    char s1 = (basic_enc((char)b));
                                    //                              System.Console.WriteLine(s1);
                                    char tmp;
                                    int  x = (s1 + ((int)str[k] % 128)) % 128;
                                    tmp = (char)x;
                                    //                            System.Console.WriteLine(tmp);
                                    str = Reverse(str);
                                    x   = (tmp + ((int)str[k] % 128)) % 128;
                                    k   = (k + 1) % str.Length;
                                    tmp = B64[x];
                                    //                          System.Console.WriteLine(tmp);
                                    fs1.WriteByte((byte)tmp);
                                }
                                //Console.WriteLine(s1);
                                fs.Close();
                                fs = new FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
                                HMACMD5 hmac = new HMACMD5(key);
                                fs1.WriteByte((byte)(' '));
                                byte[] hashValue = hmac.ComputeHash(fs);
                                for (int i = 0; i < hashValue.Length; i++)
                                {
                                    fs1.WriteByte(hashValue[i]);
                                    //    System.Console.Write((char)hashValue[i]);
                                }
                                //System.Console.WriteLine();
                                fs.Close();
                                fs.Dispose();
                                fs1.Close();
                                fs1.Dispose();
                            }
                            else if (comboBox1.SelectedIndex == 1)
                            {
                                Dictionary <int, char> B64 = new Dictionary <int, char>();
                                Dictionary <char, int> B46 = new Dictionary <char, int>();
                                for (int i = 0; i < 256; i++)
                                {
                                    B64[i] = (char)(255 - i);
                                    B46[(char)(255 - i)] = i;
                                }
                                Bitmap a, bm;
                                a  = new Bitmap(openFileDialog1.FileName);
                                bm = new Bitmap(openFileDialog1.FileName);
                                int len = a.Width, hei = a.Height;
                                int k = 0;
                                for (int i = 0; i < len; i++)
                                {
                                    for (int j = 0; j < hei; j++)
                                    {
                                        Color p = a.GetPixel(i, j), q;
                                        byte  r = p.R, g = p.G, b = p.B, v = (byte)p.ToArgb(), al = p.A;

                                        /*if (i == 0 && j == 0)
                                         * {
                                         *  System.Console.WriteLine(r);
                                         *  System.Console.WriteLine(g);
                                         *  System.Console.WriteLine(b);
                                         * }*/
                                        char tmp, s1;
                                        int  x;
                                        s1  = (basic_enc((char)r));
                                        x   = (s1 + ((int)str[k] % 256)) % 256;
                                        tmp = (char)x;
                                        str = Reverse(str);
                                        x   = (tmp + ((int)str[k] % 256)) % 256;
                                        k   = (k + 1) % str.Length;
                                        tmp = B64[x];
                                        r   = (byte)tmp;
                                        s1  = (basic_enc((char)g));
                                        x   = (s1 + ((int)str[k] % 256)) % 256;
                                        tmp = (char)x;
                                        str = Reverse(str);
                                        x   = (tmp + ((int)str[k] % 256)) % 256;
                                        k   = (k + 1) % str.Length;
                                        tmp = B64[x];
                                        g   = (byte)tmp;
                                        s1  = (basic_enc((char)b));
                                        x   = (s1 + ((int)str[k] % 256)) % 256;
                                        tmp = (char)x;
                                        str = Reverse(str);
                                        x   = (tmp + ((int)str[k] % 256)) % 256;
                                        k   = (k + 1) % str.Length;
                                        tmp = B64[x];
                                        b   = (byte)tmp;

                                        /*s1 = (basic_enc((char)v));
                                         * x = (s1 + ((int)str[k] % 256)) % 256;
                                         * tmp = (char)x;
                                         * str = Reverse(str);
                                         * x = (tmp + ((int)str[k] % 256)) % 256;
                                         * k = (k + 1) % str.Length;
                                         * tmp = B64[x];
                                         * v = (byte)tmp;
                                         * s1 = (basic_enc((char)al));
                                         * x = (s1 + ((int)str[k] % 256)) % 256;
                                         * tmp = (char)x;
                                         * str = Reverse(str);
                                         * x = (tmp + ((int)str[k] % 256)) % 256;
                                         * k = (k + 1) % str.Length;
                                         * tmp = B64[x];
                                         * al = (byte)tmp;*/
                                        /*r = (byte)~r;
                                        *  g = (byte)~g;
                                        *  b = (byte)~b;*/
                                        byte tmpr;
                                        tmpr = r;
                                        r    = b;
                                        b    = g;
                                        g    = tmpr;
                                        r    = (byte)(r ^ (i * j));
                                        g    = (byte)(g ^ (i * j));
                                        b    = (byte)(b ^ (i * j));

                                        /*r = (byte)(r ^ ((i ^ j) * 10));
                                        *  g = (byte)(g ^ ((i ^ j) * 10));
                                        *  b = (byte)(b ^ ((i ^ j) * 10));*/
                                        //q = Color.FromArgb(al, r, g, b);
                                        q = Color.FromArgb(r, g, b);

                                        /*if (i == 0 && j == 0)
                                         * {
                                         *  System.Console.WriteLine(r);
                                         *  System.Console.WriteLine(g);
                                         *  System.Console.WriteLine(b);
                                         * }*/
                                        //q = Color.FromArgb(v);
                                        bm.SetPixel(i, j, q);
                                        //                            st2 += B64[y];
                                    }
                                }
                                //bm.Save(saveFileDialog1.FileName);
                                bm.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png);
                            }
                            else
                            {
                                Dictionary <int, char> B64 = new Dictionary <int, char>();
                                Dictionary <char, int> B46 = new Dictionary <char, int>();
                                for (int i = 0; i < 256; i++)
                                {
                                    B64[i] = (char)(255 - i);
                                    B46[(char)(255 - i)] = i;
                                }
                                int        b;
                                FileStream fs  = new FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
                                FileStream fs1 = new FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create);
                                int        k   = 0;
                                while ((b = fs.ReadByte()) != -1)
                                {
                                    //                                System.Console.WriteLine((char)b);
                                    char s1 = (basic_enc((char)b));
                                    //                              System.Console.WriteLine(s1);
                                    char tmp;
                                    int  x = (s1 + ((int)str[k] % 256)) % 256;
                                    tmp = (char)x;
                                    //                            System.Console.WriteLine(tmp);
                                    str = Reverse(str);
                                    x   = (tmp + ((int)str[k] % 256)) % 256;
                                    k   = (k + 1) % str.Length;
                                    tmp = B64[x];
                                    //                          System.Console.WriteLine(tmp);
                                    fs1.WriteByte((byte)tmp);
                                }
                                //Console.WriteLine(s1);
                                fs.Close();
                                fs.Dispose();
                                fs1.Close();
                                fs1.Dispose();
                            }
                            MessageBox.Show("Encryption complete!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            label5.Text = "";
                            label6.Text = "";
                            openFileDialog1.Dispose();
                            saveFileDialog1.Dispose();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Atleast one file not selected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }
                else
                {
                    if (richTextBox1.Text == "")
                    {
                        MessageBox.Show("No text entered!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        String str = Microsoft.VisualBasic.Interaction.InputBox("Enter the secret key:", "Enter key (* 10 characters atleast)");
                        bool   f   = false;
                        if (str.Length < 10)
                        {
                            f = true;
                        }
                        if (f)
                        {
                            MessageBox.Show("Please enter a key of 10+ characters!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                        else
                        {
                            Dictionary <int, char> B64 = new Dictionary <int, char>();
                            Dictionary <char, int> B46 = new Dictionary <char, int>();
                            for (int i = 0; i < 128; i++)
                            {
                                B64[i] = (char)(128 + i);
                                B46[(char)(128 + i)] = i;
                            }
                            int    k = 0;
                            string str1 = "", s = richTextBox1.Text.Trim().ToString();
                            for (int i = 0; i < s.Length; i++)
                            {
                                byte b  = (byte)s[i];
                                char s1 = (basic_enc((char)b));
                                //                              System.Console.WriteLine(s1);
                                char tmp;
                                int  x = (s1 + ((int)str[k] % 128)) % 128;
                                tmp = (char)x;
                                //                            System.Console.WriteLine(tmp);
                                str   = Reverse(str);
                                x     = (tmp + ((int)str[k] % 128)) % 128;
                                k     = (k + 1) % str.Length;
                                tmp   = B64[x];
                                str1 += tmp;
                                //                            st2 += B64[y];
                            }
                            richTextBox2.Text = str1;
                        }
                    }
                }
            }
            else
            {
                richTextBox1.Text = "";
                if (checkBox1.Checked == true)
                {
                    if (label5.Text != "" && label6.Text != "")
                    {
                        String str = Microsoft.VisualBasic.Interaction.InputBox("Enter the secret key:", "Enter key (* 10 characters atleast)");
                        bool   f   = false;
                        if (str.Length < 10)
                        {
                            f = true;
                        }
                        if (f)
                        {
                            MessageBox.Show("Please enter a key of 10+ characters!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                        else
                        {
                            if (comboBox1.SelectedIndex == 0)
                            {
                                Dictionary <int, char> B64 = new Dictionary <int, char>();
                                Dictionary <char, int> B46 = new Dictionary <char, int>();
                                for (int i = 0; i < 128; i++)
                                {
                                    B64[i] = (char)(128 + i);
                                    B46[(char)(128 + i)] = i;
                                }
                                int    b;
                                Byte[] key = new Byte[str.Length];
                                for (int i = 0; i < str.Length; i++)
                                {
                                    key[i] = (byte)str[i];
                                }
                                FileStream fs  = new FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
                                FileStream fs1 = new FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create);
                                int        k   = 0;
                                while ((b = fs.ReadByte()) != -1)
                                {
                                    if (b == ' ')
                                    {
                                        break;
                                    }
                                    //                        System.Console.WriteLine((char)b);
                                    str = Reverse(str);
                                    //                      System.Console.WriteLine(str);
                                    int x = (B46[(char)b] - (str[k] % 128) + 128) % 128;
                                    //                    System.Console.WriteLine((char)x);
                                    str = Reverse(str);
                                    //                  System.Console.WriteLine(str);
                                    x = (x - (str[k] % 128) + 128) % 128;
                                    //                System.Console.WriteLine((char)x);
                                    k = (k + 1) % str.Length;
                                    fs1.WriteByte((byte)(basic_dec((char)x)));
                                }
                                String ha = "";
                                while ((b = fs.ReadByte()) != -1)
                                {
                                    //    System.Console.Write((char)b);
                                    ha += (char)b;
                                }
                                fs.Close();
                                fs1.Close();
                                fs1.Dispose();
                                fs = new FileStream(saveFileDialog1.FileName, System.IO.FileMode.Open);
                                HMACMD5 hmac      = new HMACMD5(key);
                                byte[]  hashValue = hmac.ComputeHash(fs);
                                int     flag      = 0;
                                for (int i = 0; i < hashValue.Length; i++)
                                {
                                    if (hashValue[i] != ha[i])
                                    {
                                        flag = 1;
                                        //break;
                                    }
                                }
                                if (flag == 1)
                                {
                                    MessageBox.Show("File integrity compromised!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                                else
                                {
                                    MessageBox.Show("File integrity maintained", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                fs.Close();
                                fs.Dispose();
                            }
                            else if (comboBox1.SelectedIndex == 1)
                            {
                                Dictionary <int, char> B64 = new Dictionary <int, char>();
                                Dictionary <char, int> B46 = new Dictionary <char, int>();
                                for (int i = 0; i < 256; i++)
                                {
                                    B64[i] = (char)(255 - i);
                                    B46[(char)(255 - i)] = i;
                                }
                                Bitmap a, bm;
                                a  = new Bitmap(openFileDialog1.FileName);
                                bm = new Bitmap(openFileDialog1.FileName);
                                int len = a.Width, hei = a.Height;
                                int k = 0;
                                for (int i = 0; i < len; i++)
                                {
                                    for (int j = 0; j < hei; j++)
                                    {
                                        Color p = a.GetPixel(i, j), q;
                                        byte  r = p.R, g = p.G, b = p.B, v = (byte)p.ToArgb(), al = p.A;

                                        /*if (i == 0 && j == 0)
                                         * {
                                         *  System.Console.WriteLine(r);
                                         *  System.Console.WriteLine(g);
                                         *  System.Console.WriteLine(b);
                                         * }*/
                                        /*r = (byte)(r ^ ((i ^ j)*10));
                                        *  g = (byte)(g ^ ((i ^ j)*10));
                                        *  b = (byte)(b ^ ((i ^ j)*10));*/
                                        r = (byte)(r ^ (i * j));
                                        g = (byte)(g ^ (i * j));
                                        b = (byte)(b ^ (i * j));
                                        byte tmpr;
                                        tmpr = g;
                                        g    = b;
                                        b    = r;
                                        r    = tmpr;

                                        /*r = (byte)~r;
                                        *  g = (byte)~g;
                                        *  b = (byte)~b;*/
                                        int x;
                                        str = Reverse(str);
                                        x   = (B46[(char)r] - (str[k] % 256) + 256) % 256;
                                        str = Reverse(str);
                                        x   = (x - (str[k] % 256) + 256) % 256;
                                        k   = (k + 1) % str.Length;
                                        r   = ((byte)(basic_dec((char)x)));
                                        str = Reverse(str);
                                        x   = (B46[(char)g] - (str[k] % 256) + 256) % 256;
                                        str = Reverse(str);
                                        x   = (x - (str[k] % 256) + 256) % 256;
                                        k   = (k + 1) % str.Length;
                                        g   = ((byte)(basic_dec((char)x)));
                                        str = Reverse(str);
                                        x   = (B46[(char)b] - (str[k] % 256) + 256) % 256;
                                        str = Reverse(str);
                                        x   = (x - (str[k] % 256) + 256) % 256;
                                        k   = (k + 1) % str.Length;
                                        b   = ((byte)(basic_dec((char)x)));

                                        /*str = Reverse(str);
                                         * x = (B46[(char)al] - (str[k] % 256) + 256) % 256;
                                         * str = Reverse(str);
                                         * x = (x - (str[k] % 256) + 256) % 256;
                                         * k = (k + 1) % str.Length;
                                         * al = ((byte)(basic_dec((char)x)));
                                         * str = Reverse(str);
                                         * x = (B46[(char)v] - (str[k] % 256) + 256) % 256;
                                         * str = Reverse(str);
                                         * x = (x - (str[k] % 256) + 256) % 256;
                                         * k = (k + 1) % str.Length;
                                         * v = ((byte)(basic_dec((char)x)));*/
                                        q = Color.FromArgb(r, g, b);
                                        //q = Color.FromArgb(al, r, g, b);
                                        //q = Color.FromArgb(v);

                                        /*if (i == 0 && j == 0)
                                         * {
                                         *  System.Console.WriteLine(r);
                                         *  System.Console.WriteLine(g);
                                         *  System.Console.WriteLine(b);
                                         * }*/
                                        bm.SetPixel(i, j, q);
                                        //                            st2 += B64[y];
                                    }
                                }
                                bm.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                                //bm.Save(saveFileDialog1.FileName);
                            }
                            else
                            {
                                Dictionary <int, char> B64 = new Dictionary <int, char>();
                                Dictionary <char, int> B46 = new Dictionary <char, int>();
                                for (int i = 0; i < 256; i++)
                                {
                                    B64[i] = (char)(255 - i);
                                    B46[(char)(255 - i)] = i;
                                }
                                int        b;
                                FileStream fs  = new FileStream(openFileDialog1.FileName, System.IO.FileMode.Open);
                                FileStream fs1 = new FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create);
                                int        k   = 0;
                                while ((b = fs.ReadByte()) != -1)
                                {
                                    //                        System.Console.WriteLine((char)b);
                                    str = Reverse(str);
                                    //                      System.Console.WriteLine(str);
                                    int x = (B46[(char)b] - (str[k] % 256) + 256) % 256;
                                    //                    System.Console.WriteLine((char)x);
                                    str = Reverse(str);
                                    //                  System.Console.WriteLine(str);
                                    x = (x - (str[k] % 256) + 256) % 256;
                                    //                System.Console.WriteLine((char)x);
                                    k = (k + 1) % str.Length;
                                    fs1.WriteByte((byte)(basic_dec((char)x)));
                                }
                                fs.Close();
                                fs.Dispose();
                                fs1.Close();
                                fs1.Dispose();
                            }
                            MessageBox.Show("Decryption complete!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            label5.Text = "";
                            label6.Text = "";
                            openFileDialog1.Dispose();
                            saveFileDialog1.Dispose();
                        }
                    }
                    else
                    {
                        MessageBox.Show("Atleast one file not selected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }
                else
                {
                    if (richTextBox2.Text == "")
                    {
                        MessageBox.Show("No text entered!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        String str = Microsoft.VisualBasic.Interaction.InputBox("Enter the secret key:", "Enter key (* 10 characters atleast)");
                        bool   f   = false;
                        if (str.Length < 10)
                        {
                            f = true;
                        }
                        if (f)
                        {
                            MessageBox.Show("Please enter a key of 10+ characters!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        }
                        else
                        {
                            Dictionary <int, char> B64 = new Dictionary <int, char>();
                            Dictionary <char, int> B46 = new Dictionary <char, int>();
                            for (int i = 0; i < 128; i++)
                            {
                                B64[i] = (char)(128 + i);
                                B46[(char)(128 + i)] = i;
                            }
                            string str1 = "", s = richTextBox2.Text.Trim().ToString();
                            int    k = 0;
                            for (int i = 0; i < s.Length; i++)
                            {
                                byte b = (byte)s[i];
                                //                                Console.Write(b);
                                str = Reverse(str);
                                //                      System.Console.WriteLine(str);
                                int x = (B46[(char)b] - (str[k] % 128) + 128) % 128;
                                //                    System.Console.WriteLine((char)x);
                                str = Reverse(str);
                                //                  System.Console.WriteLine(str);
                                x = (x - (str[k] % 128) + 128) % 128;
                                //                System.Console.WriteLine((char)x);
                                k     = (k + 1) % str.Length;
                                str1 += (basic_dec((char)x));
                            }
                            richTextBox1.Text = str1;
                        }
                    }
                }
            }
        }