예제 #1
0
        private string AuthorizationHeader(string method, DateTime now, HttpWebRequest request, string contentLength = "", string ifMatch = "", string md5 = "")
        {
            string MessageSignature;

            //this is the raw representation of the message signature
            MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
                                             method,
                                             contentLength,
                                             ifMatch,
                                             GetCanonicalizedHeaders(request),
                                             GetCanonicalizedResource(request.RequestUri, this.storageAccount),
                                             md5
                                             );

            //now turn it into a byte array
            byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature);

            //create the HMACSHA256 version of the storage key
            System.Security.Cryptography.HMACSHA256 SHA256 =
                new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(this.accessKey));

            //Compute the hash of the SignatureBytes and convert it to a base64 string.
            string signature = Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));

            //this is the actual header that will be added to the list of request headers
            string AuthorizationHeader = "SharedKey " + this.storageAccount
                                         + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));

            return(AuthorizationHeader);
        }
예제 #2
0
 public static string PBKDF2Sha256GetBytes(int dklen, string password_string, string salt_b64, int iterationCount)
 {
     byte[] password = Encoding.UTF8.GetBytes(password_string);
     byte[] salt     = Encoding.ASCII.GetBytes(salt_b64);
     using (var hmac = new System.Security.Cryptography.HMACSHA256(password))
     {
         int hashLength = hmac.HashSize / 8;
         if ((hmac.HashSize & 7) != 0)
         {
             hashLength++;
         }
         int keyLength = dklen / hashLength;
         if ((long)dklen > (0xFFFFFFFFL * hashLength) || dklen < 0)
         {
             throw new ArgumentOutOfRangeException("dklen");
         }
         if (dklen % hashLength != 0)
         {
             keyLength++;
         }
         byte[] extendedkey = new byte[salt.Length + 4];
         Buffer.BlockCopy(salt, 0, extendedkey, 0, salt.Length);
         using (var ms = new System.IO.MemoryStream())
         {
             for (int i = 0; i < keyLength; i++)
             {
                 extendedkey[salt.Length]     = (byte)(((i + 1) >> 24) & 0xFF);
                 extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF);
                 extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF);
                 extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF);
                 byte[] u = hmac.ComputeHash(extendedkey);
                 Array.Clear(extendedkey, salt.Length, 4);
                 byte[] f = u;
                 for (int j = 1; j < iterationCount; j++)
                 {
                     u = hmac.ComputeHash(u);
                     for (int k = 0; k < f.Length; k++)
                     {
                         f[k] ^= u[k];
                     }
                 }
                 ms.Write(f, 0, f.Length);
                 Array.Clear(u, 0, u.Length);
                 Array.Clear(f, 0, f.Length);
             }
             byte[] dk = new byte[dklen];
             ms.Position = 0;
             ms.Read(dk, 0, dklen);
             ms.Position = 0;
             for (long i = 0; i < ms.Length; i++)
             {
                 ms.WriteByte(0);
             }
             Array.Clear(extendedkey, 0, extendedkey.Length);
             return(Convert.ToBase64String(dk));
         }
     }
 }
예제 #3
0
        public bool VerificarPasswordHash(string password, byte[] passwordHashAlmacenado)
        {
            using var hmac = new System.Security.Cryptography.HMACSHA256(this._encoding.GetBytes(this._key));
            var passwordHashNuevo = hmac.ComputeHash(this._encoding.GetBytes(password));

            return(new ReadOnlySpan <byte>(passwordHashAlmacenado).SequenceEqual(new ReadOnlySpan <byte>(passwordHashNuevo)));
        }
예제 #4
0
 private void creathash(string pass, out byte[] hash, out byte[] salt)
 {
     using (var h = new System.Security.Cryptography.HMACSHA256()) {
         salt = h.Key;
         hash = h.ComputeHash(System.Text.Encoding.UTF8.GetBytes(pass));
     }
 }
예제 #5
0
        public IActionResult Post([FromForm] string login, [FromForm] string password)
        {
            if (login != "LF" && password != "teste")
            {
                return(Unauthorized());
            }


            var keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

            string header  = @"{""typ"":""JWT"",""alg"":""HS256""}";
            string payload = @"{""sub"":""123456789"",""name"":""Luiz Flavio""}";

            var headerBytes  = System.Text.Encoding.UTF8.GetBytes(header);
            var payloadBytes = System.Text.Encoding.UTF8.GetBytes(payload);

            var header64 = System.Convert.ToBase64String(headerBytes).Replace('+', '-')
                           .Replace('/', '_')
                           .Replace("=", "")
            ;
            var payload64 = System.Convert.ToBase64String(payloadBytes).Replace('+', '-')
                            .Replace('/', '_')
                            .Replace("=", "");

            var messageBytes = System.Text.Encoding.UTF8.GetBytes(header64 + "." + payload64);

            System.Security.Cryptography.HMACSHA256 crypto = new System.Security.Cryptography.HMACSHA256(keyBytes);

            var signBytes = crypto.ComputeHash(messageBytes);
            var sign64    = System.Convert.ToBase64String(signBytes).Replace('+', '-')
                            .Replace('/', '_')
                            .Replace("=", "");

            return(Ok(header64 + "." + payload64 + "." + sign64));
        }
예제 #6
0
        public void MakeRequest(string type, string platform, string reqjsondata)
        {
            System.Text.UTF8Encoding en = new System.Text.UTF8Encoding();

            string secret = Configs.Secret;

            string uri = "http://api.bf3stats.com/" + platform + "/" + type + "/";
            WebClient wc = new WebClient();
            wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";

            if (type == "setupkey")
            {
                wc.UploadStringCompleted += new UploadStringCompletedEventHandler(completed_register);
            }
            else
            {
                wc.UploadStringCompleted += new UploadStringCompletedEventHandler(completed_update);
                secret = Configs.GetAPIkey();
            }

            System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(en.GetBytes(secret));

            Byte[] bytes = en.GetBytes(reqjsondata);
            string encodedRequest = Convert.ToBase64String(bytes).Replace('+', '-').Replace('/', '_').Replace("=", "");

            byte[] hashVal = hmac.ComputeHash(en.GetBytes(encodedRequest));
            string signature = Convert.ToBase64String(hashVal).Replace('+', '-').Replace('/', '_').Replace("=", "");

            string query = "data=" + encodedRequest + "&sig=" + signature;
            wc.UploadStringAsync(new Uri(uri), "POST", query);
        }
예제 #7
0
        /// <summary>
        /// Creates a new hash, given a password string, salt value, and hash version to use.
        /// </summary>
        private static string CreateHash(string password, string salt, int hashVersion)
        {
            // the global secret used in password hashing;
            // you can't ever change this, or all users will be unable to log in
            string globalSecret = "terceS-hap00S,1ABo1G";
            string valueToHash  = salt + password + salt + globalSecret;

            if (hashVersion == 1)
            {
                return(new MD5(valueToHash).HashString);
            }
            else if (hashVersion == 2)
            {
                // the key used in passphase hashing;
                // you can't ever change this, or all users with v2 hashes will be unable to log in
                string globalHashKey = "xN3Jar4Uvw9HPbGBAVesRq2Lz2KxyMPegf4bNS9nSsCDgLbh";

                var    encoding           = new System.Text.UTF8Encoding();
                byte[] globalHashKeyBytes = encoding.GetBytes(globalHashKey);
                byte[] valueToHashBytes   = encoding.GetBytes(valueToHash);

                var    sha  = new System.Security.Cryptography.HMACSHA256(globalHashKeyBytes);
                byte[] hash = sha.ComputeHash(valueToHashBytes);
                return(Convert.ToBase64String(hash));
            }
            else
            {
                throw new ApplicationException("Invalid hash version");
            }
        }
