예제 #1
0
        public static Uri SignatureAlgorithmToXmlDSigUri(SigningAlgorithm signatureAlgorithm, HashAlgorithmName hashAlgorithmName)
        {
            switch (signatureAlgorithm)
            {
            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.MD5.Name:
                return(OpcKnownUris.SignatureAlgorithms.rsaMD5);

            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.SHA1.Name:
                return(OpcKnownUris.SignatureAlgorithms.rsaSHA1);

            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.SHA256.Name:
                return(OpcKnownUris.SignatureAlgorithms.rsaSHA256);

            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.SHA384.Name:
                return(OpcKnownUris.SignatureAlgorithms.rsaSHA384);

            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.SHA512.Name:
                return(OpcKnownUris.SignatureAlgorithms.rsaSHA512);

            case SigningAlgorithm.ECDSA when hashAlgorithmName.Name == HashAlgorithmName.SHA1.Name:
                return(OpcKnownUris.SignatureAlgorithms.ecdsaSHA1);

            case SigningAlgorithm.ECDSA when hashAlgorithmName.Name == HashAlgorithmName.SHA256.Name:
                return(OpcKnownUris.SignatureAlgorithms.ecdsaSHA256);

            case SigningAlgorithm.ECDSA when hashAlgorithmName.Name == HashAlgorithmName.SHA384.Name:
                return(OpcKnownUris.SignatureAlgorithms.ecdsaSHA384);

            case SigningAlgorithm.ECDSA when hashAlgorithmName.Name == HashAlgorithmName.SHA512.Name:
                return(OpcKnownUris.SignatureAlgorithms.ecdsaSHA512);

            default:
                throw new NotSupportedException("The algorithm specified is not supported.");
            }
        }
예제 #2
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                var crypt = MacAlgorithmProvider.OpenAlgorithm(ConvertToAlgorithName(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.");
                }

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

                IBuffer dataBuffer = CryptographicBuffer.CreateFromByteArray(data);
                var keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
                var cryptoKey = crypt.CreateKey(keyBuffer);

                var sigBuffer = CryptographicEngine.Sign(cryptoKey, dataBuffer);
                string signature = CryptographicBuffer.EncodeToBase64String(sigBuffer);
                return signature;
            }
예제 #3
0
        public static string EnumToString(SigningAlgorithm signingAlgorithm)
        {
            string result = null;

            switch (signingAlgorithm)
            {
            case SigningAlgorithm.RSA_SHA256:
                result = SHA256;
                break;

            case SigningAlgorithm.RSA_SHA384:
                result = SHA384;
                break;

            case SigningAlgorithm.RSA_SHA512:
                result = SHA512;
                break;
            }

            if (string.IsNullOrEmpty(result))
            {
                throw new AuthenticationException(string.Format(Resources.Unsupported_Signing_Algorithm, signingAlgorithm));
            }

            return(result);
        }
예제 #4
0
        public static string SignatureAlgorithmToJwsAlgId(SigningAlgorithm signatureAlgorithm, HashAlgorithmName hashAlgorithmName)
        {
            switch (signatureAlgorithm)
            {
            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.SHA256.Name:
                return("RS256");

            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.SHA384.Name:
                return("RS384");

            case SigningAlgorithm.RSA when hashAlgorithmName.Name == HashAlgorithmName.SHA512.Name:
                return("RS512");

            case SigningAlgorithm.ECDSA when hashAlgorithmName.Name == HashAlgorithmName.SHA256.Name:
                return("ES256");

            case SigningAlgorithm.ECDSA when hashAlgorithmName.Name == HashAlgorithmName.SHA384.Name:
                return("ES384");

            case SigningAlgorithm.ECDSA when hashAlgorithmName.Name == HashAlgorithmName.SHA512.Name:
                return("ES512");

            default:
                throw new NotSupportedException("The algorithm specified is not supported.");
            }
        }
예제 #5
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(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.");
                }

                if (null == algorithm)
                {
                    throw new ArgumentNullException("algorithm", "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();
                }
            }
예제 #6
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);
        }
예제 #7
0
        public byte[] HmacSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
        {
            if (key == null || key.Length == 0)
            {
                throw new ArgumentNullException(nameof(key), "Please specify a Secret Signing Key.");
            }
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException(nameof(data), "Please specify data to sign.");
            }

            KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(algorithmName);

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

            try
            {
                algorithm.Key = key;
                byte[] bytes = algorithm.ComputeHash(data);
                return(bytes);
            }
            finally
            {
                algorithm.Dispose();
            }
        }
