示例#1
0
 /// <summary>
 /// Computes a new hash of <paramref name="data"/> usign the <paramref name="key"/> specified.
 /// </summary>
 /// <param name="key">A byte array containing the key (secret) to use to generate a hash.</param>
 /// <param name="data">A byte arrasy containing the data to be hashed.</param>
 /// <returns>A new byte array containing the hash result.</returns>
 public byte[] ComputeHash(byte[] key, byte[] data)
 {
     using (var hasher = new System.Security.Cryptography.HMACSHA1(key))
     {
         return(hasher.ComputeHash(data));
     }
 }
示例#2
0
 /// <summary>
 /// Converts a string into a SHA-1 hash using a hash message authentication code (HMAC). Pass the secret key for the message as a parameter to the function.
 /// </summary>
 /// <param name="text">The input string</param>
 /// <param name="secretKey">The secret key</param>
 /// <returns>The `SHA-1` hash of the input string using a hash message authentication code (HMAC)</returns>
 /// <remarks>
 /// ```scriban-html
 /// {{ "test" | string.hmac_sha1 "secret" }}
 /// ```
 /// ```html
 /// 1aa349585ed7ecbd3b9c486a30067e395ca4b356
 /// ```
 /// </remarks>
 public static string HmacSha1(string text, string secretKey)
 {
     using (var hsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(secretKey ?? string.Empty)))
     {
         return(Hash(hsha1, text));
     }
 }
示例#3
0
 public static string Sign(string value, string key)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(key)))
     {
         return(UrlEncodeTo64(hmac.ComputeHash(Encoding.ASCII.GetBytes(value))));
     }
 }
