コード例 #1
0
        private KeyedHashAlgorithm CreateKeyedHashAlgorithm(SigningAlgorithm algorithmName)
        {
            KeyedHashAlgorithm algorithm;

            switch (algorithmName)
            {
            case SigningAlgorithm.HmacSHA256:
                algorithm = new HMACSHA256();
                break;

            case SigningAlgorithm.HmacSHA1:
                algorithm = new HMACSHA1();
                break;

            case SigningAlgorithm.Md5:
                algorithm = new HMACMD5();
                break;

            default:
                throw new Exception(string.Format("KeyedHashAlgorithm {0} was not found.",
                                                  algorithmName.ToString()));
            }

            return(algorithm);
        }
コード例 #2
0
            /// <summary>
            /// Computes a hash-based message authentication code
            /// </summary>
            /// <param name="data">Input to compute the hash code for</param>
            /// <param name="key">Signing key</param>
            /// <param name="algorithmName">Hashing algorithm to use</param>
            /// <returns>Computed hash code in bytes</returns>
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                if (key == null || key.Length == 0)
                {
                    throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
                }

                if (data == null || data.Length == 0)
                {
                    throw new ArgumentNullException("data", "Please specify data to sign.");
                }

                KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture));

                if (null == algorithm)
                {
                    throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use.");
                }

                try
                {
                    algorithm.Key = key;
                    byte[] bytes = algorithm.ComputeHash(data);
                    return(bytes);
                }
                finally
                {
                    algorithm.Clear();
                }
            }
コード例 #3
0
            /// <summary>
            /// Computes a hash-based message authentication code
            /// </summary>
            /// <param name="data">Input to compute the hash code for</param>
            /// <param name="key">Signing key</param>
            /// <param name="algorithmName">Hashing algorithm to use</param>
            /// <returns>Computed hash code in base-64</returns>
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                if (String.IsNullOrEmpty(key))
                {
                    throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
                }

                if (data == null || data.Length == 0)
                {
                    throw new ArgumentNullException("data", "Please specify data to sign.");
                }

                KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture));

                if (null == algorithm)
                {
                    throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use.");
                }

                try
                {
                    algorithm.Key = Encoding.UTF8.GetBytes(key);
                    byte[] bytes = algorithm.ComputeHash(data);
                    return(Convert.ToBase64String(bytes));
                }
                finally
                {
                    algorithm.Clear();
                }
            }
コード例 #4
0
        private static void SignHttp(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
            string           text      = Guid.NewGuid().ToString();
            string           formattedCurrentTimestampRFC = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            bool             flag = IsHttpsRequest(request);

            flag = false;
            request.Headers["Date"]       = formattedCurrentTimestampRFC;
            request.Headers["X-Amz-Date"] = formattedCurrentTimestampRFC;
            request.Headers.Remove("X-Amzn-Authorization");
            string text2 = request.Endpoint.Host;

            if (!request.Endpoint.IsDefaultPort)
            {
                text2 = text2 + ":" + request.Endpoint.Port;
            }
            request.Headers["host"] = text2;
            byte[] array = null;
            string text3;

            if (flag)
            {
                request.Headers["x-amz-nonce"] = text;
                text3 = formattedCurrentTimestampRFC + text;
                array = Encoding.UTF8.GetBytes(text3);
            }
            else
            {
                Uri endpoint = request.Endpoint;
                if (!string.IsNullOrEmpty(request.ResourcePath))
                {
                    endpoint = new Uri(request.Endpoint, request.ResourcePath);
                }
                text3 = request.HttpMethod + "\n" + GetCanonicalizedResourcePath(endpoint) + "\n" + GetCanonicalizedQueryString(request.Parameters) + "\n" + GetCanonicalizedHeadersForStringToSign(request) + "\n" + GetRequestPayload(request);
                array = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(Encoding.UTF8.GetBytes(text3));
            }
            metrics.AddProperty(Metric.StringToSign, text3);
            string        str           = AbstractAWSSigner.ComputeHash(array, awsSecretAccessKey, algorithm);
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.Append(flag ? "AWS3-HTTPS" : "AWS3");
            stringBuilder.Append(" ");
            stringBuilder.Append("AWSAccessKeyId=" + awsAccessKeyId + ",");
            stringBuilder.Append("Algorithm=" + algorithm.ToString() + ",");
            if (!flag)
            {
                stringBuilder.Append(GetSignedHeadersComponent(request) + ",");
            }
            stringBuilder.Append("Signature=" + str);
            string value = stringBuilder.ToString();

            request.Headers["X-Amzn-Authorization"] = value;
        }