예제 #8
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.");
                }

                if (algorithmName == SigningAlgorithm.HmacSHA1)
                {
                    using (HMACSHA1 mac = new HMACSHA1(Encoding.UTF8.GetBytes(key)))
                    {
                        byte[] hash = mac.ComputeHash(data);
                        return(Convert.ToBase64String(hash));
                    }
                }
                else if (algorithmName == SigningAlgorithm.HmacSHA256)
                {
                    using (HMACSHA256 mac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
                    {
                        byte[] hash = mac.ComputeHash(data);
                        return(Convert.ToBase64String(hash));
                    }
                }
                else
                {
                    throw new ArgumentException("不合法的参数" + nameof(algorithmName));
                }
            }
예제 #9
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();
                }
            }
예제 #10
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 keyedHashAlgorithm = ThreadSafeCreateKeyedHashedAlgorithm(algorithmName);

                if (keyedHashAlgorithm != null)
                {
                    try
                    {
                        keyedHashAlgorithm.Key = key;
                        return(keyedHashAlgorithm.ComputeHash(data));
                    }
                    finally
                    {
                        keyedHashAlgorithm.Clear();
                    }
                }
                throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use.");
            }
예제 #11
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                throw new NotImplementedException();
                //KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(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.");
                //}

                //if (null == algorithm)
                //{
                //    throw new ArgumentNullException("algorithm", "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();
                //}
            }
예제 #12
0
        public string[] ComputeToken(
            IRequest request,
            X509Certificate2 signingCertificate,
            SigningAlgorithm signingAlgorithm,
            string samlTokenXml)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (signingCertificate == null)
            {
                throw new ArgumentNullException(nameof(signingCertificate));
            }
            if (samlTokenXml == null)
            {
                throw new ArgumentNullException(nameof(samlTokenXml));
            }

            using (var rsaPrivateKey = signingCertificate.GetRSAPrivateKey()) {
                return(new TokenFormatter().Format(
                           new Token(request, rsaPrivateKey, signingAlgorithm, samlTokenXml),
                           _maxTokenChunkLength
                           ));
            }
        }
예제 #13
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                throw new NotImplementedException();
                //KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(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.");
                //}

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

                //try
                //{
                //    algorithm.Key = key;
                //    byte[] bytes = algorithm.ComputeHash(data);
                //    return bytes;
                //}
                //finally
                //{
                //    algorithm.Clear();
                //}
            }
예제 #14
0
        public void FormatNotChunkedToken()
        {
            // Arrange
            var tokenMock = new Mock <IToken>();
            var nonceMock = new Mock <Nonce>();

            nonceMock.Setup(n => n.ToString()).Returns("123:654");

            var samlToken = "<xml>saml</xml>";

            tokenMock.Setup <string>(t => t.SamlToken).Returns(samlToken);

            var nonce = nonceMock.Object;

            tokenMock.Setup <Nonce>(t => t.Nonce).Returns(nonce);

            byte[] bodyHash = { 1, 2, 3 };
            tokenMock.Setup <byte[]>(t => t.BodyHash).Returns(bodyHash);

            SigningAlgorithm signAlg = SigningAlgorithm.RSA_SHA384;

            tokenMock.Setup <SigningAlgorithm>(t => t.SignatureAlgorithm).Returns(signAlg);

            byte[] signature = { 4, 5, 6 };
            tokenMock.Setup <byte[]>(t => t.Signature).Returns(signature);

            var expected = GetExpected(samlToken, nonce, bodyHash, signAlg, signature);

            // Act
            var actual = new TokenFormatter().Format(tokenMock.Object, 4086);

            // Assert
            Assert.AreEqual(1, actual.Length);
            Assert.AreEqual(expected, actual[0]);
        }
예제 #15
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.");
                }

                if (algorithmName == SigningAlgorithm.HmacSHA1)
                {
                    using (HMACSHA1 mac = new HMACSHA1(key))
                    {
                        byte[] hash = mac.ComputeHash(data);
                        return(hash);
                    }
                }
                else if (algorithmName == SigningAlgorithm.HmacSHA256)
                {
                    using (HMACSHA256 mac = new HMACSHA256(key))
                    {
                        byte[] hash = mac.ComputeHash(data);
                        return(hash);
                    }
                }
                else
                {
                    throw new ArgumentException("不合法的参数" + nameof(algorithmName));
                }
            }