示例#4
0
        /// <summary>
        /// Method to Sign your app key
        /// This should be called with each URI resource
        /// before sending any HTTP command to the remote server
        /// </summary>
        /// <param name="url"></param>
        /// <param name="app"></param>
        /// <returns></returns>
        public static string Sign(string url)
        {
            try
            {
                // Add appSID parameter.
                UriBuilder builder = new UriBuilder(url);
                if (builder.Query != null && builder.Query.Length > 1)
                    builder.Query = builder.Query.Substring(1) + "&appSID=" + AsposeApp.AppSID;
                else
                    builder.Query = "appSID=" + AsposeApp.AppSID;
                // Remove final slash here as it can be added automatically.
                builder.Path = builder.Path.TrimEnd('/');
                // Compute the hash.

                byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(AsposeApp.AppKey);

                System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(privateKey);
                //System.Text.ASCIIEncoding
                byte[] sequence = System.Text.ASCIIEncoding.ASCII.GetBytes(builder.Uri.AbsoluteUri);
                byte[] hash = algorithm.ComputeHash(sequence);
                string signature = Convert.ToBase64String(hash);
                // Remove invalid symbols.
                signature = signature.TrimEnd('=');
                signature = System.Web.HttpUtility.UrlEncode(signature);
                // Convert codes to upper case as they can be updated automatically.
                signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
                //signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", delegate(string e){ e.Value.ToUpper()});
                // Add the signature to query string.
                return string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public void AuthenticateRequest(WebRequest request, string base64Secret)
        {
            var secret = Convert.FromBase64String(base64Secret);
            var hashingAlg = new System.Security.Cryptography.HMACSHA1(secret);

            var canonHeaders = request.Headers.AllKeys
                .Where(h => h.StartsWith("x-emc", StringComparison.InvariantCultureIgnoreCase))
                .OrderBy(h => h.ToLowerInvariant())
                .Select(h => h + ":" + request.Headers[h].Trim())
                .Aggregate(string.Empty, (current, header) => current + header + "\n")
                .TrimEnd('\n');

            var contentType = request.ContentType ?? string.Empty;
            var range = request.Headers["range"] ?? string.Empty;
            var date = request.Headers["date"] ?? string.Empty;
            var requestRelativeUri = Uri.UnescapeDataString(request.RequestUri.Segments.Aggregate(string.Empty, (current, segment) => current + segment) + request.RequestUri.Query);

            var hashString = request.Method + "\n" +
                             contentType + "\n" +
                             range + "\n" +
                             date + "\n" +
                             requestRelativeUri + "\n" +
                             canonHeaders;

            var signature = Convert.ToBase64String(hashingAlg.ComputeHash(Encoding.Default.GetBytes(hashString)));
            request.Headers.Add("x-emc-signature", signature);
        }
示例#6
0
        private string GenerateSignature(string encodedText)
        {
            var key  = Environment.GetEnvironmentVariable("SECRET_ACCESS_KEY");
            var hash = new System.Security.Cryptography.HMACSHA1(new ASCIIEncoding().GetBytes(key));

            return(Convert.ToBase64String(hash.ComputeHash(new ASCIIEncoding().GetBytes(encodedText))));
        }
示例#7
0
        public void AuthenticateRequest(WebRequest request, string base64Secret)
        {
            var secret     = Convert.FromBase64String(base64Secret);
            var hashingAlg = new System.Security.Cryptography.HMACSHA1(secret);

            var canonHeaders = request.Headers.AllKeys
                               .Where(h => h.StartsWith("x-emc", StringComparison.InvariantCultureIgnoreCase))
                               .OrderBy(h => h.ToLowerInvariant())
                               .Select(h => h + ":" + request.Headers[h].Trim())
                               .Aggregate(string.Empty, (current, header) => current + header + "\n")
                               .TrimEnd('\n');

            var contentType        = request.ContentType ?? string.Empty;
            var range              = request.Headers["range"] ?? string.Empty;
            var date               = request.Headers["date"] ?? string.Empty;
            var requestRelativeUri = Uri.UnescapeDataString(request.RequestUri.Segments.Aggregate(string.Empty, (current, segment) => current + segment) + request.RequestUri.Query);

            var hashString = request.Method + "\n" +
                             contentType + "\n" +
                             range + "\n" +
                             date + "\n" +
                             requestRelativeUri + "\n" +
                             canonHeaders;

            var signature = Convert.ToBase64String(hashingAlg.ComputeHash(Encoding.Default.GetBytes(hashString)));

            request.Headers.Add("x-emc-signature", signature);
        }
        private static bool IsValidGithubMessage(string requestBody, string githubSignature, dynamic data)
        {
            if (requestBody == null)
            {
                throw new ArgumentNullException(nameof(requestBody));
            }

            var bodyBytes = System.Text.Encoding.ASCII.GetBytes(requestBody);
            // string requestBody = System.Text.Encoding.UTF8.GetString(bodyBytes);
            string signature;

            var repoSecret = Environment.GetEnvironmentVariable(("SECRET_" + data.repository.name).ToUpper());

            if (repoSecret == null)
            {
                _log.Info("Secret not found for repo " + data.repository.name);
                return(false);
            }

            byte[] keyParts = System.Text.Encoding.ASCII.GetBytes(repoSecret);

            using (var hmac = new System.Security.Cryptography.HMACSHA1(keyParts))
            {
                // We'll be a little lazy and take the performance hit of BitConverter
                signature = "sha1=" + BitConverter.ToString(
                    hmac.ComputeHash(bodyBytes)).Replace("-", "");
            }

            return(string.Compare(githubSignature, signature, true) == 0);
        }
示例#9
0
        public static int GetVerificationCode(int value, string secretStr)
        {
            byte[] val = new byte[8];
            for (int i = 8; (i--) != 0; value >>= 8)
            {
                val[i] = (byte)(value & 0xFF);
            }

            byte[] secret = Base32Encoding.ToBytes(secretStr);
            if (secret == null || secret.Length == 0)
            {
                return(-1);
            }

            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(secret, true);
            byte[] hash = hmac.ComputeHash(val);

            int  offset        = hash[SHA1_DIGEST_LENGTH - 1] & 0xF;
            uint truncatedHash = 0;

            for (int i = 0; i < 4; ++i)
            {
                truncatedHash <<= 8;
                truncatedHash  |= hash[offset + i];
            }
            truncatedHash &= 0x7FFFFFFF;
            truncatedHash %= 1000000;
            return((int)truncatedHash);
        }
示例#10
0
        public void ComputeHMACShortTermCredentials(byte [] bMsgBytes, int nLengthWithoutMessageIntegrity, string strPassword)
        {
            byte[] bKey = System.Text.UTF8Encoding.UTF8.GetBytes(strPassword);

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(bKey);
            HMAC = sha1.ComputeHash(bMsgBytes, 0, nLengthWithoutMessageIntegrity);
        }
示例#11
0
 string HmacSha1(string key, string text)
 {
     using (var mac = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(key)))
     {
         return(mac.ComputeHash(Encoding.UTF8.GetBytes(text)).Aggregate(string.Empty, (s, e) => { return s + e.ToString("x2"); }, m => m));
     }
 }
        /// <summary>
        /// Calculates the signature for an OAuth call.
        /// </summary>
        /// <param name="method">POST or GET method.</param>
        /// <param name="url">The URL the request will be sent to.</param>
        /// <param name="parameters">Parameters to be added to the signature.</param>
        /// <param name="tokenSecret">The token secret (either request or access) for generating the SHA-1 key.</param>
        /// <returns>Base64 encoded SHA-1 hash.</returns>
        public string OAuthCalculateSignature(string method, string url, Dictionary<string, string> parameters, string oAuthAccessTokenSecret)
        {
            string baseString = "";
            string key = ApiSecret + "&" + oAuthAccessTokenSecret;
            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

            SortedList<string, string> sorted = parameters.ToSortedList();

            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append("=");
                sb.Append(pair.Value.ToEscapeOAuth());
                sb.Append("&");
            }

            //remove last &
            sb.Remove(sb.Length - 1, 1);

            baseString = method + "&" + url.ToEscapeOAuth() + "&" + sb.ToString().ToEscapeOAuth();

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(keyBytes);

            byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(baseString));

            string hash = Convert.ToBase64String(hashBytes);

            //Debug.WriteLine("key  = " + key);
            //Debug.WriteLine("base = " + baseString);
            //Debug.WriteLine("sig  = " + hash);

            return hash;
        }
示例#13
0
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            string qry = @"
    SELECT 
         L.[Id]
        ,L.[Password] 
        ,L.[Guid]
    FROM 
        [UserLogin] L
        INNER JOIN [EntityType] ET ON ET.[Id] = L.[entityTypeId] AND ET.[Guid] = '4E9B798F-BB68-4C0E-9707-0928D15AB020'
";
            var    rdr = Rock.Data.DbService.GetDataReader(qry, System.Data.CommandType.Text, null);

            while (rdr.Read())
            {
                var hash = new System.Security.Cryptography.HMACSHA1();
                hash.Key = HexToByte(rdr["Guid"].ToString().Replace("-", ""));

                string oldPassword = rdr["Password"].ToString();
                string newPassword = Convert.ToBase64String(hash.ComputeHash(Convert.FromBase64String(oldPassword)));

                string updateQry = string.Format(@"
    UPDATE 
        [UserLogin]
    SET
        [Password] = '{0}'
    WHERE
        [Id] = {1}
", newPassword, rdr["Id"].ToString());

                Rock.Data.DbService.ExecuteCommand(updateQry, System.Data.CommandType.Text);
            }

            rdr.Close();
        }