コード例 #5
0
            private KeyedHashAlgorithm CreateKeyedHashAlgorithm(SigningAlgorithm algorithm)
            {
                switch (algorithm)
                {
                case SigningAlgorithm.HmacSHA256:
                    return(new HMACSHA256());

                case SigningAlgorithm.HmacSHA1:
                    return(new HMACSHA1());

                default:
                    throw new Exception("Unknown algorithm: " + algorithm.ToString());
                }
            }
コード例 #6
0
ファイル: CryptoUtil.pcl.cs プロジェクト: tsujimic/s3hash-net
            MacAlgorithm Convert(SigningAlgorithm algorithm)
            {
                switch (algorithm)
                {
                case SigningAlgorithm.HmacSHA256:
                    return(MacAlgorithm.HmacSha256);

                case SigningAlgorithm.HmacSHA1:
                    return(MacAlgorithm.HmacSha1);

                default:
                    throw new Exception("Unknown signing algorithm: " + algorithm.ToString());
                }
            }
コード例 #7
0
ファイル: CryptoUtil.unity.cs プロジェクト: aws/aws-sdk-net
            /// <summary>
            /// The iOS il2cpp implementation of System.Security.Cryptography.RandomNumberGenerator,
            /// which is called by the initialization of KeyedHashAlgorithm.Create for a given
            /// algorithm name, is not threadsafe. We keep track of which algorithms have been
            /// initialized, and retain a lock if this is the first time we create a particular
            /// algorithm.
            /// </summary>
            /// <param name="algorithmName"></param>
            /// <returns></returns>
            private KeyedHashAlgorithm ThreadSafeCreateKeyedHashedAlgorithm(SigningAlgorithm algorithmName)
            {
                string algorithmNameUpper = algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture);
                KeyedHashAlgorithm algorithm = null;
                bool firstCreation = true;
                lock (_keyedHashAlgorithmCreationLock)
                {
                    firstCreation = !_initializedAlgorithmNames.Contains(algorithmNameUpper);

                    if (firstCreation)
                    {
                        algorithm = KeyedHashAlgorithm.Create(algorithmNameUpper);
                        _initializedAlgorithmNames.Add(algorithmNameUpper);
                    }
                }
                if (!firstCreation)
                {
                    algorithm = KeyedHashAlgorithm.Create(algorithmNameUpper);
                }
                return algorithm;
            }
コード例 #8
0
            private KeyedHashAlgorithm ThreadSafeCreateKeyedHashedAlgorithm(SigningAlgorithm algorithmName)
            {
                string             text   = algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture);
                KeyedHashAlgorithm result = null;
                bool flag = true;

                lock (_keyedHashAlgorithmCreationLock)
                {
                    flag = !_initializedAlgorithmNames.Contains(text);
                    if (flag)
                    {
                        result = KeyedHashAlgorithm.Create(text);
                        _initializedAlgorithmNames.Add(text);
                    }
                }
                if (!flag)
                {
                    result = KeyedHashAlgorithm.Create(text);
                }
                return(result);
            }
コード例 #9
0
            /// <summary>
            /// The iOS il2cpp implementation of System.Security.Cryptography.RandomNumberGenerator,
            /// which is called by the initialization of KeyedHashAlgorithm.Create for a given
            /// algorithm name, is not threadsafe. We keep track of which algorithms have been
            /// initialized, and retain a lock if this is the first time we create a particular
            /// algorithm.
            /// </summary>
            /// <param name="algorithmName"></param>
            /// <returns></returns>
            private KeyedHashAlgorithm ThreadSafeCreateKeyedHashedAlgorithm(SigningAlgorithm algorithmName)
            {
                string             algorithmNameUpper = algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture);
                KeyedHashAlgorithm algorithm          = null;
                bool firstCreation = true;

                lock (_keyedHashAlgorithmCreationLock)
                {
                    firstCreation = !_initializedAlgorithmNames.Contains(algorithmNameUpper);

                    if (firstCreation)
                    {
                        algorithm = KeyedHashAlgorithm.Create(algorithmNameUpper);
                        _initializedAlgorithmNames.Add(algorithmNameUpper);
                    }
                }
                if (!firstCreation)
                {
                    algorithm = KeyedHashAlgorithm.Create(algorithmNameUpper);
                }
                return(algorithm);
            }
コード例 #10
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                if (String.IsNullOrEmpty(key))
                    throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");

                if (data == null || data.Length == 0)
                    throw new ArgumentNullException("data", "Please specify data to sign.");

                KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture));
                if (null == algorithm)
                    throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use.");

                try
                {
                    algorithm.Key = Encoding.UTF8.GetBytes(key);
                    byte[] bytes = algorithm.ComputeHash(data);
                    return Convert.ToBase64String(bytes);
                }
                finally
                {
                    algorithm.Clear();
                }
            }