예제 #8
0
        // https://docs.microsoft.com/en-gb/rest/api/cosmos-db/access-control-on-cosmosdb-resources?redirectedfrom=MSDN
        private static string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)
        {
            var hmacSha256 = new System.Security.Cryptography.HMACSHA256 {
                Key = Convert.FromBase64String(key)
            };

            verb         = verb ?? string.Empty;
            resourceType = resourceType ?? string.Empty;
            resourceId   = resourceId ?? string.Empty;

            string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
                                           verb.ToLowerInvariant(),
                                           resourceType.ToLowerInvariant(),
                                           resourceId,
                                           date.ToLowerInvariant(),
                                           string.Empty
                                           );

            byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
            string signature   = Convert.ToBase64String(hashPayLoad);

            return(Uri.EscapeDataString(
                       string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                     "type=" + keyType + "&ver=" + tokenVersion + "&sig=" + signature)));
        }
예제 #9
0
파일: Seed.cs 프로젝트: cuong1404/code
 public void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA256()) {
         passwordSalt = hmac.Key;
         passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
     }
 }
        public IHttpActionResult GetTokenExConfig()
        {
            if (!Request.Headers.TryGetValues("Origin", out var originValues))
            {
                return(BadRequest("Invalid request."));
            }

            var timeStamp   = DateTime.Now.ToString("yyyyMMddHHmmss");
            var tokenScheme = "nTOKEN";

            var concatenatedInfo = $"{_tokenizationOptions.TokenizationId}|{originValues.First()}|{timeStamp}|{tokenScheme}";
            var hmac             = new System.Security.Cryptography.HMACSHA256
            {
                Key = Encoding.UTF8.GetBytes(_tokenizationOptions.ClientSecretKey)
            };
            var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(concatenatedInfo));
            var authenticationKey = Convert.ToBase64String(hash);

            return(Ok(new TokenExIframeConfigModel
            {
                TokenExID = _tokenizationOptions.TokenizationId,
                AuthenticationKey = authenticationKey,
                Timestamp = timeStamp,
                TokenScheme = tokenScheme
            }));
        }
        public bool IsValid(string key, ILogger log)
        {
            //are the fields properly populated?
            if (string.IsNullOrEmpty(this.expiry) || this.requestedResource == null || string.IsNullOrEmpty(this.signature) || string.IsNullOrEmpty(key))
            {
                log.LogInformation("badrequest");
                return(false);
            }

            //is request expired?
            double expiryDouble;

            if (double.TryParse(this.expiry, out expiryDouble))
            {
                if (expiryDouble < (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds)
                {
                    log.LogInformation("expired");
                    return(false);
                }
            }
            else
            {
                log.LogInformation("error parsing");
                return(false);
            }

            string stringToSign = System.Web.HttpUtility.UrlEncode(this.requestedResource.ToString()) + "\n" + this.expiry;

            System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(key));
            string computedSignature = Convert.ToBase64String(hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)));

            return(string.Equals(this.signature, computedSignature));
        }
예제 #12
0
        /// <summary>
        /// Generates the signature for a string containing a LatitudePay request body in json format.
        /// </summary>
        /// <param name="jsonPayload">The json payload.</param>
        /// <remarks>
        /// <para>If <paramref name="jsonPayload"/> is null or an empty string then null is returned as the signature.</para>
        /// </remarks>
        /// <returns>A string containing the required signature.</returns>
        /// <exception cref="ObjectDisposedException">Thrown if <see cref="Dispose"/> has been called on this instance.</exception>
        public string?GenerateSignature(string jsonPayload)
        {
            if (_IsDisposed)
            {
                throw new ObjectDisposedException(nameof(LatitudePayHMACSHA256SignatureGenerator));
            }
            if (String.IsNullOrEmpty(jsonPayload))
            {
                return(null);
            }

            //TODO: Lots of allocations going on here, should be improved.
            //Convert byte array to base 64 without converting to string
            //Use recyclable memory streams
            //Reuse/pool the string builder (or replace with a recycable memory stream etc)
            var normalisedPayload    = StripJsonFormatting(jsonPayload);
            var base64EncodedPayload = System.Convert.ToBase64String(normalisedPayload);
            var hashBytes            = _Hasher.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(base64EncodedPayload));

            var resultBuilder = new StringBuilder(hashBytes.Length * 2);

            foreach (var b in hashBytes)
            {
                resultBuilder.Append(b.ToString("x2", System.Globalization.CultureInfo.InvariantCulture));
            }
            return(resultBuilder.ToString());
        }
예제 #13
0
 public static byte[] Compute(byte[] data, byte[] key)
 {
     using (var hmacSha256 = new System.Security.Cryptography.HMACSHA256(key))
     {
         return(hmacSha256.ComputeHash(data));
     }
 }
예제 #14
0
 private void createPass(string password, out byte[] hashed, out byte[] salt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA256()){
         salt   = hmac.Key;
         hashed = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
     }
 }
예제 #15
0
        private static string GenerateMasterKeyAuthorizationSignature(
            string verb,
            string resourceId,
            string resourceType,
            string key,
            string keyType,
            string tokenVersion,
            string dateTimeUtc)
        {
            System.Security.Cryptography.HMACSHA256 hmacSha256 = new System.Security.Cryptography.HMACSHA256 {
                Key = Convert.FromBase64String(key)
            };

            string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
                                           verb.ToLowerInvariant(),
                                           resourceType.ToLowerInvariant(),
                                           resourceId,
                                           dateTimeUtc.ToLowerInvariant(),
                                           ""
                                           );

            byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
            string signature   = Convert.ToBase64String(hashPayLoad);

            return(System.Web.HttpUtility.UrlEncode(string.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
                                                                  keyType,
                                                                  tokenVersion,
                                                                  signature)));
        }
예제 #16
0
        /*
         * https://www.cnblogs.com/lechengbo/p/9860711.html
         * /// <summary>
         * /// 创建jwtToken,采用微软内部方法,默认使用HS256加密,如果需要其他加密方式,请更改源码
         * /// 返回的结果和CreateToken一样
         * /// </summary>
         * /// <param name="payLoad"></param>
         * /// <param name="expiresMinute">有效分钟</param>
         * /// <returns></returns>
         * public static string CreateTokenByHandler(Dictionary<string, object> payLoad, int expiresMinute)
         * {
         *
         *  var now = DateTime.UtcNow;
         *
         *  // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
         *  // You can add other claims here, if you want:
         *  var claims = new List<Claim>();
         *  foreach (var key in payLoad.Keys)
         *  {
         *      var tempClaim = new Claim(key, payLoad[key]?.ToString());
         *      claims.Add(tempClaim);
         *  }
         *
         *
         *  // Create the JWT and write it to a string
         *  var jwt = new JwtSecurityToken(
         *      issuer: null,
         *      audience: null,
         *      claims: claims,
         *      notBefore: now,
         *      expires: now.Add(TimeSpan.FromMinutes(expiresMinute)),
         *      signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(securityKey)), SecurityAlgorithms.HmacSha256));
         *  var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
         *  return encodedJwt;
         * }
         *
         *
         *           /// <summary>
         * /// 获取jwt中的payLoad
         * /// </summary>
         * /// <param name="encodeJwt"></param>
         * /// <returns></returns>
         * public static Dictionary<string, object> GetPayLoad(string encodeJwt)
         * {
         *  var jwtArr = encodeJwt.Split('.');
         *  var payLoad = JsonConvert.DeserializeObject<Dictionary<string, object>>(Base64Decode(jwtArr[1]));
         *  return payLoad;
         * }
         *
         */

        /// <summary>
        /// 验证身份 验证签名的有效性,
        /// </summary>
        /// <param name="encodeJwt"></param>
        /// <param name="validatePayLoad">自定义各类验证; 是否包含那种申明,或者申明的值, </param>
        /// 例如:payLoad["aud"]?.ToString() == "roberAuddience";
        /// 例如:验证是否过期 等
        /// <returns></returns>
        public static bool Validate(string encodeJwt, Func <Dictionary <string, object>, bool> validatePayLoad)
        {
            encodeJwt = encodeJwt.Replace("Bearer ", string.Empty);
            var success = true;
            var jwtArr  = encodeJwt.Split('.');
            //var header = JsonConvert.DeserializeObject<Dictionary<string, object>>(Base64Decode(jwtArr[0]));


            var hs256 = new System.Security.Cryptography.HMACSHA256(Encoding.ASCII.GetBytes(securityKey));

            //首先验证签名是否正确(必须的)
            success = success && string.Equals(jwtArr[2], Convert.ToBase64String(hs256.ComputeHash(Encoding.UTF8.GetBytes(string.Concat(jwtArr[0], ".", jwtArr[1])))));
            if (!success)
            {
                return(success);//签名不正确直接返回
            }
            //其次验证是否在有效期内(也应该必须)
            var now = ToUnixEpochDate(DateTime.UtcNow);

            var payLoad = JsonConvert.DeserializeObject <Dictionary <string, object> >(Base64Decode(jwtArr[1]));

            success = success && (now >= long.Parse(payLoad["nbf"].ToString()) && now < long.Parse(payLoad["exp"].ToString()));

            //再其次 进行自定义的验证
            success = success && validatePayLoad(payLoad);

            return(success);
        }