示例#14
0
        private static string GetContent(byte[] secret, HttpListenerRequest request)
        {
            var ms = new System.IO.MemoryStream();

            request.InputStream.CopyTo(ms);
            byte[] bytes = ms.ToArray();
            (request.InputStream as IDisposable).Dispose();

            var signature = request.Headers.Get("X-Signature");

            if (secret != null)
            {
                using (var hmac = new System.Security.Cryptography.HMACSHA1(secret)) {
                    hmac.Initialize();
                    string result = BitConverter.ToString(
                        hmac.ComputeHash(bytes, 0, bytes.Length)
                        ).Replace("-", "");
                    if (!string.Equals(
                            signature,
                            $"sha1={result}",
                            StringComparison.OrdinalIgnoreCase
                            ))
                    {
                        return(null);
                    }
                }
            }
            return(request.ContentEncoding.GetString(bytes));
        }
 /// <summary>
 /// Hmac signin with
 /// </summary>
 /// <param name="dataToSign">payoad to compute</param>
 /// <param name="keyBody">key</param>
 /// <returns>bytes of computehash</returns>
 private static byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
 {
     using (var hmacAlgorithm = new System.Security.Cryptography.HMACSHA1(keyBody))
     {
         return(hmacAlgorithm.ComputeHash(dataToSign));
     }
 }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            string qry = @"
            SELECT
             L.[Id]
            ,L.[Password]
            ,L.[Guid]
            FROM
            [UserLogin] L
            INNER JOIN [EntityType] ET ON ET.[Id] = L.[entityTypeId] AND ET.[Guid] = '4E9B798F-BB68-4C0E-9707-0928D15AB020'
            ";
            var rdr = Rock.Data.DbService.GetDataReader( qry, System.Data.CommandType.Text, null );
            while ( rdr.Read() )
            {
                var hash = new System.Security.Cryptography.HMACSHA1();
                hash.Key = HexToByte( rdr["Guid"].ToString().Replace( "-", "" ) );

                string oldPassword = rdr["Password"].ToString();
                string newPassword = Convert.ToBase64String( hash.ComputeHash( Convert.FromBase64String( oldPassword ) ) );

                string updateQry = string.Format( @"
            UPDATE
            [UserLogin]
            SET
            [Password] = '{0}'
            WHERE
            [Id] = {1}
            ", newPassword, rdr["Id"].ToString() );

                Rock.Data.DbService.ExecuteCommand( updateQry, System.Data.CommandType.Text );
            }

            rdr.Close();
        }
示例#17
0
        string GetDownloadAuthoritionKey(string filePath, DateTime?expired)
        {
            var bucket    = _options.Bucket;
            var appId     = _options.AppId;
            var secretId  = _options.SecretId;
            var secretKey = _options.SecretKey;

            int e;

            if (expired.HasValue)
            {
                e = Convert.ToInt32(Math.Floor(DateTimeUtils.ToUnixTime(expired.Value)));
            }
            else
            {
                e = 0;
            }

            string fileId = filePath;

            var rdm       = new Random().Next(Int32.MaxValue);
            var plainText = "a=" + appId + "&k=" + secretId + "&e=" + e + "&t=" + Convert.ToInt32(Math.Floor(DateTimeUtils.ToUnixTime(DateTime.Now))) + "&r=" + rdm + "&f=" + fileId + "&b=" + bucket;

            using (var mac = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(secretKey)))
            {
                var hash  = mac.ComputeHash(Encoding.UTF8.GetBytes(plainText));
                var pText = Encoding.UTF8.GetBytes(plainText);
                var all   = new byte[hash.Length + pText.Length];
                Array.Copy(hash, 0, all, 0, hash.Length);
                Array.Copy(pText, 0, all, hash.Length, pText.Length);
                return(Convert.ToBase64String(all));
            }
        }
 public void AuthenticateRequest(WebRequest request, string base64Secret)
 {
     var secret = Convert.FromBase64String(base64Secret);
     //var url = Encoding.Default.GetBytes(request.RequestUri.ToString());
     var hashingAlg = new System.Security.Cryptography.HMACSHA1(secret);
     Convert.ToBase64String(hashingAlg.ComputeHash(Encoding.UTF8.GetBytes(request.RequestUri.ToString())));
 }
示例#19
0
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            var query = string.Format("{0}{1}devid={2}", request.RequestUri.PathAndQuery, request.RequestUri.PathAndQuery.Contains("?") ? "&" : "?", this.UserId);

            var encoding = new ASCIIEncoding();

            // encode key
            byte[] apiKeyBytes = encoding.GetBytes(this.ApiKey);
            // encode url
            byte[] queryBytes = encoding.GetBytes(query);
            byte[] tokenBytes = new System.Security.Cryptography.HMACSHA1(apiKeyBytes).ComputeHash(queryBytes);
            var    sb         = new StringBuilder();

            // convert signature to string
            Array.ForEach <byte>(tokenBytes, x => sb.Append(x.ToString("X2")));
            // add signature to url
            var signature = string.Format("{0}&signature={1}", query, sb.ToString());

            var r = $"{request.RequestUri.GetLeftPart(UriPartial.Authority)}{signature}";

            request.RequestUri = new Uri(r);

            return(await base.SendAsync(request, cancellationToken));
        }
 private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA1()){
         passwordSalt = hmac.Key;
         passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
     }
 }