コード例 #11
0
        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature.
        /// </summary>
        protected string ComputeHash(string data, string clearkey, SecureString secureKey, SigningAlgorithm algorithm)
        {
            try
            {
                KeyedHashAlgorithm mac = KeyedHashAlgorithm.Create(algorithm.ToString().ToUpper());

                string signature;
                if (string.IsNullOrEmpty(clearkey))
                {
                    signature = AWSSDKUtils.HMACSign(data, secureKey, mac);
                }
                else
                {
                    signature = AWSSDKUtils.HMACSign(data, clearkey, mac);
                }

                return signature;
            }
            catch (Exception e)
            {
                throw new SignatureException("Failed to generate signature: " + e.Message, e);
            }
        }
コード例 #12
0
        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature.
        /// </summary>
        protected string ComputeHash(byte[] data, string clearkey, SecureString secureKey, SigningAlgorithm algorithm)
        {
            try
            {
                KeyedHashAlgorithm mac = KeyedHashAlgorithm.Create(algorithm.ToString().ToUpper());

                string signature;
                if (string.IsNullOrEmpty(clearkey))
                {
                    signature = AWSSDKUtils.HMACSign(data, secureKey, mac);
                }
                else
                {
                    signature = AWSSDKUtils.HMACSign(data, clearkey, mac);
                }

                return(signature);
            }
            catch (Exception e)
            {
                throw new SignatureException("Failed to generate signature: " + e.Message, e);
            }
        }
コード例 #13
0
 string ConvertToAlgorithName(SigningAlgorithm algorithm)
 {
     switch (algorithm)
     {
         case SigningAlgorithm.HmacSHA256:
             return MacAlgorithmNames.HmacSha256;
         case SigningAlgorithm.HmacSHA1:
             return MacAlgorithmNames.HmacSha1;
         default:
             throw new Exception("Unknown signing algorithm: " + algorithm.ToString());
     }
 }
コード例 #14
0
ファイル: CryptoUtil.wp8.cs プロジェクト: rossmas/aws-sdk-net
 private KeyedHashAlgorithm CreateKeyedHashAlgorithm(SigningAlgorithm algorithm)
 {
     switch (algorithm)
     {
         case SigningAlgorithm.HmacSHA256:
             return new HMACSHA256();
         case SigningAlgorithm.HmacSHA1:
             return new HMACSHA1();
         default:
             throw new Exception("Unknown algorithm: " + algorithm.ToString());
     }
 }
コード例 #15
0
ファイル: CryptoUtil.coreclr.cs プロジェクト: aws/aws-sdk-net
            KeyedHashAlgorithm CreateKeyedHashAlgorithm(SigningAlgorithm algorithmName)
            {
                KeyedHashAlgorithm algorithm;
                switch (algorithmName)
                {
                    case SigningAlgorithm.HmacSHA256:
                        algorithm = new HMACSHA256();
                        break;
                    case SigningAlgorithm.HmacSHA1:
                        algorithm = new HMACSHA1();
                        break;
                    default:
                        throw new Exception(string.Format("KeyedHashAlgorithm {0} was not found.", algorithmName.ToString()));
                }

                return algorithm;
            }
コード例 #16
0
ファイル: AWS3Signer.cs プロジェクト: micheldavid/aws-sdk-net
        private void SignHttp(IRequest request, ClientConfig clientConfig, string awsAccessKeyId, string awsSecretAccessKey, SecureString secureKey)
        {
            SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
            string           nonce     = Guid.NewGuid().ToString();
            string           date      = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            bool             isHttps   = IsHttpsRequest(request);

            // Temporarily disabling the AWS3 HTTPS signing scheme and only using AWS3 HTTP
            isHttps = false;

            request.Headers["Date"]       = date;
            request.Headers["X-Amz-Date"] = date;

            // AWS3 HTTP requires that we sign the Host header
            // so we have to have it in the request by the time we sign.
            string hostHeader = request.Endpoint.Host;

            if (!request.Endpoint.IsDefaultPort)
            {
                hostHeader += ":" + request.Endpoint.Port;
            }
            request.Headers["Host"] = hostHeader;

            byte[] bytesToSign;
            string stringToSign;

            if (isHttps)
            {
                request.Headers[NONCE_HEADER] = nonce;
                stringToSign = date + nonce;
                bytesToSign  = Encoding.UTF8.GetBytes(stringToSign);
            }
            else
            {
                Uri url = request.Endpoint;
                if (!string.IsNullOrEmpty(request.ResourcePath))
                {
                    url = new Uri(request.Endpoint, request.ResourcePath);
                }

                stringToSign = request.HttpMethod + "\n"
                               + GetCanonicalizedResourcePath(url) + "\n"
                               + GetCanonicalizedQueryString(request.Parameters) + "\n"
                               + GetCanonicalizedHeadersForStringToSign(request) + "\n"
                               + GetRequestPayload(request);

                bytesToSign = CanonicalizationHash.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
            }

            string signature = ComputeHash(bytesToSign, awsSecretAccessKey, secureKey, algorithm);

            StringBuilder builder = new StringBuilder();

            builder.Append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME);
            builder.Append(" ");
            builder.Append("AWSAccessKeyId=" + awsAccessKeyId + ",");
            builder.Append("Algorithm=" + algorithm.ToString() + ",");

            if (!isHttps)
            {
                builder.Append(GetSignedHeadersComponent(request) + ",");
            }

            builder.Append("Signature=" + signature);
            string authorizationHeader = builder.ToString();

            request.Headers[AUTHORIZATION_HEADER] = authorizationHeader;
        }
