Exemplo n.º 1
0
 public void Dispose()
 {
     if (_sigHasher != null)
     {
         _sigHasher.Dispose();
     }
 }
Exemplo n.º 2
0
        private static string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters)
        {
            normalizedUrl = null;
            normalizedRequestParameters = null;

            switch (signatureType)
            {
            case SignatureTypes.PlainText:
                return(HttpUtility.UrlEncode(string.Format(CultureInfo.InvariantCulture, "{0}&{1}", consumerSecret, tokenSecret)));

            case SignatureTypes.HmacSha1:
                string signatureBase = GenerateSignatureBase(url, consumerKey, token, httpMethod, timeStamp, nonce, HmacSha1SignatureType, out normalizedUrl, out normalizedRequestParameters);

                var hmacsha1 = new HMACSHA1
                {
                    Key = Encoding.ASCII.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}&{1}", UrlEncode(consumerSecret),
                                                                string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)))
                };

                var signatureUsingHash = GenerateSignatureUsingHash(signatureBase, hmacsha1);
                hmacsha1.Dispose();
                return(signatureUsingHash);

            case SignatureTypes.RsaSha1:
                throw new NotSupportedException();

            default:
                throw new ArgumentException("Unknown signature type", "signatureType");
            }
        }
Exemplo n.º 3
0
 public void Dispose()
 {
     sha1.Dispose();
     aesProvider.Dispose();
     finalsha.Dispose();
     shaSalt.Dispose();
 }
Exemplo n.º 4
0
        public static int GenerateToken(string base32Key)
        {
            var keySize = Encoding.UTF8.GetByteCount(base32Key);

            int bufferSize = (keySize + 7) / 8 * 5;

            byte[] decoded = new byte[bufferSize];

            int         hmacResSize = HMAC_RES_SIZE;
            Span <byte> hmacRes     = stackalloc byte[HMAC_RES_SIZE];
            long        timestamp   = Time.GetTimestamp(Time.Now) / 30;

            Span <byte> challenge = stackalloc byte[8];

            for (int i = 7; i >= 0; i--, timestamp >>= 8)
            {
                challenge[i] = (byte)timestamp;
            }

            Base32Decode(base32Key, decoded);

            var hmac = new HMACSHA1(decoded);

            hmac.TryComputeHash(challenge, hmacRes, out hmacResSize);
            hmac.Dispose();

            int offset    = hmacRes[19] & 0xF;
            int truncHash = (hmacRes[offset] << 24) | (hmacRes[offset + 1] << 16) | (hmacRes[offset + 2] << 8) | (hmacRes[offset + 3]);

            truncHash &= 0x7FFFFFFF;

            return(truncHash % 1000000);
        }
Exemplo n.º 5
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         _hmac?.Dispose();
     }
 }
Exemplo n.º 6
0
        public void Dispose()
        {
            DecryptSHA1.Dispose();
            EncryptSHA1.Dispose();

            IsInitialized = false;
        }
Exemplo n.º 7
0
        /// <summary>
        /// Generate the compelte signature by hashins the base with the secret
        /// </summary>
        /// <param name="SignatureBase"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        private static string GenerateSignature(string SignatureBase, string secret)
        {
            HMACSHA1 hmacsha1 = new HMACSHA1();

            hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", HttpUtility.UrlEncode(secret), ""));
            byte[] hashBytes = hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(SignatureBase));
            hmacsha1.Dispose();
            return(Convert.ToBase64String(hashBytes));
        }
Exemplo n.º 8
0
        public void Dispose()
        {
            SARC4Encrypt.Dispose();
            SARC4Decrypt.Dispose();
            DecryptSHA1.Dispose();
            EncryptSHA1.Dispose();

            GC.SuppressFinalize(this);

            IsInitialized = false;
        }
Exemplo n.º 9
0
        public void Dispose()
        {
            if (_receiveLoopCancellation != null)
            {
                _receiveLoopCancellation.Cancel();
                _receiveLoopCancellation.Dispose();
            }

            _webSocket?.Dispose();
            _hmac?.Dispose();
        }
        public string HashPassword(string password)
        {
            var hash = new HMACSHA1 {
                Key = Encoding.Unicode.GetBytes(password)
            };

            var encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

            hash.Dispose();

            return(encodedPassword);
        }