示例#21
0
        /// <summary>
        /// Generates AuthenticationHeaderValue to authorize requests to twitter API.
        /// (https://developer.twitter.com/en/docs/basics/authentication/guides/authorizing-a-request)
        /// </summary>
        /// <param name="requestParameters">The custom parameters of the request.</param>
        /// <param name="httpMethod">The http method of the request.</param>
        /// <param name="url">The url to which the request will be made.</param>
        /// <returns>AuthenticationHeaderValue with the parameters to authorize the request.</returns>
        public AuthenticationHeaderValue getAuthenticationHeaderValue(
            Dictionary <string, string> requestParameters, string httpMethod, string url)
        {
            //USER-AUTHENTICATION(https://developer.twitter.com/en/docs/basics/authentication/guides/authorizing-a-request)
            //CREATE SIGNATURE(https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature.html)

            // 1) Percent Encode all parameters:
            Dictionary <string, string> allEncodedParameters = new Dictionary <string, string>();

            foreach (var x in OAuthUtil.paramatersDic.Concat(requestParameters))
            {
                allEncodedParameters.Add(PercentEncode(x.Key), PercentEncode(x.Value));
            }

            // 2) get signature base string:
            string allParameterString    = AggregateParameters(allEncodedParameters, "&");
            string signature_base_string = PercentEncode(httpMethod) + "&" + PercentEncode(url) + "&" + PercentEncode(allParameterString);

            // 3) get signing key:
            string signingKey = PercentEncode(OAuthUtil.OAUTH_CONSUMER_SECRET) + "&" + PercentEncode(OAuthUtil.OAUTH_SECRET);

            // 4) calculate oauth_signature [HMACSHA1]:
            var    aux             = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(signingKey));
            var    hashValue       = aux.ComputeHash(Encoding.ASCII.GetBytes(signature_base_string));
            string oauth_signature = Convert.ToBase64String(hashValue);

            // 5) generate AuthenticationHeaderValue:
            Dictionary <string, string> oauthDic = new Dictionary <string, string>(allEncodedParameters); //include request parameters!

            oauthDic.Add(PercentEncode("oauth_signature"), PercentEncode(oauth_signature));
            string oauthFinalString = AggregateParameters(oauthDic, ", ", true);

            return(new System.Net.Http.Headers.AuthenticationHeaderValue("OAuth", oauthFinalString));
        }
示例#22
0
 public static string sign(String data, String appSecret)
 {
     System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
     hmacsha1.Key = Encoding.UTF8.GetBytes(appSecret);
     byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
     byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
     return byteToHexStr(hashBytes);
 }
示例#23
0
 public static string sign(String data, String appSecret)
 {
     System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
     hmacsha1.Key = Encoding.UTF8.GetBytes(appSecret);
     byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
     byte[] hashBytes  = hmacsha1.ComputeHash(dataBuffer);
     return(byteToHexStr(hashBytes));
 }
示例#24
0
 public static byte[] SHA1(byte[] Data, byte[] Key, int Offset, int Length)
 {
     byte[] destinationArray = new byte[Data.Length];
     Array.Copy(Data, Offset, destinationArray, 0, Data.Length);
     byte[] array = new System.Security.Cryptography.HMACSHA1(Key).ComputeHash(destinationArray);
     Array.Resize <byte>(ref array, 0x10);
     return(array);
 }
示例#25
0
        internal static string Sha1Hash(byte[] key, string basestring)
        {
            var sha1 = new System.Security.Cryptography.HMACSHA1(key);

            var hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(basestring));

            return(Convert.ToBase64String(hashBytes));
        }
示例#26
0
 private string Hmac_Sha1AndBase64(string Source, string SecretKey)
 {
     System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
     hmacsha1.Key = System.Text.Encoding.ASCII.GetBytes(SecretKey);
     byte[] dataBuffer = System.Text.Encoding.ASCII.GetBytes(Source); //signatureBase要进行签名的基础字符串
     byte[] hashBytes  = hmacsha1.ComputeHash(dataBuffer);
     return(Convert.ToBase64String(hashBytes));
 }
示例#27
0
        public static string HMACSHA1(string value, string salt)
        {
            byte[] inBuf = Encoding.UTF8.GetBytes(value);
            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(salt));
            var hash = sha1.ComputeHash(inBuf);

            return(OtpTools.ByteArrayToHexString(hash));
        }
示例#28
0
            public static String HmacSha1(String value, String key)
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(key);
                var    mac      = new System.Security.Cryptography.HMACSHA1(keyBytes);

                byte[] rawHmac = mac.ComputeHash(Encoding.UTF8.GetBytes(value));
                return(Base64Util.Base64(rawHmac));
            }
示例#29
0
 public static string GetSig(string policyStr, string secretKey)
 {
     policyStr = GetBase64_string(policyStr);
     var signature = new System.Security.Cryptography.HMACSHA1(GetBase64(secretKey));
     var bytes = GetBase64(policyStr);
     var moreBytes = signature.ComputeHash(bytes);
     var encodedCanonical = Convert.ToBase64String(moreBytes);
     return encodedCanonical;
 }
示例#30
0
        public string Encrypt(Encoding encode, string text, string key)
        {
            using (var sha = new System.Security.Cryptography.HMACSHA1(encode.GetBytes(key)))
            {
                var hash = sha.ComputeHash(encode.GetBytes(text));

                return(ByteToString.Convert(hash));
            }
        }
示例#31
0
        public static string HMACSHA1(string text, string passKey)
        {
            var provider = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(passKey));

            provider.Initialize();
            var binary = provider.ComputeHash(Encoding.ASCII.GetBytes(text));

            return(Convert.ToBase64String(binary));
        }