예제 #17
0
        public static bool VerifyPasswordHash(string password, byte[] storedHash)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }
            if (storedHash.Length != 32)
            {
                throw new ArgumentException("Invalid length of password hash (32 bytes expected).", "passwordHash");
            }


            using (var hmac = new System.Security.Cryptography.HMACSHA256(salt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
예제 #18
0
        public string GetSignature(string messageSignature)
        {
            var signatureBytes = Encoding.UTF8.GetBytes(messageSignature);
            var SHA256         = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(StorageKey));

            return(Convert.ToBase64String(SHA256.ComputeHash(signatureBytes)));
        }
예제 #19
0
        public static string AuthorizationHeader(string StorageAccount, string StorageKey, string method, DateTime now, HttpWebRequest request, bool IsTableStorage, string ifMatch = "", string md5 = "")
        {
            if (string.IsNullOrEmpty(StorageAccount))
            {
                throw new ArgumentNullException(StorageAccount);
            }
            string MessageSignature;

            if (IsTableStorage)
            {
                MessageSignature = String.Format("{0}\n\n{1}\n{2}\n{3}",
                    method,
                    "application/atom+xml",
                    now.ToString("R", System.Globalization.CultureInfo.InvariantCulture),
                    GetCanonicalizedResource(request.RequestUri, StorageAccount, IsTableStorage)
                    );
            }
            else
            {
                MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
                    method,
                    (method == "GET" || method == "HEAD") ? String.Empty : request.ContentLength.ToString(),
                    ifMatch,
                   GetCanonicalizedHeaders(request),
                    GetCanonicalizedResource(request.RequestUri, StorageAccount, IsTableStorage),
                    md5
                    );
            }
            byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature);
            System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(StorageKey));
            String AuthorizationHeader = "SharedKey " + StorageAccount + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
            return AuthorizationHeader;
        }
예제 #20
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "api/skyway")] HttpRequest req,
            ILogger log)
        {
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            string  token       = data?.token;

            if (string.IsNullOrEmpty(token))
            {
                return(new BadRequestResult());
            }

            var uri  = new Uri(token.Replace("?", "/check.txt?"));
            var blob = new BlobClient(uri);

            try
            {
                await blob.DownloadAsync();
            }
            catch
            {
                return(new UnauthorizedResult());
            }

            var timestamp = DateTimeOffset.Now.ToUnixTimeSeconds();
            var ttl       = 3600 * 3;
            var peerId    = Guid.NewGuid().ToString("n");

            using var hmac = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(_settings.SkyWaySecretKey));
            var authToken = hmac.ComputeHash(Encoding.UTF8.GetBytes($"{timestamp}:{ttl}:{peerId}"));

            return(new OkObjectResult(new { peerId, timestamp, ttl, authToken }));
        }
예제 #21
0
        internal static string GenerateMasterKeyAuthorizationSignature(string utcDate, string verb, string resourceType, string resourceValue, string key, string keyType, string tokenVersion)
        {
            try
            {
                var hmacSha256 = new System.Security.Cryptography.HMACSHA256 {
                    Key = Convert.FromBase64String(key)
                };
                string payLoad = verb.ToLowerInvariant() + "\n" +
                                 (!String.IsNullOrWhiteSpace(resourceType) ? resourceType.ToLowerInvariant() : "") + "\n" +
                                 (!String.IsNullOrWhiteSpace(resourceValue) ? resourceValue : "") + "\n" +
                                 utcDate.ToLowerInvariant() + "\n\n";

                byte[] hashPayLoad = hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(payLoad));
                string signature   = Convert.ToBase64String(hashPayLoad);
                return(Uri.EscapeDataString(
                           String.Format(System.Globalization.CultureInfo.InvariantCulture,
                                         "type=" + keyType + "&ver=" + tokenVersion + "&sig=" + signature)));
            }
            catch (FormatException ex) // and UriFormatException
            {
                throw new TinyDocDB_Exception("Error Generating the Authentication Signature.", ex);
            }
            catch (EncoderFallbackException ex)
            {
                throw new TinyDocDB_Exception("Error Generating the Authentication Signature.", ex);
            }
            catch (ObjectDisposedException ex)
            {
                throw new TinyDocDB_Exception("Error Generating the Authentication Signature.", ex);
            }
            catch (ArgumentNullException ex)
            {
                throw new TinyDocDB_Exception("Error Generating the Authentication Signature.", ex);
            }
        }
예제 #22
0
        internal static string CreateAuthorizationSignature(string utcDate, string verb, string resourceType, string resourceValue, string key, string keyType, string tokenVersion)
        {
            try
            {
                var hmacSha256 = new System.Security.Cryptography.HMACSHA256 {
                    Key = Convert.FromBase64String(key)
                };

                verb          = verb ?? "";
                resourceType  = resourceType ?? "";
                resourceValue = resourceValue ?? "";

                string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
                                               verb.ToLowerInvariant(),
                                               resourceType.ToLowerInvariant(),
                                               resourceValue,
                                               utcDate.ToLowerInvariant(),
                                               ""
                                               );

                var    hashPayLoad = hmacSha256.ComputeHash(Encoding.UTF8.GetBytes(payLoad));
                string signature   = Convert.ToBase64String(hashPayLoad);
                return(Uri.EscapeDataString(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type=" + keyType + "&ver=" + tokenVersion + "&sig=" + signature)));
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                throw;
            }
        }
예제 #23
0
        private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt)
        {
            if (storedHash.Length != 32)
            {
                return(false);
            }
            if (storedSalt.Length != 64)
            {
                return(false);
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA256(storedSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                for (var i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != storedHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
예제 #24
0
        /// <summary>
        /// 创建jwttoken,源码自定义
        /// </summary>
        /// <param name="payLoad"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static string CreateToken(Dictionary <string, object> payLoad, int expiresMinute, Dictionary <string, object> header = null)
        {
            if (header == null)
            {
                header = new Dictionary <string, object>(new List <KeyValuePair <string, object> >()
                {
                    new KeyValuePair <string, object>("alg", "HS256"),
                    new KeyValuePair <string, object>("typ", "JWT")
                });
            }
            //添加jwt可用时间(应该必须要的)
            var now = DateTime.UtcNow;

            payLoad["nbf"] = ToUnixEpochDate(now);                                          //可用时间起始
            payLoad["exp"] = ToUnixEpochDate(now.Add(TimeSpan.FromMinutes(expiresMinute))); //可用时间结束

            var encodedHeader  = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header)));
            var encodedPayload = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payLoad)));

            var hs256            = new System.Security.Cryptography.HMACSHA256(Encoding.ASCII.GetBytes(securityKey));
            var encodedSignature = Convert.ToBase64String(hs256.ComputeHash(Encoding.UTF8.GetBytes(string.Concat(encodedHeader, ".", encodedPayload))));

            var encodedJwt = string.Concat(encodedHeader, ".", encodedPayload, ".", encodedSignature);

            return($"Bearer {encodedJwt}");
        }