예제 #16
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                var crypt = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(Convert(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.");
                }

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

                var dataBuffer = WinRTCrypto.CryptographicBuffer.CreateFromByteArray(data);
                var keyBuffer  = WinRTCrypto.CryptographicBuffer.ConvertStringToBinary(key, Encoding.UTF8);
                var cryptoKey  = crypt.CreateKey(keyBuffer);

                var sigBuffer = WinRTCrypto.CryptographicEngine.Sign(cryptoKey, dataBuffer);
                var signature = WinRTCrypto.CryptographicBuffer.EncodeToBase64String(sigBuffer);

                return(signature);
            }
예제 #17
0
        public string HmacSign(byte[] data, string key, SigningAlgorithm algorithmName)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key), "Please specify a Secret Sign Key.");
            }
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException(nameof(data), "Please specify data to sign.");
            }

            KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(algorithmName);

            if (algorithm == null)
            {
                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.Dispose();
            }
        }
예제 #18
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(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.");
                }

                if (null == algorithm)
                {
                    throw new ArgumentNullException("algorithm", "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();
                }
            }
예제 #19
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                var crypt = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(Convert(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.");
                }

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

                var dataBuffer = WinRTCrypto.CryptographicBuffer.CreateFromByteArray(data);
                var keyBuffer  = WinRTCrypto.CryptographicBuffer.CreateFromByteArray(key);
                var cryptoKey  = crypt.CreateKey(keyBuffer);

                var sigBuffer = WinRTCrypto.CryptographicEngine.Sign(cryptoKey, dataBuffer);

                byte[] result;
                WinRTCrypto.CryptographicBuffer.CopyToByteArray(sigBuffer, out result);
                return(result);
            }
예제 #20
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(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.");
                }

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

                try
                {
                    algorithm.Key = key;
                    byte[] bytes = algorithm.ComputeHash(data);
                    return(bytes);
                }
                finally
                {
                    algorithm.Clear();
                }
            }
예제 #21
0
        public string HmacSign(byte[] data, string key, SigningAlgorithm algorithmName)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key), "请指定一个签名的加密密钥");
            }
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException(nameof(data), "请指定需要签名的数据");
            }

            var algorithm = CreateKeyedHashAlgorithm(algorithmName);

            if (algorithm == null)
            {
                throw new InvalidOperationException("请指定一个签名的哈希算法: KeyedHashAlgorithm");
            }

            try
            {
                algorithm.Key = Encoding.UTF8.GetBytes(key);
                var bytes = algorithm.ComputeHash(data);
                return(Convert.ToBase64String(bytes));
            }
            finally
            {
                algorithm.Dispose();
            }
        }
예제 #22
0
        public AlgorithmInfo(SigningAlgorithm algorithm)
        {
            this.SigningAlgorithm = algorithm;

            switch (algorithm)
            {
                case SigningAlgorithm.RSASha1:
                    {
                        this.HashAlgorithm = new SHA1Managed();
                        this.Name = "rsa-sha1";

                        break;
                    }
                case SigningAlgorithm.RSASha256:
                    {
                        this.HashAlgorithm = new SHA256Managed();
                        this.Name = "rsa-sha256";

                        break;
                    }

                default:
                    {
                        throw new ArgumentException("Invalid SigningAlgorithm value", "algorithm");
                    }

            }
        }
예제 #23
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 keyedHashAlgorithm = ThreadSafeCreateKeyedHashedAlgorithm(algorithmName);

                if (keyedHashAlgorithm != null)
                {
                    try
                    {
                        keyedHashAlgorithm.Key = Encoding.UTF8.GetBytes(key);
                        return(Convert.ToBase64String(keyedHashAlgorithm.ComputeHash(data)));
                    }
                    finally
                    {
                        keyedHashAlgorithm.Clear();
                    }
                }
                throw new InvalidOperationException("Please specify a KeyedHashAlgorithm to use.");
            }