示例#32
0
        public string awsGetSHA1AuthorizationValue(string sAWSSecretAccessKey, string sStringToSign)
        {
            System.Security.Cryptography.HMACSHA1 MySigner =
                new System.Security.Cryptography.HMACSHA1(System.Text.Encoding.UTF8.GetBytes(sAWSSecretAccessKey));
            string SignatureValue =
                Convert.ToBase64String(MySigner.ComputeHash(System.Text.Encoding.UTF8.GetBytes(sStringToSign)));

            return(SignatureValue);
        }
        public static byte[] GenerateHMACSHA1Signature(this string content, string sigKey)
        {
            var hmac = new System.Security.Cryptography.HMACSHA1();

            hmac.Key = Encoding.UTF8.GetBytes(sigKey);
            var contentBytes = Encoding.UTF8.GetBytes(content);

            return(hmac.ComputeHash(contentBytes));
        }
        /// <summary>
        /// HmacSha1签名算法
        /// </summary>
        /// <param name="key">密钥</param>
        /// <param name="data">要签名的数据</param>
        /// <returns></returns>
        private static string HmacSha1Sign(string key, string data)
        {
            var signer = new System.Security.Cryptography.HMACSHA1();


            signer.Key = Encoding.UTF8.GetBytes(key.ToCharArray());
            return(Convert.ToBase64String(
                       signer.ComputeHash(Encoding.UTF8.GetBytes(data.ToCharArray()))));
        }
示例#35
0
        public static string GetSig(string policyStr, string secretKey)
        {
            policyStr = GetBase64_string(policyStr);
            var signature        = new System.Security.Cryptography.HMACSHA1(GetBase64(secretKey));
            var bytes            = GetBase64(policyStr);
            var moreBytes        = signature.ComputeHash(bytes);
            var encodedCanonical = Convert.ToBase64String(moreBytes);

            return(encodedCanonical);
        }
示例#36
0
 public static String Sign(String signatureBaseString, String signingKey)
 {
     Byte[] keyBytes = System.Text.Encoding.ASCII.GetBytes(signingKey);
     using (var myhmacsha1 = new System.Security.Cryptography.HMACSHA1(keyBytes))
     {
         Byte[] byteArray   = System.Text.Encoding.ASCII.GetBytes(signatureBaseString);
         Byte[] signedValue = myhmacsha1.ComputeHash(byteArray);//stream);
         return(Convert.ToBase64String(signedValue));
     }
 }
示例#37
0
        private static string SignCompute(string accessSecret, string stringToSign)
        {
            var hmacsha1 = new System.Security.Cryptography.HMACSHA1 {
                Key = Encoding.UTF8.GetBytes(accessSecret)
            };
            var dataBuffer = Encoding.UTF8.GetBytes(stringToSign);
            var hashBytes  = hmacsha1.ComputeHash(dataBuffer);

            return(Convert.ToBase64String(hashBytes));
        }
        internal static byte[] ComputeHmacSha1Hash(byte[] data, byte[] key)
        {
            Contract.Requires(data != null);
            Contract.Requires(key != null);
            Contract.Ensures(Contract.Result<byte[]>() != null);

            using (var crypto = new System.Security.Cryptography.HMACSHA1(key))
            {
                return crypto.ComputeHash(data);
            }
        }
        public string AuthenticateRequest(string queryString, string base64Secret)
        {
            var queryBytes = Encoding.UTF8.GetBytes(queryString.ToLower());
            var secret = Encoding.UTF8.GetBytes(base64Secret);
            var hashingAlg = new System.Security.Cryptography.HMACSHA1(secret);
            var hashedQuery = hashingAlg.ComputeHash(queryBytes);
            var base64Hash = Convert.ToBase64String(hashedQuery);
            var signature = Uri.EscapeDataString(base64Hash);

            return signature;
        }
示例#40
0
文件: Startup.cs 项目: umicho/arrg
        public void Configuration(IAppBuilder app)
        {
            AsyncOAuth.OAuthUtility.ComputeHash = (key, buffer) =>
            {
                using (var hmac = new System.Security.Cryptography.HMACSHA1(key))
                {
                    return hmac.ComputeHash(buffer);
                }
            };

            ConfigureAuth(app);
        }
        /// <summary>
        /// Gets a HMAC-SHA1 hash for an OAuth request.
        /// </summary>
        /// <param name="consumerSecret">
        /// The consumer secret.
        /// </param>
        /// <param name="oauthSecret">
        /// The OAuth secret.
        /// </param>
        /// <param name="signatureBaseString">
        /// The signature base string for which to compute the hash.
        /// </param>
        /// <returns>
        /// A HMAC-SHA1 hash of <paramref name="signatureBaseString"/>.
        /// </returns>
        public string ComputeHash(string consumerSecret, string oauthSecret, string signatureBaseString)
        {
            if (signatureBaseString == null)
                return null;

            byte[] key = Encoding.UTF8.GetBytes(String.Format("{0}&{1}", consumerSecret, oauthSecret));
            using (System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(key))
            {
                byte[] signatureBaseStringHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));
                return Convert.ToBase64String(signatureBaseStringHash);
            }
        }
示例#42
0
        public void Initialize(byte[] sessionKey)
        {
            // create RC4-drop[1024] stream
            using(HMACSHA1 outputHMAC = new HMACSHA1(encryptionKey))
                encryptionStream = new ARC4(outputHMAC.ComputeHash(sessionKey));
            encryptionStream.Process(new byte[1024], 0, 1024);

            // create RC4-drop[1024] stream
            using(HMACSHA1 inputHMAC = new HMACSHA1(decryptionKey))
                decryptionStream = new ARC4(inputHMAC.ComputeHash(sessionKey));
            decryptionStream.Process(new byte[1024], 0, 1024);

            Status = AuthStatus.Ready;
        }