예제 #25
0
        private static string CreateSignatureOfRequest(byte[] body)
        {
            try
            {
                //string documentContents = "";
                //using (Stream receiveStream = request.InputStream)
                //{
                //    using (StreamReader readStream = new StreamReader(receiveStream, request.ContentEncoding))
                //    {
                //        documentContents = readStream.ReadToEnd();
                //    }
                //}

                byte[] key = Encoding.UTF8.GetBytes(Models.Constants.CHANNEL_SECRET);
                using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(key))
                {
                    var hash = hmac.ComputeHash(body, 0, body.Length);
                    return(Convert.ToBase64String(hash));
                }
            }
            catch
            {
                return("ERROR");
            }
        }
예제 #26
0
        public string Cipher(string stringToCipher, string verb, string resourceType, string resourceId, string date)
        {
            var hmacSha256 = new System.Security.Cryptography.HMACSHA256 {
                Key = Convert.FromBase64String(stringToCipher)
            };

            //var date = DateTime.UtcNow.ToString("r");
            verb         = verb ?? "";
            resourceType = resourceType ?? "";
            resourceId   = resourceId ?? "";

            string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
                                           verb.ToLowerInvariant(),
                                           resourceType.ToLowerInvariant(),
                                           resourceId,
                                           date.ToLowerInvariant(),
                                           ""
                                           );

            byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
            string signature   = Convert.ToBase64String(hashPayLoad);

            return(System.Net.WebUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
                                                                 "master",
                                                                 "1.0",
                                                                 signature)));
        }
예제 #27
0
        public static string SignTheStringToSign(string stringToSign, string sharedKey)
        {
            byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(stringToSign);
            System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(sharedKey));

            return(Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes)));
        }
예제 #28
0
		public static JObject DecodeFacebookRequest(string signed_request, Facebook.Apps app)
		{
			string secret = Facebook.FacebookCommon.Common(app).Secret;
			var facebookData = new Dictionary<string, string>();

			var requestArray = signed_request.Split('.');

			var sig = Base64_Url_Decode(requestArray[0]);

			var dataString = Base64_Url_Decode(requestArray[1]);

			var data = JObject.Parse(dataString);

			var algo = data["algorithm"].ToString().Replace("\"", "");

			if (algo != "HMAC-SHA256")
			{
				return null;
			}

			var hmacsha256 = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secret));
			hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(requestArray[1]));

			var expected_sig = Encoding.UTF8.GetString(hmacsha256.Hash);

			if (sig != expected_sig)
			{
				return null;
			}

			return data;
		}
예제 #29
0
        public Dictionary <string, string> gen_encodedHeaders()
        {
            var payload = new global::Riminder.response.WebhookProfileParse()
            {
                type    = global::Riminder.route.Webhook.EventNames.PROFILE_PARSE_SUCCESS,
                message = "Yey it's parsed ! :) (not actually a true message)",
                profile = new global::Riminder.response.WebhookProfile()
                {
                    profile_id        = "some complicated id",
                    profile_reference = "some simple reference"
                }
            };
            var json_payload      = JsonConvert.SerializeObject(payload);
            var byte_json_payload = System.Text.Encoding.UTF8.GetBytes(json_payload);
            var byte_key          = System.Text.Encoding.UTF8.GetBytes(_webhook_key);

            var hasher = new System.Security.Cryptography.HMACSHA256(byte_key);

            var encoded_sign = hasher.ComputeHash(byte_json_payload);

            var b64_sign    = System.Convert.ToBase64String(encoded_sign);
            var b64_payload = System.Convert.ToBase64String(byte_json_payload);
            var res         = String.Concat(b64_sign, ".", b64_payload);

            return(new Dictionary <string, string>()
            {
                { "HTTP-RIMINDER-SIGNATURE", res }
            });
        }
예제 #30
0
        /// <summary>
        /// Verifies whether a plain text password matches the hashed password
        /// </summary>
        /// <param name="passwordSalt"></param>
        /// <param name="plainTextPassword"></param>
        /// <param name="passwordHash"></param>
        /// <returns></returns>
        public bool VerifyPasswordHash(byte[] passwordHash, byte[] passwordSalt, string plainTextPassword)
        {
            if (passwordHash == null)
            {
                throw new ArgumentNullException(nameof(passwordHash));
            }

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

            if (string.IsNullOrEmpty(plainTextPassword))
            {
                throw new ArgumentNullException(nameof(plainTextPassword));
            }

            // pass the passwordSalt to obtain the secure key
            using (var hmac = new System.Security.Cryptography.HMACSHA256(passwordSalt))
            {
                // password converted to a byte array so it can be hashed using the salt key above
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(plainTextPassword));

                // compare each element in the computedHash byte array
                if (computedHash.Where((t, i) => t != passwordHash[i]).Any())
                {
                    return(false);
                }
            }

            // if all correct, return true
            return(true);
        }
예제 #31
0
        private static bool VerifyPasswordHash(string password, string storedHash, string storedSalt)
        {
            byte[] byeHash  = Convert.FromBase64String(storedHash);
            byte[] byteSalt = Convert.FromBase64String(storedSalt);
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty or whitespace only string.", "password");
            }
            if (byeHash.Length != 32)
            {
                throw new ArgumentException("Invalid length of password hash (62 bytes expected).", "passwordHash");
            }
            if (byteSalt.Length != 64)
            {
                throw new ArgumentException("Invalid length of password salt (64 bytes expected).", "passwordSalt");
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA256(byteSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != byeHash[i])
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
예제 #32
0
 /// <summary>
 /// Création d'un token HS256 HMAC AES
 /// </summary>
 /// <param name="payload">Données à signer</param>
 /// <param name="keyHs256">Clef UTF8</param>
 /// <returns></returns>
 public static string Encode(Dictionary <string, object> payload, string keyHs256)
 {
     try
     {
         if (string.IsNullOrWhiteSpace(keyHs256))
         {
             throw new Exception("Invalid Key for sign");
         }
         byte[]        keyBytes   = Encoding.UTF8.GetBytes(keyHs256);
         List <string> segments   = new List <string>();
         const string  headerJson = "{\"alg\":\"HS256\",\"typ\": \"JWT\"}";
         //string payloadJson = Nglib.FILES.SERIAL.JsonTools.Serialize<Dictionary<string, object>>(payload);
         string payloadJson = FILES.SERIAL.JsonTools.SerializeDictionaryValues(payload);
         segments.Add(Base64UrlEncode(Encoding.UTF8.GetBytes(headerJson)));
         segments.Add(Base64UrlEncode(Encoding.UTF8.GetBytes(payloadJson)));
         var    stringToSign = string.Join(".", segments.ToArray());
         var    bytesToSign  = Encoding.UTF8.GetBytes(stringToSign);
         var    sha          = new System.Security.Cryptography.HMACSHA256(keyBytes);
         byte[] signature    = sha.ComputeHash(bytesToSign);
         segments.Add(Base64UrlEncode(signature));
         return(string.Join(".", segments.ToArray()));
     }
     catch (Exception ex)
     {
         throw new Exception("EncodeJWT " + ex.Message, ex);
     }
 }
예제 #33
0
        public static bool ValidateSignature(string body, string signature, string secret)
        {
            var hash = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secret));
            var computedSignature = Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(body)));

            return(computedSignature == signature);
        }
예제 #34
0
 public static string GenerateEventHash(string apiKey, string eventTime, string eventType)
 {
     var keyBytes = Encoding.ASCII.GetBytes(apiKey);
     using (var hmac = new System.Security.Cryptography.HMACSHA256(keyBytes))
     {
         var inputBytes = Encoding.ASCII.GetBytes(eventTime + eventType);
         var outputBytes = hmac.ComputeHash(inputBytes);
         return BitConverter.ToString(outputBytes).Replace("-", "").ToLower();
     }
 }