예제 #24
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                var crypt = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(Convert(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.");
                }

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

                var dataBuffer = WinRTCrypto.CryptographicBuffer.CreateFromByteArray(data);
                var keyBuffer = WinRTCrypto.CryptographicBuffer.CreateFromByteArray(key);
                var cryptoKey = crypt.CreateKey(keyBuffer);

                var sigBuffer = WinRTCrypto.CryptographicEngine.Sign(cryptoKey, dataBuffer);
                byte[] result;
                WinRTCrypto.CryptographicBuffer.CopyToByteArray(sigBuffer, out result);
                return result;
            }
예제 #25
0
 public Token(IRequest request, RSA signer, SigningAlgorithm signingAlgorithm, string samlTokenXml)
 {
     _samlTokenXml      = samlTokenXml;
     _nonce             = Nonce.FromNow();
     SignatureAlgorithm = signingAlgorithm;
     _bodyHash          = ComputeBodyHash(request);
     _signature         = ComputeSignature(request, signer);
 }
예제 #26
0
 public Token(string samlTokenXml, Nonce nonce, SigningAlgorithm signingAlgorithm, byte[] bodyHash, byte[] signature)
 {
     _samlTokenXml      = samlTokenXml;
     _nonce             = nonce;
     SignatureAlgorithm = signingAlgorithm;
     _bodyHash          = bodyHash;
     _signature         = signature;
 }
예제 #27
0
 protected static string ComputeHash(string data, string key, SigningAlgorithm algorithm)
 {
     try
     {
         return(CryptoUtilFactory.CryptoInstance.HmacSign(data, key, algorithm));
     }
     catch (Exception e)
     {
         throw new SignatureException("Failed to generate signature: " + e.Message, e);
     }
 }
예제 #28
0
        PrivateKeySigner(string privateKey, SigningAlgorithm signingAlgorithm)
        {
            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }

            _key = OpenSslKey.DecodeOpenSSLPrivateKey(privateKey);

            _algorithmInfo = new AlgorithmInfo(signingAlgorithm);
        }
예제 #29
0
 protected static string ComputeHash(byte[] data, string secretkey, SigningAlgorithm algorithm)
 {
     try
     {
         return(CryptoUtilFactory.CryptoInstance.HMACSign(data, secretkey, algorithm));
     }
     catch (Exception ex)
     {
         throw new Amazon.Runtime.SignatureException("Failed to generate signature: " + ex.Message, ex);
     }
 }
예제 #30
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;
        }
예제 #31
0
 /// <summary>
 /// 方法描述:签名
 /// </summary>
 /// <param name="data">二进制数据</param>
 /// <param name="key">密钥</param>
 /// <param name="algorithm">算法</param>
 /// <returns>HMAC计算的结果</returns>
 protected byte[] Sign(byte[] data, byte[] key, SigningAlgorithm algorithm)
 {
     try
     {
         HMAC hMAC = SigningAlgorithmHMACFactory.GetSigningHMACAlgorithm(algorithm, key);
         return(hMAC.ComputeHash(data));
     }
     catch (Exception e)
     {
         throw new Exception("Unable to calculate a request signature: ", e);
     }
 }
예제 #32
0
        public byte[] Hash(byte[] data, SigningAlgorithm algorithm)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            using (var hash = GetHash(algorithm))
            {
                return(hash.ComputeHash(data));
            }
        }