示例#43
0
        /// <summary>
        /// Creates an HMAC-SHA1 hash from an array of parameters and a security token.
        /// </summary>
        /// <param name="paramList">The parameters to be hashed</param>
        /// <param name="signingKey">The Subscriber's unique signing key.</param>
        /// <returns>The BASE64-encoded HMAC</returns>
        public static string CalculateHMAC(string signingKey, params object[] paramList)
        {
            byte[] key = Encoding.UTF8.GetBytes(signingKey);
            string stringToSign = Canonicalize(paramList);
            byte[] bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
            byte[] signature;

            using (var hmac = new System.Security.Cryptography.HMACSHA1(key))
            {
                signature = hmac.ComputeHash(bytesToSign);
            }

            return System.Convert.ToBase64String(signature);
        }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            // Update the Admin's password to be encoded using the current passwordKey setting in web.config
            string encryptionKey = System.Configuration.ConfigurationManager.AppSettings["PasswordKey"];
            if ( !String.IsNullOrWhiteSpace( encryptionKey ) )
            {
                var hash = new System.Security.Cryptography.HMACSHA1();
                hash.Key = Encryption.HexToByte( encryptionKey );
                string newPassword = Convert.ToBase64String( hash.ComputeHash( System.Text.Encoding.Unicode.GetBytes( "admin" ) ) );

                Sql( string.Format( "Update [UserLogin] SET [Password] = '{0}' WHERE [UserName] = 'Admin'", newPassword ) );
            }

            AddColumn("dbo.GroupLocation", "GroupMemberPersonId", c => c.Int());
            CreateIndex("dbo.GroupLocation", "GroupMemberPersonId");
            AddForeignKey("dbo.GroupLocation", "GroupMemberPersonId", "dbo.Person", "Id", cascadeDelete: true);
        }
示例#45
0
        /// <summary>
        /// Calculates the signature for an OAuth call.
        /// </summary>
        /// <param name="method">POST or GET method.</param>
        /// <param name="url">The URL the request will be sent to.</param>
        /// <param name="parameters">Parameters to be added to the signature.</param>
        /// <param name="tokenSecret">The token secret (either request or access) for generating the SHA-1 key.</param>
        /// <returns>Base64 encoded SHA-1 hash.</returns>
        public string OAuthCalculateSignature(string method, string url, Dictionary<string, string> parameters, string tokenSecret)
        {
            string baseString = "";
            string key = ApiSecret + "&" + tokenSecret;
            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

            #if !SILVERLIGHT
            SortedList<string, string> sorted = new SortedList<string, string>();
            foreach (KeyValuePair<string, string> pair in parameters) { sorted.Add(pair.Key, pair.Value); }
            #else
                var sorted = parameters.OrderBy(p => p.Key);
            #endif

            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append("=");
                sb.Append(UtilityMethods.EscapeOAuthString(pair.Value));
                sb.Append("&");
            }

            sb.Remove(sb.Length - 1, 1);

            baseString = method + "&" + UtilityMethods.EscapeOAuthString(url) + "&" + UtilityMethods.EscapeOAuthString(sb.ToString());

            #if WindowsCE
            FlickrNet.Security.Cryptography.HMACSHA1 sha1 = new FlickrNet.Security.Cryptography.HMACSHA1(keyBytes);
            #else
            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(keyBytes);
            #endif

            byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(baseString));

            string hash = Convert.ToBase64String(hashBytes);

            Debug.WriteLine("key  = " + key);
            Debug.WriteLine("base = " + baseString);
            Debug.WriteLine("sig  = " + hash);

            return hash;
        }