예제 #35
0
        public HttpResponseMessage Post([FromBody]TokenRequestModel model)
        {
            try
            {
                var user = _repo.GetApiUsers().Where(u => u.AppId == model.ApiKey).FirstOrDefault();
                //if we actually have the user
                if (user != null)
                {
                    var secret = user.Secret;

                    // Converting the secret to the raw version
                    var key = Convert.FromBase64String(secret);
                    var provider = new System.Security.Cryptography.HMACSHA256(key);
                    // Compute Hash from API Key (NOT SECURE)
                    var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(user.AppId));
                    var signature = Convert.ToBase64String(hash);
                    //checking the signature with the user
                    if (signature == model.Signature)
                    {
                        var rawTokenInfo = string.Concat(user.AppId + DateTime.UtcNow.ToString("d"));
                        var rawTokenByte = Encoding.UTF8.GetBytes(rawTokenInfo);
                        var token = provider.ComputeHash(rawTokenByte);
                        var authToken = new AuthToken()
                        {
                            Token = Convert.ToBase64String(token),
                            Expiration = DateTime.UtcNow.AddDays(15),
                            ApiUser = user
                        };
                        if (_repo.Insert(authToken) && _repo.SaveAll())
                        {
                            return Request.CreateResponse(HttpStatusCode.Created, authToken);
                        }
                    }
                }
            }
            catch 
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest,"ERROR");
            }

            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
예제 #36
0
    public HttpResponseMessage Post([FromBody]TokenRequestModel model)
    {
      try
      {
        var user = TheRepository.GetApiUsers().Where(u => u.AppId == model.ApiKey).FirstOrDefault();
        if (user != null)
        {
          var secret = user.Secret;

          // Simplistic implementation DO NOT USE
          var key = Convert.FromBase64String(secret);
          var provider = new System.Security.Cryptography.HMACSHA256(key);
          // Compute Hash from API Key (NOT SECURE)
          var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(user.AppId));
          var signature = Convert.ToBase64String(hash);

          if (signature == model.Signature)
          {
            var rawTokenInfo = string.Concat(user.AppId + DateTime.UtcNow.ToString("d"));
            var rawTokenByte = Encoding.UTF8.GetBytes(rawTokenInfo);
            var token = provider.ComputeHash(rawTokenByte);
            var authToken = new AuthToken()
            {
              Token = Convert.ToBase64String(token),
              Expiration = DateTime.UtcNow.AddDays(7),
              ApiUser = user
            };
            if (TheRepository.Insert(authToken) && TheRepository.SaveAll())
            {
              return Request.CreateResponse(HttpStatusCode.Created, TheModelFactory.Create(authToken));
            }
          }
        }
      }
      catch (Exception ex)
      {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
      }

      return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
예제 #37
0
        public System.Security.Cryptography.HMACSHA256 HashSignature(ETextingDomainModel.ApiUser user, out string signature)
        {
            var secret = user.Secret;

            // Simplistic implementation DO NOT USE
            var key = Convert.FromBase64String(secret);
            var provider = new System.Security.Cryptography.HMACSHA256(key);
            // Compute Hash from API Key (NOT SECURE)
            var hash = provider.ComputeHash(Encoding.UTF8.GetBytes(user.AppId));
            signature = Convert.ToBase64String(hash);
            return provider;
        }
예제 #38
0
파일: Kana.cs 프로젝트: kazukioishi/Uzuki
 public static String CaculateHMAC(String key,String mesg)
 {
     byte[] data = System.Text.Encoding.UTF8.GetBytes(mesg);
     byte[] keyData = System.Text.Encoding.UTF8.GetBytes(key);
     //HMACSHA1オブジェクトの作成
     System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(keyData);
     //ハッシュ値を計算
     byte[] bs = hmac.ComputeHash(data);
     //リソースを解放する
     hmac.Clear();
     //byte型配列を16進数に変換
     return BitConverter.ToString(bs).ToLower().Replace("-", "");
 }
예제 #39
0
        public static string MakeBlobReadSignature(DateTime starttime, DateTime endtime,
            string account, string container, string blobname, string sharedKey)
        {
            string stringtosign =
              string.Format("r\n{0:yyyy-MM-ddThh:mm:ssZ}\n{1:yyyy-MM-ddTHH:mm:ssZ}\n/{2}/{3}/{4}\n\n2012-02-12",
              starttime, endtime, account, container, blobname);
              byte[] signatureByteForm = System.Text.Encoding.UTF8.GetBytes(sharedKey );

              using (var hmac = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(sharedKey)))
              {
              return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringtosign)));
              }
        }
예제 #40
0
 private static string CreateToken(string message, string secret)
 {
     // don't allow null secrets
     secret = secret ?? "";
     var encoding = new System.Text.ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(secret);
     byte[] messageBytes = encoding.GetBytes(message);
     using (var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyByte))
     {
         byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
         return Convert.ToBase64String(hashmessage);
     }
 }
예제 #41
0
        protected internal static string GenerateNonce(AuthConfig config, DateTimeOffset httpRequestUTCDate)
        {
            string content = config.ApiAccessKey + " " + httpRequestUTCDate.ToString(CultureInfo.CurrentCulture.DateTimeFormat.RFC1123Pattern);

            byte[] keyByte = System.Text.Encoding.UTF8.GetBytes(config.ApiSecretKey);
            var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyByte);

            byte[] messageBytes = System.Text.Encoding.UTF8.GetBytes(content);
            byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);

            string sbinary = "";
            for (int i = 0; i < hashmessage.Length; i++) sbinary += hashmessage[i].ToString("X2"); // hex format
            return sbinary;
        }
예제 #42
0
        /// <summary>
        /// Generate Signature
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>

        public static string GenerateSignature(string data)
        {
            string secret = "25eace5393646842f0d0c3fb2ac7d3cfa15c052436ee86b5406a8433f54d24a5";
            var secretBytes = Encoding.UTF8.GetBytes(secret);
            var dataBytes = Encoding.UTF8.GetBytes(data);
            string signature = "";

            using (var hmac = new System.Security.Cryptography.HMACSHA256(secretBytes))
            {
                var hash = hmac.ComputeHash(dataBytes);
                for (int i = 0; i < hash.Length; i++)
                {
                    signature += hash[i].ToString("x2");
                }
            }
            return signature;
        }
예제 #43
0
        public static void AddAzureAuthorizationHeaderLiteFromSharedKey(System.Net.HttpWebRequest req, string sharedKey)
        {
            string StringToSign = req.Headers["x-ms-date"] + "\n";
            StringToSign += GenerateCanonicalizedResource(req.RequestUri);

            string signature = StringToSign;
            //System.Diagnostics.Trace.TraceInformation("GenerateAzureSignatureFromSharedKey: Generated signature: " + StringToSign);

            byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(signature);
            System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(sharedKey));

            string strHash2Base64 = Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));

            String AuthorizationHeader = "SharedKeyLite " + GetAccountNameFromUri(req.RequestUri) + ":" + strHash2Base64;

            req.Headers.Add("Authorization", AuthorizationHeader);
        }
예제 #44
0
        /// <summary>
        /// Parses the signed request string.
        /// </summary>
        /// <param name="signedRequestValue">The encoded signed request value.</param>
        /// <returns>The valid signed request.</returns>
        protected internal FbmlFacebookSession ParseSignedRequest(string signedRequestValue, string secrect)
        {
            string[] parts = signedRequestValue.Split('.');
            var encodedValue = parts[0];

            var sig = Base64UrlDecode(encodedValue);
            var payload = parts[1];

            using (var cryto = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secrect)))
            {
                var hash = Convert.ToBase64String(cryto.ComputeHash(Encoding.UTF8.GetBytes(payload)));
                var hashDecoded = Base64UrlDecode(hash);
                if (hashDecoded != sig)
                {
                    return null;
                }
            }

            var payloadJson = Encoding.UTF8.GetString(Convert.FromBase64String(Base64UrlDecode(payload)));
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var data = (IDictionary<string, object>)serializer.DeserializeObject(payloadJson);
            var sessionKeyValue = PopulateFbmlSessionObject(data);
            return new FbmlFacebookSession(sessionKeyValue);
        }