コード例 #17
0
        private static void SignHttp(IRequest request, RequestMetrics metrics, string awsAccessKeyId, string awsSecretAccessKey)
        {
            SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
            string           nonce     = Guid.NewGuid().ToString();
            string           date      = AWSSDKUtils.FormattedCurrentTimestampRFC822;
            bool             isHttps   = IsHttpsRequest(request);

            // Temporarily disabling the AWS3 HTTPS signing scheme and only using AWS3 HTTP
            isHttps = false;

            request.Headers[HeaderKeys.DateHeader]     = date;
            request.Headers[HeaderKeys.XAmzDateHeader] = date;

            // Clear out existing auth header (can be there if retry)
            request.Headers.Remove(HeaderKeys.XAmzAuthorizationHeader);

            // AWS3 HTTP requires that we sign the Host header
            // so we have to have it in the request by the time we sign.
            string hostHeader = request.Endpoint.Host;

            if (!request.Endpoint.IsDefaultPort)
            {
                hostHeader += ":" + request.Endpoint.Port;
            }
            request.Headers[HeaderKeys.HostHeader] = hostHeader;

            byte[] bytesToSign = null;
            string stringToSign;

            if (isHttps)
            {
                request.Headers[HeaderKeys.XAmzNonceHeader] = nonce;
                stringToSign = date + nonce;
                bytesToSign  = Encoding.UTF8.GetBytes(stringToSign);
            }
            else
            {
                Uri url = request.Endpoint;
                if (!string.IsNullOrEmpty(request.ResourcePath))
                {
                    url = new Uri(request.Endpoint, request.ResourcePath);
                }

                stringToSign = request.HttpMethod + "\n"
                               + GetCanonicalizedResourcePath(url) + "\n"
                               + GetCanonicalizedQueryString(request.Parameters) + "\n"
                               + GetCanonicalizedHeadersForStringToSign(request) + "\n"
                               + GetRequestPayload(request);

                bytesToSign = CryptoUtilFactory.CryptoInstance.ComputeSHA256Hash(Encoding.UTF8.GetBytes(stringToSign));
            }

            metrics.AddProperty(Metric.StringToSign, stringToSign);
            string signature = ComputeHash(bytesToSign, awsSecretAccessKey, algorithm);

            StringBuilder builder = new StringBuilder();

            builder.Append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME);
            builder.Append(" ");
            builder.Append("AWSAccessKeyId=" + awsAccessKeyId + ",");
            builder.Append("Algorithm=" + algorithm.ToString() + ",");

            if (!isHttps)
            {
                builder.Append(GetSignedHeadersComponent(request) + ",");
            }

            builder.Append("Signature=" + signature);
            string authorizationHeader = builder.ToString();

            request.Headers[HeaderKeys.XAmzAuthorizationHeader] = authorizationHeader;
        }
コード例 #18
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                if (key == null || key.Length == 0)
                    throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");

                if (data == null || data.Length == 0)
                    throw new ArgumentNullException("data", "Please specify data to sign.");

                KeyedHashAlgorithm algorithm = KeyedHashAlgorithm.Create(algorithmName.ToString().ToUpper(CultureInfo.InvariantCulture));
                if (null == algorithm)
                    throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use.");

                try
                {
                    algorithm.Key = key;
                    byte[] bytes = algorithm.ComputeHash(data);
                    return bytes;
                }
                finally
                {
                    algorithm.Clear();
                }
            }