示例#46
0
        public App()
        {
            UnhandledException += Application_UnhandledException;

            InitializeComponent();

            InitializePhoneApplication();

            InitializeLanguage();


            // initialize computehash function
            OAuthUtility.ComputeHash = (key, buffer) => { using (var hmac = new System.Security.Cryptography.HMACSHA1(key)) { return hmac.ComputeHash(buffer); } };

            if (Debugger.IsAttached)
            {
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }
示例#47
0
 public MACSHA1(byte[] key) {
     _algorithm = new HMACSHA1(key);
 }
示例#48
0
 //I have no idea how this works, but it takes the signing key and uses
 //it to create somesort of cryptokey and then applies it to the
 //basestring and then returns the b64 version of it.
 public static string Sign(string signatureBaseString, string signingKey)
 {
     var keyBytes = System.Text.Encoding.ASCII.GetBytes(signingKey);
     using (var myhmacsha1 = new System.Security.Cryptography.HMACSHA1(keyBytes)) {
         byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(signatureBaseString);
         var stream = new MemoryStream(byteArray);
         var signedValue = myhmacsha1.ComputeHash(stream);
         var result = Convert.ToBase64String(signedValue, Base64FormattingOptions.None);
         return result;
     }
 }
示例#49
0
 public static String Sign(String signatureBaseString, String signingKey)
 {
     Byte[] keyBytes = System.Text.Encoding.ASCII.GetBytes(signingKey);
     using (var myhmacsha1 = new System.Security.Cryptography.HMACSHA1(keyBytes))
     {
         Byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(signatureBaseString);
         Byte[] signedValue = myhmacsha1.ComputeHash(byteArray);//stream);
         return Convert.ToBase64String(signedValue);
     }
 }
示例#50
0
        protected void decode(int stanzaSize, bool useDecrypt)
        {
            int size = stanzaSize;
            byte[] data = new byte[size];
            byte[] dataReal = null;
            Buffer.BlockCopy(this.buffer.ToArray(), 0, data, 0, size);

            byte[] packet = new byte[size - 4];

            byte[] hashServerByte = new byte[4];
            Buffer.BlockCopy(data, 0, hashServerByte, 0, 4);
            Buffer.BlockCopy(data, 4, packet, 0, size - 4);

            System.Security.Cryptography.HMACSHA1 h = new System.Security.Cryptography.HMACSHA1(this.Encryptionkey);
            byte[] hashByte = new byte[4];
            Buffer.BlockCopy(h.ComputeHash(packet, 0, packet.Length), 0, hashByte, 0, 4);

            if (hashServerByte.SequenceEqual(hashByte))
            {
                this.buffer.RemoveRange(0, 4);
                if (useDecrypt)
                {
                    dataReal = Encryption.WhatsappDecrypt(this.Encryptionkey, packet);
                }
                else
                {
                    dataReal = Encryption.WhatsappEncrypt(this.Encryptionkey, packet, true);
                    //dataReal = new byte[foo.Length - 4];
                    //Buffer.BlockCopy(foo, 0, dataReal, 0, dataReal.Length);
                }

                for (int i = 0; i < size - 4; i++)
                {
                    this.buffer[i] = dataReal[i];
                }
            }
            else
            {
                throw new Exception("Hash doesnt match");
            }
        }
示例#51
0
 /// <summary>
 /// OAuth認証ヘッダの署名作成
 /// </summary>
 /// <param name="tokenSecret">アクセストークン秘密鍵</param>
 /// <param name="method">HTTPメソッド文字列</param>
 /// <param name="uri">アクセス先Uri</param>
 /// <param name="parameter">クエリ、もしくはPOSTデータ</param>
 /// <returns>署名文字列</returns>
 protected virtual string CreateSignature( string tokenSecret, string method, Uri uri, Dictionary< string, string > parameter )
 {
     // パラメタをソート済みディクショナリに詰替(OAuthの仕様)
     SortedDictionary< string, string > sorted = new SortedDictionary< string, string >( parameter );
     // URLエンコード済みのクエリ形式文字列に変換
     string paramString = this.CreateQueryString( sorted );
     // アクセス先URLの整形
     string url = string.Format( "{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath );
     // 署名のベース文字列生成(&区切り)。クエリ形式文字列は再エンコードする
     string signatureBase = string.Format( "{0}&{1}&{2}", method, this.UrlEncode( url ), this.UrlEncode( paramString ) );
     // 署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと)
     string key = this.UrlEncode( this.consumerSecret ) + "&";
     if ( !string.IsNullOrEmpty( tokenSecret ) )
         key += this.UrlEncode( tokenSecret );
     // 鍵生成&署名生成
     using ( HMACSHA1 hmac = new HMACSHA1( Encoding.ASCII.GetBytes( key ) ) )
     {
         byte[] hash = hmac.ComputeHash( Encoding.ASCII.GetBytes( signatureBase ) );
         return Convert.ToBase64String( hash );
     }
 }
示例#52
0
        public void ComputeHMACShortTermCredentials(byte [] bMsgBytes, int nLengthWithoutMessageIntegrity, string strPassword)
        {
            byte[] bKey = System.Text.UTF8Encoding.UTF8.GetBytes(strPassword);

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(bKey);
            HMAC = sha1.ComputeHash(bMsgBytes, 0, nLengthWithoutMessageIntegrity);
        }
示例#53
0
        public void ComputeHMACShortTermCredentials(STUNMessage msgWithoutHMAC, int nLengthWithoutMessageIntegrity, string strPassword)
        {
            if (strPassword == null)
                strPassword = "";

            /// No MD5 on short term credentials
            byte[] bKey = System.Text.UTF8Encoding.UTF8.GetBytes(strPassword);

            byte[] bBytes = msgWithoutHMAC.Bytes;

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(bKey);
            HMAC = sha1.ComputeHash(bBytes, 0, nLengthWithoutMessageIntegrity);
        }
示例#54
0
        /// <summary>
        /// Generate a Totp using provided binary data.
        /// </summary>
        /// <param name="key">Binary data.</param>
        /// <returns>Time-based One Time Password.</returns>
        public string Generate(byte[] key)
        {
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); //Instanciates a new hash provider with a key.
            byte[] hash = hmac.ComputeHash(GetBytes((ulong)Counter)); //Generates hash from key using counter.
            hmac.Clear(); //Clear hash instance securing the key.

            int offset = hash[hash.Length - 1] & 0xf;           //Math.
            int binary =                                        //Math.
                ((hash[offset] & 0x7f) << 24)                   //Math.
                | ((hash[offset + 1] & 0xff) << 16)             //Math.
                | ((hash[offset + 2] & 0xff) << 8)              //Math.
                | (hash[offset + 3] & 0xff);                    //Math.

            int password = binary % (int)Math.Pow(10, _Length); //Math.
            return password.ToString(new string('0', _Length)); //Math.
        }
        private static byte[] GetHMAC(byte[] key, byte[] counter)
        {
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true);

            return hmac.ComputeHash(counter);
        }
示例#56
0
        string SignString( string toSign, string withKey )
        {
            // sign parameter string
            byte[] sigBase = UTF8Encoding.UTF8.GetBytes ( toSign );
            MemoryStream ms = new MemoryStream();
            ms.Write (sigBase, 0, sigBase.Length );

            byte[] key = UTF8Encoding.UTF8.GetBytes ( withKey );
            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1( key );
            byte[] hashBytes = sha1.ComputeHash ( sigBase );
            return System.Convert.ToBase64String( hashBytes );
        }
示例#57
0
        /// <summary>
        /// Signs the specified data (in string format) with HMAC-SHA1 algorithm and the specified <paramref name="signKey"/>.
        /// </summary>
        /// <param name="data">The data to be signed.</param>
        /// <param name="signKey">The sign key.</param>
        /// <returns>The base64 format signature string.</returns>
        private static string Sign(string data, string signKey)
        {
            var dataBytes = Encoding.ASCII.GetBytes(data);
            var signKeyBytes = Encoding.ASCII.GetBytes(signKey);

            var algorithm = new System.Security.Cryptography.HMACSHA1(signKeyBytes);
            var result = Convert.ToBase64String(algorithm.ComputeHash(dataBytes));

            return result;
        }
示例#58
0
        public void ComputeHMACLongTermCredentials(STUNMessage msgWithoutHMAC, int nLengthWithoutMessageIntegrity, string strUserName, string strRealm, string strPassword)
        {
            string strKey = string.Format("{0}:{1}:{2}", strUserName, strRealm, strPassword);
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] bKey = md5.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(strKey));

            byte[] bBytes = msgWithoutHMAC.Bytes;

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(bKey);
            HMAC = sha1.ComputeHash(bBytes, 0, nLengthWithoutMessageIntegrity);
        }