Exemplo n.º 11
0
        private string CalcSignature(BasePacket parameter)
        {
            SortedDictionary <string, string> dicSorted = new SortedDictionary <string, string>();

            foreach (string item in dicParameter.Keys)
            {
                if (!string.IsNullOrEmpty(dicParameter[item]) && !item.EndsWith("_secret") && !item.EndsWith("_signature")
                    /*&& !item.EndsWith("_verifier") && !item.EndsWith("_callback")*/)
                {
                    dicSorted[item] = dicParameter[item];
                }
            }
            foreach (string item in parameter.dicParams.Keys)
            {
                if (!string.IsNullOrEmpty(parameter.dicParams[item]) && !item.EndsWith("_secret") && !item.EndsWith("_signature"))
                {
                    dicSorted[item] = parameter.dicParams[item];
                }
            }

            StringBuilder sb = new StringBuilder();

            foreach (string item in dicSorted.Keys)
            {
                sb.Append(item);
                sb.Append("=");
                CalcParamUri(sb, dicSorted[item]);
                sb.Append("&");
            }
            sb.Remove(sb.Length - 1, 1);            //마지막 & 지우기

            string baseStr = CalcBaseString(parameter.method, parameter.url, sb.ToString());
            string signKey = GetSignKey();            //Generate.ConsumerSecret + "&" + Generate.TokenSecret;//이게 문제
            string ret     = string.Empty;

            using (HMACSHA1 sha = new HMACSHA1(Encoding.ASCII.GetBytes(signKey)))
            {
                byte[] byteArray = Encoding.ASCII.GetBytes(baseStr);
                //MemoryStream stream = new MemoryStream(byteArray);//버그?
                byte[] hashvalue = sha.ComputeHash(byteArray);
                ret = Convert.ToBase64String(hashvalue);
                sha.Dispose();
            }
            return(ret);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Verify SHA-1 authentication of a packet.
        /// </summary>
        /// <param name="authKey">Authentication key (not password)</param>
        /// <param name="authenticationParameters">Authentication parameters extracted from the packet being authenticated</param>
        /// <param name="wholeMessage">Entire packet being authenticated</param>
        /// <returns>True on authentication success, otherwise false</returns>
        public bool authenticateIncomingMsg(byte[] authKey, byte[] authenticationParameters, MutableByte wholeMessage)
        {
            HMACSHA1 sha = new HMACSHA1(authKey);

            byte[]      hash   = sha.ComputeHash(wholeMessage);
            MutableByte myhash = new MutableByte(hash, 12);

#if !NETCOREAPP11 && !NETSTANDARD15
            sha.Clear();             // release resources
#else
            sha.Dispose();
#endif
            if (myhash.Equals(authenticationParameters))
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Authenticate packet and return authentication parameters value to the caller
        /// </summary>
        /// <param name="authKey">Authentication key (not password)</param>
        /// <param name="wholeMessage">Message to authenticate</param>
        /// <returns>Authentication parameters value</returns>
        public byte[] authenticate(byte[] authKey, byte[] wholeMessage)
        {
            byte[] result = new byte[12];

            HMACSHA1 sha = new HMACSHA1(authKey);

            byte[] hash = sha.ComputeHash(wholeMessage);
            // copy 12 bytes of the hash into the wholeMessage
            for (int i = 0; i < 12; i++)
            {
                result[i] = hash[i];
            }
#if !NETCOREAPP11 && !NETSTANDARD15
            sha.Clear();             // release resources
#else
            sha.Dispose();
#endif
            return(result);
        }
Exemplo n.º 14
0
        /// <summary>
        /// verified the authenticator code
        /// </summary>
        /// <param name="key">base32 key</param>
        /// <param name="inputCode">input from google authenticator</param>
        /// <returns></returns>
        public static bool Verified(string key, string inputCode)
        {
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            //30 sec
            long timeBase = timestamp / 30;

            byte[] byteMsg = new byte[8];

            for (int i = 1; i <= byteMsg.Length; i++)
            {
                byteMsg[byteMsg.Length - i] = (byte)(timeBase & 0xff);
                timeBase = timeBase >> 8;
            }


            byte[] byteKey = Base32Encoding.Standard.ToBytes(key);

            HMACSHA1 hmacsha1 = new HMACSHA1(byteKey);

            byte[] hashResult = hmacsha1.ComputeHash(byteMsg);

            int offset = hashResult[hashResult.Length - 1] & 0xf;

            int result = (hashResult[offset] & 0x7f) << 24 |
                         (hashResult[offset + 1] & 0xff) << 16 |
                         (hashResult[offset + 2] & 0xff) << 8 |
                         (hashResult[offset + 3] & 0xff);

            //show 6 digits of code only
            string code = (result % Math.Pow(10, NUMBER_DIGITS)).ToString();

            hmacsha1.Dispose();

            //add 0's if less than 6 digits
            while (code.Length < NUMBER_DIGITS)
            {
                code = "0" + code;
            }
            return(code.Equals(inputCode));
        }
Exemplo n.º 15
0
        public void TestHMACs2(int key, int value)
        {
            byte[] keyB   = new byte[key];
            byte[] valueB = new byte[value];

            rng.GetBytes(keyB);
            rng.GetBytes(valueB);

            var code = HMAC <Sha1Digest> .Compute(keyB, valueB);

            HMACSHA1 hmac1 = new HMACSHA1(keyB);
            var      code2 = hmac1.ComputeHash(valueB);

            if (!code.SequenceEqual(code2))
            {
                throw new Exception();
            }


            hmac1.Dispose();
        }
Exemplo n.º 16
0
        public async Task <string> TranslateAsync(string sourceText, string desLang, string srcLang)
        {
            if (sourceText == "" || desLang == "" || srcLang == "")
            {
                errorInfo = "Param Missing";
                return(null);
            }

            // 原文
            string q = HttpUtility.UrlEncode(sourceText);

            string retString;

            string salt = CommonFunction.RD.Next(100000).ToString();

            string url = "https://tmt.tencentcloudapi.com/?";

            // 签名,参数使用未URL编码的值
            var sb = new StringBuilder()
                     .Append("Action=TextTranslate")
                     .Append("&Nonce=").Append(salt)
                     .Append("&ProjectId=0")
                     .Append("&Region=ap-shanghai")
                     .Append("&SecretId=").Append(SecretId)
                     .Append("&Source=").Append(srcLang)
                     .Append("&SourceText=").Append(sourceText)
                     .Append("&Target=").Append(desLang)
                     .Append("&Timestamp=").Append(CommonFunction.GetTimeStamp())
                     .Append("&Version=2018-03-21");
            string req = sb.ToString();

            HMACSHA1 hmac = new HMACSHA1()
            {
                Key = Encoding.UTF8.GetBytes(SecretKey)
            };

            byte[] data   = Encoding.UTF8.GetBytes("GETtmt.tencentcloudapi.com/?" + req);
            var    result = hmac.ComputeHash(data);

            hmac.Dispose();

            // 请求参数,参数使用URL编码后的值
            sb = new StringBuilder()
                 .Append("Action=TextTranslate")
                 .Append("&Nonce=").Append(salt)
                 .Append("&ProjectId=0")
                 .Append("&Region=ap-shanghai")
                 .Append("&SecretId=").Append(SecretId)
                 .Append("&Source=").Append(srcLang)
                 .Append("&SourceText=").Append(q)
                 .Append("&Target=").Append(desLang)
                 .Append("&Timestamp=").Append(CommonFunction.GetTimeStamp())
                 .Append("&Version=2018-03-21")
                 .Append("&Signature=").Append(HttpUtility.UrlEncode(Convert.ToBase64String(result)));
            req = sb.ToString();

            var hc = CommonFunction.GetHttpClient();

            try
            {
                retString = await hc.GetStringAsync(url + req);
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }
            catch (TaskCanceledException ex)
            {
                errorInfo = ex.Message;
                return(null);
            }

            TencentOldTransOutInfo oinfo = JsonConvert.DeserializeObject <TencentOldTransOutInfo>(retString);

            if (oinfo.Response.Error == null)
            {
                //得到翻译结果
                return(oinfo.Response.TargetText);
            }
            else
            {
                errorInfo = "ErrorID:" + oinfo.Response.Error.Value.Code + " ErrorInfo:" + oinfo.Response.Error.Value.Message;
                return(null);
            }
        }
Exemplo n.º 17
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);
        }