예제 #33
0
        public void Signing_VerifyAesGmacSigning()
        {
            #region Check Applicability
            TestConfig.CheckDialect(DialectRevision.Smb311);
            TestConfig.CheckSigning();
            #endregion

            var signingAlgorithms = new SigningAlgorithm[] { SigningAlgorithm.AES_GMAC };
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client sends NEGOTIATE with the Aes-GMAC signing algorithm and NEGOTIATE_SIGNING_REQUIRED.");
            client.NegotiateWithContexts(
                Packet_Header_Flags_Values.NONE,
                Smb2Utility.GetDialects(DialectRevision.Smb311),
                SecurityMode_Values.NEGOTIATE_SIGNING_REQUIRED,
                preauthHashAlgs: new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 },
                compressionFlags: SMB2_COMPRESSION_CAPABILITIES_Flags.SMB2_COMPRESSION_CAPABILITIES_FLAG_NONE,
                signingAlgorithms: signingAlgorithms,
                checker: (Packet_Header header, NEGOTIATE_Response response) =>
            {
                BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SUCCESS, header.Status, "SUT MUST return STATUS_SUCCESS if the negotiation finished successfully.");
            });

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client sends SESSION_SETUP request and expects response.");
            client.SessionSetup(
                TestConfig.DefaultSecurityPackage,
                TestConfig.SutComputerName,
                TestConfig.AccountCredential,
                TestConfig.UseServerGssToken,
                SESSION_SETUP_Request_SecurityMode_Values.NEGOTIATE_SIGNING_ENABLED);

            string uncSharepath =
                Smb2Utility.GetUncPath(TestConfig.SutComputerName, TestConfig.BasicFileShare);
            uint treeId;
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Client sends TREE_CONNECT to share: {0}", uncSharepath);
            client.TreeConnect(
                uncSharepath,
                out treeId,
                (Packet_Header header, TREE_CONNECT_Response response) =>
            {
                BaseTestSite.Assert.AreEqual(
                    Smb2Status.STATUS_SUCCESS,
                    header.Status,
                    "TreeConnect should succeed, actually server returns {0}.", Smb2Status.GetStatusCode(header.Status));

                BaseTestSite.Assert.AreEqual(
                    Packet_Header_Flags_Values.FLAGS_SIGNED,
                    Packet_Header_Flags_Values.FLAGS_SIGNED & header.Flags,
                    "Server should set SMB2_FLAGS_SIGNED bit in the Flags field of the SMB2 header");
            });

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "Tear down the client by sending the following requests: TREE_DISCONNECT; LOG_OFF");
            client.TreeDisconnect(treeId);
            client.LogOff();
        }
예제 #34
0
        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature.
        /// </summary>
        protected static string ComputeHash(byte[] data, string secretkey, SigningAlgorithm algorithm)
        {
            try
            {
                string signature = CryptoUtilFactory.CryptoInstance.HMACSign(data, secretkey, algorithm);

                return(signature);
            }
            catch (Exception e)
            {
                throw new SignatureException("Failed to generate signature: " + e.Message, e);
            }
        }
예제 #35
0
 private HMAC GetAlgorithm(SigningAlgorithm algorithm, byte[] key)
 {
     switch(algorithm)
     {
         case SigningAlgorithm.HS256:
             return new HMACSHA256(key);
         case SigningAlgorithm.HS384:
             return  new HMACSHA384(key);
         case SigningAlgorithm.HS512:
             return new HMACSHA512(key);
     }
     throw new NotSupportedException("No signing found for algorithm "+algorithm);
 }
예제 #36
0
        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature.
        /// </summary>
        protected static string ComputeHash(byte[] data, string secretkey, SigningAlgorithm algorithm)
        {
            try
            {
                string signature = CryptoUtilFactory.CryptoInstance.HMACSign(data, secretkey, algorithm);

                return signature;
            }
            catch (Exception e)
            {
                throw new Amazon.Runtime.SignatureException("Failed to generate signature: " + e.Message, e);
            }
        }
예제 #37
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;
            }
예제 #38
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();
                }
            }
예제 #39
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);
            }
        }
예제 #40
0
 PrivateKeySigner(byte[] key, SigningAlgorithm signingAlgorithm)
 {
     _key = key;
     _algorithmInfo = new AlgorithmInfo(signingAlgorithm);
 }
예제 #41
0
 public HmacSigning(ISymmetricKeyProvider keyProvider, SigningAlgorithm algorithm)
 {
     _keyProvider = keyProvider;
     _algorithm = algorithm;
 }
예제 #42
0
		public byte[] Sign(byte[] data, SigningAlgorithm algorithm)
		{
		    if (data == null)
		    {
		        throw new ArgumentNullException("data");
		    }

		    using (var rsa = OpenSslKey.DecodeRSAPrivateKey(_key))
			{
				byte[] signature = rsa.SignData(data, GetHashName(algorithm));

				return signature;

			}
		}
예제 #43
0
            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;
            }
 /// <summary>
 /// Compute and return the hash of a data blob using the specified key
 /// </summary>
 /// <param name="algorithm">Algorithm to use for hashing</param>
 /// <param name="key">Hash key</param>
 /// <param name="data">Data blob</param>
 /// <returns>Hash of the data</returns>
 public static byte[] ComputeKeyedHash(SigningAlgorithm algorithm, byte[] key, string data)
 {
     return ComputeKeyedHash(algorithm, key, Encoding.UTF8.GetBytes(data));
 }