示例#59
0
        public WebResponse SendRequest(String twitterSreenName)
        {
            try
            {
                var oauth_token = "1594158649-FN2fYJKW8aLJopq81cD0HZbUylDtpmIVbOU9KJR";
                var oauth_token_secret = "0t14X8BvUJmyCu5loN5itfH97QejFjzS0xDTaptu8";
                var oauth_consumer_key = "ui7oDxGwLbcoPzQmUuA";
                var oauth_consumer_secret = "Xe68RKvQ77NpXbmcGvUTvcScLT2wWQTFxrp6ckxUzM";

                var oauth_version = "1.0";
                var oauth_signature_method = "HMAC-SHA1";
                var oauth_nonce = Convert.ToBase64String(
                                                  new System.Text.ASCIIEncoding().GetBytes(
                                                       DateTime.Now.Ticks.ToString()));
                var timeSpan = DateTime.UtcNow
                                                  - new DateTime(1970, 1, 1, 0, 0, 0, 0,
                                                       DateTimeKind.Utc);
                var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
                //var slug = "libraries-and-news-sites";
                var owner_screen_name = twitterSreenName;
                var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
                var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                     "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";

                var baseString = string.Format(baseFormat,
                                            oauth_consumer_key,
                                            oauth_nonce,
                                            oauth_signature_method,
                                            oauth_timestamp,
                                            oauth_token,
                                            oauth_version,
                                            Uri.EscapeDataString(owner_screen_name)

                                            );

                baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url),
                             "&", Uri.EscapeDataString(baseString));

                var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                        "&", Uri.EscapeDataString(oauth_token_secret));

                string oauth_signature;
                using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(System.Text.ASCIIEncoding.ASCII.GetBytes(compositeKey)))
                {
                    oauth_signature = Convert.ToBase64String(
                        hasher.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(baseString)));
                }

                var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", oauth_timestamp=\"{4}\", oauth_token=\"{5}\", oauth_version=\"{6}\"";

                var authHeader = string.Format(headerFormat,
                                        Uri.EscapeDataString(oauth_consumer_key),
                                        Uri.EscapeDataString(oauth_nonce),
                                        Uri.EscapeDataString(oauth_signature),
                                        Uri.EscapeDataString(oauth_signature_method),
                                        Uri.EscapeDataString(oauth_timestamp),
                                        Uri.EscapeDataString(oauth_token),
                                        Uri.EscapeDataString(oauth_version)
                                );

                ServicePointManager.Expect100Continue = false;

                var getBody = "?screen_name=" + Uri.EscapeDataString(owner_screen_name);
                resource_url += getBody;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);

                request.Headers.Add("Authorization", authHeader);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                WebResponse response = request.GetResponse();
                return response;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#60
0
        public static HttpWebRequest AddOAuth(this HttpWebRequest req, string pData, string ConsumerKey, string ConsumerSecret, string AccessToken, string AccessTokenSecret)
        {
            string nonce = new Random().Next(Int16.MaxValue, Int32.MaxValue).ToString("X", System.Globalization.CultureInfo.InvariantCulture);
            string timeStamp = DateTime.UtcNow.ToUnixTimeStamp().ToString();

            // Create the base string. This is the string that will be hashed for the signature.
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("oauth_consumer_key", ConsumerKey);
            param.Add("oauth_nonce", nonce);
            param.Add("oauth_signature_method", "HMAC-SHA1");
            param.Add("oauth_timestamp", timeStamp);
            if (!string.IsNullOrEmpty(AccessToken))
                param.Add("oauth_token", AccessToken);
            param.Add("oauth_version", "1.0");

            pData += req.RequestUri.Query;

            foreach (string kv in pData.Replace("?", "&").Split('&'))
            {
                string[] akv = kv.Split('=');
                if (akv.Length == 2)
                {
                    param.Add(akv[0], akv[1].PercentDecode());
                }
            }

            StringBuilder sParam = new StringBuilder(); ;
            foreach (KeyValuePair<string, string> p in param.OrderBy(k => k.Key))
            {
                if (sParam.Length > 0)
                    sParam.Append("&");

                sParam.AppendFormat("{0}={1}", p.Key.PercentEncode(), p.Value.PercentEncode());
            }

            string url = req.RequestUri.AbsoluteUri;
            if (!string.IsNullOrEmpty(req.RequestUri.Query))
            {
                url = url.Replace(req.RequestUri.Query, "");
            }

            string signatureBaseString
                = string.Format("{0}&{1}&{2}",
                req.Method.ToUpper(),
                url.PercentEncode(),
                sParam.ToString().PercentEncode()
            );

            // Create our hash key (you might say this is a password)
            string signatureKey = string.Format("{0}&{1}", ConsumerSecret.PercentEncode(), AccessTokenSecret.PercentEncode());

            // Generate the hash
            System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(signatureKey));
            byte[] signatureBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));

            string signature = Convert.ToBase64String(signatureBytes).PercentEncode();

            string at = string.IsNullOrEmpty(AccessToken) ? "" : string.Format("oauth_token=\"{0}\",", AccessToken);
            string oauth = "OAuth realm=\"{0}\",oauth_consumer_key=\"{1}\",oauth_nonce=\"{2}\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"{3}\",{4}oauth_version=\"1.0\",oauth_signature=\"{5}\"";
            oauth = string.Format(oauth, "Spiral16", ConsumerKey, nonce, timeStamp, at, signature);

            req.Headers.Add("Authorization", oauth);
            req.ContentType = "application/x-www-form-urlencoded";

            return req;
        }