Esempio n. 1
0
        internal void SignatureRequest()
        {
            QueryCollection queries = new QueryCollection();

            PropertyInfo[] propertyInfos = this.GetType().GetProperties(InstanceBindFlags);
            if (propertyInfos == null || propertyInfos.Length == 0)
            {
                throw new Exception("Can not get class properties.");
            }
            foreach (var item in propertyInfos)
            {
                string name = item.Name;
                if (name == "IsSignature" || name == "Signature")
                {
                    continue;
                }
                object valueObj = item.GetValue(this, null);
                string value    = valueObj?.ToString();
                queries.Add(name, value);
            }
            queries.Sort((x, y) =>
            {
                for (int i = 0; i < (x.Key.Length < y.Key.Length ? x.Key.Length : y.Key.Length); i++)
                {
                    int val = x.Key[i] - y.Key[i];
                    if (val != 0)
                    {
                        return(val);
                    }
                    else
                    {
                        continue;
                    }
                }
                return(0);
            });

            StringBuilder sb = new StringBuilder();

            sb.Append(AppConfig.DdnsApiRequestMethod);
            sb.Append(AppConfig.DdnsApiRequestUrl.Replace("https://", ""));
            sb.Append("?");
            sb.Append(string.Join("&", queries.Select(t =>
            {
                //不能对中文进行URL Encode
                if (string.Equals(t.Key, "domain", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(t.Key, "recordline", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(t.Key, "subDomain", StringComparison.OrdinalIgnoreCase))
                {
                    return($"{t.Key}={(t.Value ?? "")}");
                }
                return($"{HttpUtil.UrlEncode(t.Key)}={(t.Value == null ? "" : HttpUtil.UrlEncode(t.Value))}");
            })));

            HMAC mac = null;

            if (SignatureMethod == SignatureType.HmacSHA1)
            {
                mac = new HMACSHA1(Encoding.UTF8.GetBytes(AppConfig.SecretKey));
            }
            else
            {
                mac = new HMACSHA256(Encoding.UTF8.GetBytes(AppConfig.SecretKey));
            }
            byte[] hashBytes = mac.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()));
            mac.Dispose();
            Signature   = HttpUtil.UrlEncode(Convert.ToBase64String(hashBytes));
            IsSignature = true;
        }