예제 #45
0
	    public byte[] Hash(byte[] data, SigningAlgorithm algorithm)
	    {
	        if (data == null)
	        {
	            throw new ArgumentNullException("data");
	        }

	        using(var hash = GetHash(algorithm))
			{
				return hash.ComputeHash(data);	
			}
	    }
예제 #46
0
 public byte[] GetIssuerKey(SigningAlgorithm algorithm)
 {
     return _issuerKey;
 }
예제 #47
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();
                }
            }
예제 #48
0
        PrivateKeySigner(string privateKey, SigningAlgorithm signingAlgorithm)
        {
            if (privateKey == null)
            {
                throw new ArgumentNullException("privateKey");
            }

            _key = OpenSslKey.DecodeOpenSSLPrivateKey(privateKey);

            _algorithmInfo = new AlgorithmInfo(signingAlgorithm);
        }
예제 #49
0
 public byte[] GetConsumerKey(SigningAlgorithm algorithm, string issuer)
 {
     return _consumerKey;
 }
예제 #50
0
 public static IPrivateKeySigner Create(string privateKey, SigningAlgorithm signingAlgorithm = SigningAlgorithm.RSASha256)
 {
     return new PrivateKeySigner(privateKey, signingAlgorithm);
 }
예제 #51
0
	    private static string GetHashName(SigningAlgorithm algorithm)
		{
			switch (algorithm)
			{
				case SigningAlgorithm.RSASha1:
					{
						return "SHA1";
					}
				case SigningAlgorithm.RSASha256:
					{
						return "SHA256";
					}
				default:
					{
						throw new ArgumentException("Invalid SigningAlgorithm value", "algorithm");
					}

			}
		}
예제 #52
0
        public static IPrivateKeySigner LoadFromFile(string path, SigningAlgorithm signingAlgorithm = SigningAlgorithm.RSASha256)
        {
            var privateKey = File.ReadAllText(path);

            return new PrivateKeySigner(privateKey, signingAlgorithm);
        }
예제 #53
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(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.");
                }

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

                try
                {
                    algorithm.Key = key;
                    byte[] bytes = algorithm.ComputeHash(data);
                    return bytes;
                }
                finally
                {
                    algorithm.Clear();
                }
            }
예제 #54
0
		private static HashAlgorithm GetHash(SigningAlgorithm algorithm)
		{
			switch (algorithm)
			{
				case SigningAlgorithm.RSASha1:
					{
						return new SHA1Managed();
					}
				case SigningAlgorithm.RSASha256:
					{
						return new SHA256Managed();
					}

				default:
					{
						throw new ArgumentException("Invalid SigningAlgorithm value", "algorithm");
					}

			}
		}
 /// <summary>
 /// Compute and return the hash of a data blob using the specified key
 /// </summary>
 /// <param name="algorithm">Algorithm to use for hashing</param>
 /// <param name="key">Hash key</param>
 /// <param name="data">Data blob</param>
 /// <returns>Hash of the data</returns>
 public static byte[] ComputeKeyedHash(SigningAlgorithm algorithm, byte[] key, byte[] data)
 {
     return CryptoUtilFactory.CryptoInstance.HMACSignBinary(data, key, algorithm);
 }
예제 #56
0
 public string HMACSign(string data, string key, SigningAlgorithm algorithmName)
 {
     var binaryData = Encoding.UTF8.GetBytes(data);
     return HMACSign(binaryData, key, algorithmName);
 }
예제 #57
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());
     }
 }
예제 #58
0
 /// <summary>
 /// Compute and return the hash of a data blob using the specified key
 /// </summary>
 /// <param name="algorithm">Algorithm to use for hashing</param>
 /// <param name="key">Hash key</param>
 /// <param name="data">Data blob</param>
 /// <returns>Hash of the data</returns>
 public static string ComputeKeyedHash(SigningAlgorithm algorithm, string key, string data)
 {
     return CryptoUtilFactory.CryptoInstance.HMACSign(data, key, algorithm);
 }
예제 #59
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());
     }
 }
예제 #60
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                throw new NotImplementedException();
                //KeyedHashAlgorithm algorithm = CreateKeyedHashAlgorithm(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.");
                //}

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

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