예제 #45
0
        private void CompareBlocks(HmacAlg Algorithm)
        {
            if (Algorithm == HmacAlg.Sha256Hmac)
            {
                byte[] hashKey = new byte[32];
                byte[] buffer = new byte[640];
                byte[] hash1 = new byte[32];
                byte[] hash2 = new byte[32];

                using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    rng.GetBytes(hashKey);
                    rng.GetBytes(buffer);
                }

                using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(hashKey))
                    hash1 = hmac.ComputeHash(buffer);

                // test 1: HMAC interface
                HMAC hmac1 = new HMAC(new SHA256Digest());
                hmac1.Init(hashKey);
                hmac1.BlockUpdate(buffer, 0, buffer.Length);
                hmac1.DoFinal(hash2, 0);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac is not equal!");

                // test 2: class with dofinal
                using (SHA256HMAC hmac = new SHA256HMAC())
                {
                    hmac.Init(hashKey);
                    hmac.BlockUpdate(buffer, 0, buffer.Length);
                    hmac.DoFinal(hash2, 0);
                }

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 3: class with computemac
                using (SHA256HMAC hmac = new SHA256HMAC(hashKey))
                    hash2 = hmac.ComputeMac(buffer);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac2 is not equal!");
            }
            else
            {
                // SHA512 //
                byte[] hash1 = new byte[64];
                byte[] hash2 = new byte[64];
                byte[] hashKey = new byte[64];
                byte[] buffer = new byte[128];

                using (System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
                {
                    rng.GetBytes(hashKey);
                    rng.GetBytes(buffer);
                }

                using (System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(hashKey))
                    hash1 = hmac.ComputeHash(buffer);

                // test 1: HMAC interface
                HMAC hmac1 = new HMAC(new SHA512Digest());
                hmac1.Init(hashKey);
                hmac1.BlockUpdate(buffer, 0, buffer.Length);
                hmac1.DoFinal(hash2, 0);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 2: class with dofinal
                using (SHA512HMAC hmac = new SHA512HMAC())
                {
                    hmac.Init(hashKey);
                    hmac.BlockUpdate(buffer, 0, buffer.Length);
                    hmac.DoFinal(hash2, 0);
                }

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac1 is not equal!");

                // test 3: class with computemac
                using (SHA512HMAC hmac = new SHA512HMAC(hashKey))
                    hash2 = hmac.ComputeMac(buffer);

                if (!Compare.AreEqual(hash2, hash1))
                    throw new Exception("hmac2 is not equal!");
            }
        }
예제 #46
0
		private byte[] ComputeHandshakeDigest1(byte[] vec, byte[] key, int doffset)
		{
			var msg = new byte[vec.Length-32];
			Array.Copy(vec, 0, msg, 0, doffset);
			Array.Copy(vec, doffset+32, msg, doffset, vec.Length-32-doffset);
			var hasher = new System.Security.Cryptography.HMACSHA256(key);
			return hasher.ComputeHash(msg);
		}
예제 #47
0
        public static string SignTheStringToSign(string stringToSign, string sharedKey)
        {
            byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(stringToSign);
            System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(sharedKey));

            return Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
        }
예제 #48
0
		private byte[] ComputeHandshakeDigest2(byte[] keyvec, DigestPosition keypos, byte[] vec, byte[] key)
		{
			var doffset = GetDigestOffset(keyvec, keypos);
			var hasher1 = new System.Security.Cryptography.HMACSHA256(key);
			var key2 = hasher1.ComputeHash(keyvec, doffset, 32);
			var hasher2 = new System.Security.Cryptography.HMACSHA256(key2);
			return hasher2.ComputeHash(vec, 0, vec.Length-32);
		}
        public static string SharedKey(string Account, string signature)
        {
            // Hash-based Message Authentication Code (HMAC) using SHA256 hash
            System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(GetSecret(Account)));

            byte[] hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(signature));

            // return the Shared Key
            return "SharedKey " + Account + ":" + System.Convert.ToBase64String(hash);
        }
예제 #50
0
		public static byte[] PseudorandomFunction(byte[] secret, byte[] seed, int length)
		{
			byte[] result = new byte[length];
			System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(secret);
			int iterations = (int)Math.Ceiling(length / (double)hmac.HashSize);
			byte[] dataToHash = seed;
			int offset = 0;
			for (int index = 0; index < iterations; index++)
			{
				dataToHash = hmac.ComputeHash(dataToHash);
				hmac.TransformBlock(dataToHash, 0, dataToHash.Length, dataToHash, 0);
				byte[] hash = hmac.TransformFinalBlock(seed, 0, seed.Length);
				Buffer.BlockCopy(hash, 0, result, offset, Math.Min(hash.Length, length - offset));
				offset += hash.Length;
			}
			return result;
		}
예제 #51
0
 private static string CreateAuthorizationHeader(string canonicalizedstring, string sharedKeyAuthorizationScheme, string account, string applicationKey)
 {
     string signature = string.Empty;
     using (System.Security.Cryptography.HMACSHA256 hmacSha256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(applicationKey)))
     {
         Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedstring);
         signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
     }
     string authorizationHeader = string.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}", sharedKeyAuthorizationScheme, account, signature);
     return authorizationHeader;
 }
예제 #52
0
파일: Challenge.cs 프로젝트: RoPe93/CBcrypt
 public static byte[] GenerateChallengeResponseBytes(byte[] challenge, byte[] sharedSecret)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA256(sharedSecret)) {
         return hmac.ComputeHash(challenge);
     }
 }
예제 #53
0
        public void TestRfc7515Example_A_1_1()
        {
            string protectedSample = // From the RFC example
                    "{\"typ\":\"JWT\",\r\n" +
                    " \"alg\":\"HS256\"}";
          
            var protectedBytesExpected = new byte[] // From the RFC example
            {
                123, 34, 116, 121, 112, 34, 58, 34, 74, 87, 84, 34, 44, 13, 10,
                32, 34, 97, 108, 103, 34, 58, 34, 72, 83, 50, 53, 54, 34, 125
            };
            var protectedBytesActual = Encoding.UTF8.GetBytes(protectedSample);
            CollectionAssert.AreEqual(protectedBytesExpected, protectedBytesActual);
           
            string protectedB64uExpected = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9"; // From the RFC example
            string protectedB64uActual = JOSE.JwsHelper.Base64UrlEncode(protectedBytesActual);
            Assert.AreEqual(protectedB64uExpected, protectedB64uActual);

            string payloadSample = // From the RFC example
                    "{\"iss\":\"joe\",\r\n" +
                    " \"exp\":1300819380,\r\n" +
                    " \"http://example.com/is_root\":true}";

            byte[] payloadBytesExpected = // From the RFC example
            {
                123, 34, 105, 115, 115, 34, 58, 34, 106, 111, 101, 34, 44, 13, 10,
                32, 34, 101, 120, 112, 34, 58, 49, 51, 48, 48, 56, 49, 57, 51, 56,
                48, 44, 13, 10, 32, 34, 104, 116, 116, 112, 58, 47, 47, 101, 120, 97,
                109, 112, 108, 101, 46, 99, 111, 109, 47, 105, 115, 95, 114, 111,
                111, 116, 34, 58, 116, 114, 117, 101, 125
            };
            byte[] payloadBytesActual = Encoding.UTF8.GetBytes(payloadSample);
            CollectionAssert.AreEqual(payloadBytesExpected, payloadBytesActual);

            string payloadB64uExpected = // From the RFC example
                    "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt" +
                    "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ";
            string payloadB64uActual = JOSE.JwsHelper.Base64UrlEncode(payloadBytesActual);
            Assert.AreEqual(payloadB64uExpected, payloadB64uActual);

            string signingInput = $"{protectedB64uActual}.{payloadB64uActual}";

            byte[] signingBytesExpected = // From the RFC example
            {
                101, 121, 74, 48, 101, 88, 65, 105, 79, 105, 74, 75, 86, 49, 81,
                105, 76, 65, 48, 75, 73, 67, 74, 104, 98, 71, 99, 105, 79, 105, 74,
                73, 85, 122, 73, 49, 78, 105, 74, 57, 46, 101, 121, 74, 112, 99, 51,
                77, 105, 79, 105, 74, 113, 98, 50, 85, 105, 76, 65, 48, 75, 73, 67,
                74, 108, 101, 72, 65, 105, 79, 106, 69, 122, 77, 68, 65, 52, 77, 84,
                107, 122, 79, 68, 65, 115, 68, 81, 111, 103, 73, 109, 104, 48, 100,
                72, 65, 54, 76, 121, 57, 108, 101, 71, 70, 116, 99, 71, 120, 108, 76,
                109, 78, 118, 98, 83, 57, 112, 99, 49, 57, 121, 98, 50, 57, 48, 73,
                106, 112, 48, 99, 110, 86, 108, 102, 81
            };
            byte[] signingBytesActual = Encoding.ASCII.GetBytes(signingInput);
            CollectionAssert.AreEqual(signingBytesExpected, signingBytesActual);

            // JSON Web Key (JWK) symmetric key from the RFC example:
            //   {"kty":"oct",
            //    "k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75
            //         aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"
            //   }
            byte[] symKey = JOSE.JwsHelper.Base64UrlDecode(
                    "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75" +
                    "aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow");
            byte[] hmacExpected = // From the RFC example:
            {
                116, 24, 223, 180, 151, 153, 224, 37, 79, 250, 96, 125, 216, 173,
                187, 186, 22, 212, 37, 77, 105, 214, 191, 240, 91, 88, 5, 88, 83,
                132, 141, 121
            };
            byte[] hmacActual;
            using (var hmacAlgor = new System.Security.Cryptography.HMACSHA256(symKey))
            {
                hmacActual = hmacAlgor.ComputeHash(signingBytesActual);
            }
            CollectionAssert.AreEqual(hmacExpected, hmacActual);

            string hmacB64uExpected = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; // From RFC example
            string hmacB64uActual = JOSE.JwsHelper.Base64UrlEncode(hmacActual);
            Assert.AreEqual(hmacB64uExpected, hmacB64uActual);

            string jwsSigExpected = // From RFC example
                    "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9" +
                    ".eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt" +
                    "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ" +
                    ".dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
            string jwsSigActual = $"{protectedB64uActual}.{payloadB64uActual}.{hmacB64uActual}";
            Assert.AreEqual(jwsSigExpected, jwsSigActual);
        }
예제 #54
0
파일: Insta.cs 프로젝트: c4wrd/Insta
 private string signMessage(string message)
 {
     var hmac = new System.Security.Cryptography.HMACSHA256(System.Text.ASCIIEncoding.ASCII.GetBytes(g_apiInformation["sig_key"]));
     return BitConverter.ToString(
             hmac.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(message)
         )
     ).Replace("-", string.Empty);
 }
예제 #55
0
 // Hash Encryption
 public static string hashHmac(string input, string key)
 {
     byte[] keyBytes = System.Text.Encoding.ASCII.GetBytes(key);
     System.Security.Cryptography.HMACSHA256 hashmac = new System.Security.Cryptography.HMACSHA256(keyBytes);
     byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
     hashmac.Key = keyBytes;
     byte[] hash = hashmac.ComputeHash(inputBytes);
     return Convert.ToBase64String(hash);
 }
예제 #56
0
파일: OAuth.cs 프로젝트: vebin/WeiboSdk
        /// <summary>
        /// 站内应用使用SignedRequest获取AccessToken
        /// </summary>
        /// <param name="signedRequest">SignedRequest</param>
        /// <returns></returns>
        public AccessToken GetAccessTokenBySignedRequest(string signedRequest)
        {
            string[] parameters = signedRequest.Split('.');
            if (parameters.Length < 2)
                throw new Exception("SignedRequest格式错误。");
            var encodedSig = parameters[0];
            var payload = parameters[1];
            var sha256 = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(AppSecret));
            var expectedSig = Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(payload)));
            sha256.Clear();

            encodedSig = parameters[0].Length % 4 == 0 ? parameters[0] : parameters[0].PadRight(parameters[0].Length + (4 - parameters[0].Length % 4), '=').Replace("-", "+").Replace("_", "/");
            payload = parameters[1].Length % 4 == 0 ? parameters[1] : parameters[1].PadRight(parameters[1].Length + (4 - parameters[1].Length % 4), '=').Replace("-", "+").Replace("_", "/");

            if(encodedSig != expectedSig)
                throw new WeiboException("SignedRequest签名验证失败。");
            var result = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(payload)));

            if (result["oauth_token"] == null)
                return null;//throw new WeiboException("没有获取到授权信息,请先进行授权。");

            AccessToken token = new AccessToken();
            AccessToken = token.Token = result["oauth_token"].ToString();

            token.UID = result["user_id"].ToString();
            token.ExpiresIn = Convert.ToInt32(result["expires"].ToString());
            return token;
        }
예제 #57
0
        public string CreateSharedKeyAuth(string method, string resource, string contentMD5, DateTime requestDate, HttpClient client, string contentType, Authentication auth)
        {
            Hashtable ht = new Hashtable();
               StringBuilder sbHdrs = new StringBuilder();
               StringBuilder sbHeader = new StringBuilder();
               string rtn = string.Empty;
               //string fmtStringToSign = "{0}\n{1}\n{2}\n{3:R}\n{4}{5}";

               //string hdr = CanonicalizeHeaders(client.RequestHeaders);
               //string authValue = string.Format(fmtStringToSign, method, contentMD5, contentType, "", hdr, resource);
             // support for 2009-09-09 version
               string contentEncoding = string.Empty;
               string contentLanguage = string.Empty;
               string dateForSigning = string.Empty;
               string ifModifiedSince = string.Empty;// client.IfModifiedSince.ToString();
               string ifMatch = string.Empty;
               string ifNoneMatch = string.Empty;
               string ifUnmodifiedSince = string.Empty;
               string rangeForSigning = string.Empty;
               string clientContentLength = string.Empty;
               string clientContentType = string.Empty;

               if (client.RequestHeaders["if-match"] != null)// && client.Headers["if-match"] != "*")
             ifMatch = client.RequestHeaders["if-match"].ToString();
               if (client.RequestHeaders["if-none-match"] != null)
             ifNoneMatch = client.RequestHeaders["if-none-match"].ToString();
               if (client.RequestHeaders["if-unmodified-since"] != null)
             ifUnmodifiedSince = client.RequestHeaders["if-unmodified-since"].ToString();
               //if (client.ResponseLength> 0 || method != "GET")
               //  clientContentLength = client.ResponseLength.ToString();

               //if (client.ContentType != null)
               //  clientContentType = client.ContentType.ToString();

               //string fmtStringToSign = "{0}\n{1}\n{2}\n{3:R}\n{4}{5}";
               string fmtStringToSign = "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}{13}";
               string hdrs = CanonicalizeHeaders(client.RequestHeaders);
               //string authValue = string.Format(fmtStringToSign, method, contentMD5, client.ContentType, "", hdrs, resource);
               string authValue = string.Format(fmtStringToSign, method, contentEncoding,contentLanguage,clientContentLength, contentMD5, clientContentType,
             dateForSigning, ifModifiedSince, ifMatch,ifNoneMatch,ifUnmodifiedSince,rangeForSigning, hdrs, resource);
               byte[] signatureByteForm = System.Text.Encoding.UTF8.GetBytes(authValue);

               System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(auth.SharedKey));

               // Now build the Authorization header
               String authHeader = String.Format(CultureInfo.InvariantCulture,
                              "{0} {1}:{2}",
                              "SharedKey",
                              auth.Account,
                              System.Convert.ToBase64String(hasher.ComputeHash(signatureByteForm)
                              ));

               rtn = authHeader;

               return rtn;
        }
예제 #58
0
파일: Link.cs 프로젝트: pilehave/headweb-mp
        public void GetSwf()
        {
            try
            {
                // check if we can retrieve
                if (string.IsNullOrEmpty(swfUrl)) return;
                Uri swfUri = new Uri(swfUrl);

                if (swfCache.ContainsKey(swfUrl))
                {
                    SWFHash = swfCache[swfUrl].Hash;
                    SWFSize = swfCache[swfUrl].Size;
                }
                else
                {
                    // get the swf file from the web
                    HttpWebRequest request = WebRequest.Create(swfUri) as HttpWebRequest;
                    if (request == null) return;
                    request.Accept = "*/*";
                    request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                    request.Timeout = 5000; // don't wait longer than 5 seconds
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    System.IO.Stream responseStream;
                    if (response.ContentEncoding.ToLower().Contains("gzip"))
                        responseStream = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                    else if (response.ContentEncoding.ToLower().Contains("deflate"))
                        responseStream = new System.IO.Compression.DeflateStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                    else
                        responseStream = response.GetResponseStream();

                    byte[] tempBuff = new byte[1024 * 1024 * 10];
                    int bytesRead = 0;
                    int totalBytesRead = 0;
                    while ((bytesRead = responseStream.Read(tempBuff, totalBytesRead, tempBuff.Length - totalBytesRead)) > 0)
                    {
                        totalBytesRead += bytesRead;
                    }
                    byte[] buff = new byte[totalBytesRead];
                    Array.Copy(tempBuff, buff, totalBytesRead);

                    MemoryStream ms = new MemoryStream(buff);
                    BinaryReader br = new BinaryReader(ms);
                    // compressed swf?
                    if (br.PeekChar() == 'C')
                    {
                        // read size
                        br.BaseStream.Position = 4; // skip signature
                        SWFSize = Convert.ToInt32(br.ReadUInt32());
                        // read swf head
                        byte[] uncompressed = new byte[SWFSize];
                        br.BaseStream.Position = 0;
                        br.Read(uncompressed, 0, 8); // header data is not compressed
                        uncompressed[0] = System.Text.Encoding.ASCII.GetBytes(new char[] { 'F' })[0];
                        // un-zip
                        byte[] compressed = br.ReadBytes(SWFSize);
                        Ionic.Zlib.ZlibStream dStream = new Ionic.Zlib.ZlibStream(new MemoryStream(compressed), Ionic.Zlib.CompressionMode.Decompress);
                        int read = dStream.Read(uncompressed, 8, SWFSize - 8);

                        byte[] finalUncompressed = new byte[8 + read];
                        Array.Copy(uncompressed, finalUncompressed, 8 + read);
                        buff = finalUncompressed;
                    }
                    System.Security.Cryptography.HMACSHA256 sha256Hmac = new System.Security.Cryptography.HMACSHA256(System.Text.Encoding.ASCII.GetBytes("Genuine Adobe Flash Player 001"));
                    SWFHash = sha256Hmac.ComputeHash(buff);
                    Logger.Log(string.Format("Size of decompressed SWF: {0}, Hash:", SWFSize));
                    Logger.LogHex(SWFHash, 0, SWFHash.Length);
                    swfCache.Add(swfUrl, new SwFInfo() { Hash = SWFHash, Size = SWFSize, Time = DateTime.Now });
                }
            }
            catch (Exception ex)
            {
                Logger.Log(string.Format("Error while getting swf ({0}): {1}", swfUrl, ex.Message));
            }
        }
예제 #59
0
        private void SetAuthorizationHeader()
        {
            // Now sign the request
            // For a blob, you need to use this Canonical form:
            //  VERB + "\n" +
            //  Content - MD5 + "\n" +
            //  Content - Type + "\n" +
            //  Date + "\n" +
            //  CanonicalizedHeaders +
            //  CanonicalizedResource;

            StringBuilder signature = new StringBuilder();

            // Verb
            signature.Append(String.Format("{0}{1}", this.request.Method, "\n"));

            // Content-MD5 Header
            signature.Append("\n");

            // Content-Type Header
            signature.Append("\n");

            // Then Date, if we have already added the x-ms-date header, leave this null
            signature.Append("\n");

            // Now for CanonicalizedHeaders
            // TODO: Replace with LINQ statement
            foreach (string header in this.request.Headers)
            {
                if (header.StartsWith("x-ms"))
                {
                    signature.Append(String.Format("{0}:{1}\n", header, this.request.Headers[header]));
                }
            }

            // Now for CanonicalizedResource
            // Format is /{0}/{1} where 0 is name of the account and 1 is resources URI path
            // Also make sure any comp query params are included
            signature.Append(String.Format("/{0}{1}", this.storageEndpoint.Account, GetCanonicalizedResourceURI()));

            // Next, we need to encode our signature using the HMAC-SHA256 algorithm
            byte[] signatureByteForm = System.Text.Encoding.UTF8.GetBytes(signature.ToString());

            System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(this.storageEndpoint.Key));

            // Now build the Authorization header
            String authHeader = String.Format(CultureInfo.InvariantCulture,
                                       "{0} {1}:{2}",
                                       "SharedKey",
                                       this.storageEndpoint.Account,
                                       System.Convert.ToBase64String(hasher.ComputeHash(signatureByteForm)
                                       ));

            // And add the Authorization header to the request
            this.request.Headers.Add("Authorization", authHeader);
        }
        public string AuthorizationHeader(string method, string date, HttpWebRequest request, string ifMatch = "", string md5 = "")
        {
            string MessageSignature;

            if (IsTableStorage)
            {
                if (radioButton4.Checked)
                {
                    MessageSignature = String.Format("{0}\n\n{1}\n{2}\n{3}",
                    method,
                    "application/atom+xml",
                    now.ToString("R", System.Globalization.CultureInfo.InvariantCulture),
                    GetCanonicalizedResource(request.RequestUri, storageAccount)
                    );
                    //MessageSignature = String.Format("{0}\n{1}\n{2}\n{3}\n{4}",
                    //    method,
                    //    md5,
                    //    "application/atom+xml",
                    //    date,
                    //    GetCanonicalizedResource(request.RequestUri, storageAccount)
                    //    );
                }
                else
                {
                    MessageSignature = String.Format("{0}\n{1}\n{2}",
                        method,
                        date,
                        GetCanonicalizedResource(request.RequestUri, storageAccount)
                        );
                }
            }
            else
            {
                if (radioButton4.Checked)
                {
                    MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
                    method,
                    (method == "GET" || method == "HEAD") ? String.Empty : request.ContentLength > 0? request.ContentLength.ToString():String.Empty,
                    ifMatch,
                    GetCanonicalizedHeaders(request),
                    GetCanonicalizedResource(request.RequestUri, storageAccount),
                    md5
                    );
                    //MessageSignature = String.Format("{0}\n\n\n{1}\n{2}\n\n{3}\n\n{4}\n\n\n\n{5}{6}",
                    //    method,
                    //    (method == "GET" || method == "HEAD") ? String.Empty : request.ContentLength.ToString(),
                    //    md5,
                    //    date,
                    //    ifMatch,
                    //    GetCanonicalizedHeaders(request),
                    //    GetCanonicalizedResource(request.RequestUri, storageAccount)

                    //    );
                }
                else
                {
                    MessageSignature = String.Format("{0}\n{1}\n{2}\n{3}\n{4}{5}",
                        method,
                        md5,
                        "text/plain; charset=UTF-8",
                        date,
                        GetCanonicalizedHeaders(request),
                        GetCanonicalizedResource(request.RequestUri, storageAccount)

                        );
                }
            }
            Debug.WriteLine("=============================");
            Debug.WriteLine(MessageSignature);
            Debug.WriteLine("=============================");
            byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature);
            System.Security.Cryptography.HMACSHA256 SHA256 = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(storageKey));
            String AuthorizationHeader = storageAccount + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));
            if (radioButton4.Checked)
            {
                AuthorizationHeader = "SharedKey " + AuthorizationHeader;
            }
            else
            {
                AuthorizationHeader = "SharedKey Lite " + AuthorizationHeader;
            }
            return AuthorizationHeader;
        }