public void SymmetricSignatureProvider_SupportedAlgorithms()
        {
            var errors = new List <string>();

            foreach (var algorithm in
                     new string[] {
                SecurityAlgorithms.HmacSha256Signature,
                SecurityAlgorithms.HmacSha384Signature,
                SecurityAlgorithms.HmacSha512Signature,
                SecurityAlgorithms.HmacSha256,
                SecurityAlgorithms.HmacSha384,
                SecurityAlgorithms.HmacSha512
            })
            {
                try
                {
                    var provider = new SymmetricSignatureProvider(KeyingMaterial.DefaultSymmetricSecurityKey_256, algorithm);
                }
                catch (Exception ex)
                {
                    errors.Add("Creation of AsymmetricSignatureProvider with algorithm: " + algorithm + ", threw: " + ex.Message);
                }

                TestUtilities.AssertFailIfErrors("AsymmetricSignatureProvider_SupportedAlgorithms", errors);
            }
        }
        private void SymmetricSignatureProviderTests_Constructor(string testcase, SymmetricSecurityKey key, string algorithm, ExpectedException exceptionExpected = null)
        {
            Console.WriteLine(string.Format("Testcase: '{0}'", testcase));

            SymmetricSignatureProvider provider = null;

            try
            {
                if (testcase.StartsWith("Signing"))
                {
                    provider = new SymmetricSignatureProvider(key, algorithm);
                }
                else
                {
                    provider = new SymmetricSignatureProvider(key, algorithm);
                }

                if (exceptionExpected != null && exceptionExpected.Thrown != null)
                {
                    Assert.Fail("Expected exception: '{0}'", exceptionExpected.Thrown);
                }
            }
            catch (Exception ex)
            {
                ExpectedException.ProcessException(exceptionExpected, ex);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticatedEncryptionProvider"/> class used for encryption and decryption.
        /// <param name="key">The <see cref="SecurityKey"/> that will be used for crypto operations.</param>
        /// <param name="algorithm">The encryption algorithm to apply.</param>
        /// <exception cref="ArgumentNullException">'key' is null.</exception>
        /// <exception cref="ArgumentNullException">'algorithm' is null or whitespace.</exception>
        /// <exception cref="ArgumentOutOfRangeException">key size is not large enough.</exception>
        /// <exception cref="ArgumentException">'algorithm' is not supported.</exception>
        /// <exception cref="ArgumentException">a symmetricSignatureProvider is not created.</exception>
        /// </summary>
        public AuthenticatedEncryptionProvider(SecurityKey key, string algorithm)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

            if (string.IsNullOrWhiteSpace(algorithm))
            {
                throw LogHelper.LogArgumentNullException(nameof(algorithm));
            }

            if (!IsSupportedAlgorithm(key, algorithm))
            {
                throw LogHelper.LogExceptionMessage(new ArgumentException(String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10668, GetType(), algorithm, key)));
            }

            ValidateKeySize(key, algorithm);
            _authenticatedkeys = GetAlgorithmParameters(key, algorithm);
            _hashAlgorithm     = GetHashAlgorithm(algorithm);

            // TODO - should we defer and use CreateForSigning for encrypt, CreateForVerifying for decrypt?
            _symmetricSignatureProvider = key.CryptoProviderFactory.CreateForSigning(_authenticatedkeys.HmacKey, _hashAlgorithm) as SymmetricSignatureProvider;
            if (_symmetricSignatureProvider == null)
            {
                throw LogHelper.LogExceptionMessage(new ArgumentException(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10649, Algorithm)));
            }

            Key       = key;
            Algorithm = algorithm;
        }
 private void SymmetricSignatureProvider_ConstructorVariation(SecurityKey key, string algorithm, ExpectedException expectedException)
 {
     try
     {
         SymmetricSignatureProvider provider = new SymmetricSignatureProvider(key, algorithm);
         expectedException.ProcessNoException();
     }
     catch (Exception ex)
     {
         expectedException.ProcessException(ex);
     }
 }
 private void SymmetricSignatureProvidersSignVariation(SecurityKey key, string algorithm, byte[] input, ExpectedException ee, List <string> errors)
 {
     try
     {
         SymmetricSignatureProvider provider = new SymmetricSignatureProvider(key, algorithm);
         byte[] signature = provider.Sign(input);
         ee.ProcessNoException(errors);
     }
     catch (Exception ex)
     {
         ee.ProcessException(ex, errors);
     }
 }
        public void SymmetricSignatureProvider_Publics()
        {
            SymmetricSignatureProvider provider = new SymmetricSignatureProvider(KeyingMaterial.DefaultSymmetricSecurityKey_256, KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2.Algorithm);

            ExpectedException expectedException = ExpectedException.ArgumentOutOfRangeException("IDX10628:");

            try
            {
                provider.MinimumSymmetricKeySizeInBits = SymmetricSignatureProvider.DefaultMinimumSymmetricKeySizeInBits - 10;
                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }
        private void SymmetricSignatureProviders_Verify_Variation(SecurityKey key, string algorithm, byte[] rawBytes, byte[] signature, ExpectedException ee, List <string> errors, bool shouldSignatureSucceed)
        {
            try
            {
                SymmetricSignatureProvider provider = new SymmetricSignatureProvider(key, algorithm);
                if (provider.Verify(rawBytes, signature) != shouldSignatureSucceed)
                {
                    errors.Add("SignatureProvider.Verify did not return expected: " + shouldSignatureSucceed + " , algorithm: " + algorithm);
                }

                ee.ProcessNoException(errors);
            }
            catch (Exception ex)
            {
                ee.ProcessException(ex, errors);
            }
        }
Exemple #8
0
        public bool VerifyToken(string token)
        {
            //Parts of Token
            var    partsOfToken    = token.Split('.');
            string header          = partsOfToken[0];
            string payload         = partsOfToken[1];
            string signedSignature = partsOfToken[2];

            byte[] byteSign             = Base64UrlEncoder.DecodeBytes(signedSignature);
            byte[] byteHeaderAndPayload = Encoding.UTF8.GetBytes(header + '.' + payload);

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));

            SymmetricSignatureProvider provider = new SymmetricSignatureProvider(key, SecurityAlgorithms.HmacSha512);

            return(provider.Verify(byteHeaderAndPayload, byteSign));
        }
        public void SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking()
        {
            SymmetricSignatureProvider provider = new SymmetricSignatureProvider(KeyingMaterial.SymmetricSigningCreds_256_Sha2.SigningKey as SymmetricSecurityKey, KeyingMaterial.SymmetricSigningCreds_256_Sha2.SignatureAlgorithm);

            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Sign - null input", provider, null, null, ExpectedException.ArgNull);
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Sign - 0 bytes", provider, new byte[0], null, ExpectedException.ArgEx("Jwt10524"));
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Sign - 1 byte", provider, new byte[1], null, ExpectedException.Null);

            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Verify - null input", provider, null, null, ExpectedException.ArgNull);
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Verify - null signature", provider, new byte[0], null, ExpectedException.ArgNull);
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Verify - 0 bytes input", provider, new byte[0], new byte[0], ExpectedException.ArgEx("Jwt10525"));
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Verify - 0 bytes signature", provider, new byte[1], new byte[0], ExpectedException.ArgEx("Jwt10526"));
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Verify - 1 byte", provider, new byte[1], new byte[1], ExpectedException.Null);

            provider.Dispose();
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Sign - dispose", provider, new byte[1], new byte[1], ExpectedException.ObjDisp);
            SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking("Verify - dispose", provider, new byte[1], new byte[1], ExpectedException.ObjDisp);
        }
Exemple #10
0
        public void SymmetricSignatureProvider_Publics()
        {
            SymmetricSignatureProvider provider = new SymmetricSignatureProvider(KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2.SigningKey as SymmetricSecurityKey, KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2.SignatureAlgorithm);

            SignatureProvider_SignVariation(provider, null, null, ExpectedException.ArgumentNullException());
            SignatureProvider_SignVariation(provider, new byte[0], null, ExpectedException.ArgumentException("IDX10624:"));
            SignatureProvider_SignVariation(provider, new byte[1], null, ExpectedException.NoExceptionExpected);

            SignatureProvider_VerifyVariation(provider, null, null, ExpectedException.ArgumentNullException());
            SignatureProvider_VerifyVariation(provider, new byte[0], null, ExpectedException.ArgumentNullException());
            SignatureProvider_VerifyVariation(provider, new byte[0], new byte[0], ExpectedException.ArgumentException("IDX10625:"));
            SignatureProvider_VerifyVariation(provider, new byte[1], new byte[0], ExpectedException.ArgumentException("IDX10626:"));
            SignatureProvider_VerifyVariation(provider, new byte[1], new byte[1], ExpectedException.NoExceptionExpected);

            provider.Dispose();
            SignatureProvider_SignVariation(provider, new byte[1], new byte[1], ExpectedException.ObjectDisposedException);
            SignatureProvider_VerifyVariation(provider, new byte[1], new byte[1], ExpectedException.ObjectDisposedException);
        }
        public void SignatureProvider_Dispose()
        {
            AsymmetricSignatureProvider asymmetricSignatureProvider = new AsymmetricSignatureProvider(KeyingMaterial.DefaultX509Key_Public_2048, SecurityAlgorithms.RsaSha256Signature);

            asymmetricSignatureProvider.Dispose();

            ExpectedException expectedException = ExpectedException.ObjectDisposedException;

            SignatureProvider_DisposeVariation("Sign", asymmetricSignatureProvider, expectedException);
            SignatureProvider_DisposeVariation("Verify", asymmetricSignatureProvider, expectedException);
            SignatureProvider_DisposeVariation("Dispose", asymmetricSignatureProvider, ExpectedException.NoExceptionExpected);

            SymmetricSignatureProvider symmetricProvider = new SymmetricSignatureProvider(KeyingMaterial.DefaultSymmetricSecurityKey_256, KeyingMaterial.DefaultSymmetricSigningCreds_256_Sha2.Algorithm);

            symmetricProvider.Dispose();
            SignatureProvider_DisposeVariation("Sign", symmetricProvider, expectedException);
            SignatureProvider_DisposeVariation("Verify", symmetricProvider, expectedException);
            SignatureProvider_DisposeVariation("Dispose", symmetricProvider, ExpectedException.NoExceptionExpected);
        }
Exemple #12
0
        private void SymmetricSignatureProvider_ConstructorVariation(string testcase, SymmetricSecurityKey key, string algorithm, ExpectedException expectedException)
        {
            Console.WriteLine(string.Format("Testcase: '{0}'", testcase));

            SymmetricSignatureProvider provider = null;

            try
            {
                if (testcase.StartsWith("Signing"))
                {
                    provider = new SymmetricSignatureProvider(key, algorithm);
                }
                else
                {
                    provider = new SymmetricSignatureProvider(key, algorithm);
                }

                expectedException.ProcessNoException();
            }
            catch (Exception ex)
            {
                expectedException.ProcessException(ex);
            }
        }
        private void SymmetricSignatureProviderTests_Sign_Verify_ParameterChecking(string testcase, SymmetricSignatureProvider provider, byte[] bytes, byte[] signature, ExpectedException exceptionExpected)
        {
            Console.WriteLine(string.Format("Testcase: '{0}'", testcase));
            try
            {
                if (testcase.StartsWith("Sign"))
                {
                    provider.Sign(bytes);
                }
                else
                {
                    provider.Verify(bytes, signature);
                }

                Assert.IsFalse(exceptionExpected.Thrown != null, string.Format("Expected exception: '{0}'", exceptionExpected.Thrown));
            }
            catch (Exception ex)
            {
                ExpectedException.ProcessException(exceptionExpected, ex);
            }
        }
        public void SignatureProviders_SignAndVerify()
        {
            // asymmetric
            try
            {
                Random r = new Random();
                AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(KeyingMaterial.AsymmetricKey_2048, SecurityAlgorithms.RsaSha256Signature);
                byte[] bytesin = new byte[1024];
                r.NextBytes(bytesin);
                byte[] signature = provider.Sign(bytesin);
            }
            catch (Exception ex)
            {
                Assert.IsFalse(ex.GetType() != typeof(InvalidOperationException), "ex.GetType() != typeof( InvalidOperationException )");
            }

            // asymmetric
            try
            {
                Random r = new Random();
                AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(KeyingMaterial.AsymmetricKey_2048, SecurityAlgorithms.RsaSha256Signature, true);
                byte[] bytesin = new byte[1024];
                r.NextBytes(bytesin);
                byte[] signature = provider.Sign(bytesin);
                Assert.IsFalse(!provider.Verify(bytesin, signature), string.Format("AsymmetricSignatureProvider did not verify"));
            }
            catch (Exception)
            {
                Assert.Fail("Should have thrown, it is possible that crypto config mapped this.");
            }

            // unknown algorithm
            try
            {
                Random r = new Random();
                AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(KeyingMaterial.AsymmetricKey_2048, "SecurityAlgorithms.RsaSha256Signature");
                Assert.Fail(string.Format("Should have thrown, it is possible that crypto config mapped this."));
            }
            catch (Exception ex)
            {
                Assert.IsFalse(ex.GetType() != typeof(InvalidOperationException), "ex.GetType() != typeof( InvalidOperationException )");
            }

            // symmetric
            try
            {
                Random r = new Random();
                SymmetricSignatureProvider provider = new SymmetricSignatureProvider(KeyingMaterial.SymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature);
                byte[] bytesin = new byte[1024];
                r.NextBytes(bytesin);
                byte[] signature = provider.Sign(bytesin);
                Assert.IsFalse(!provider.Verify(bytesin, signature), string.Format("Signature did not verify"));
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("Unexpected exception received: '{0}'", ex));
            }

            // unknown algorithm
            try
            {
                Random r = new Random();
                SymmetricSignatureProvider provider = new SymmetricSignatureProvider(KeyingMaterial.SymmetricSecurityKey_256, "SecurityAlgorithms.HmacSha256Signature");
                Assert.Fail(string.Format("Should have thrown, it is possible that crypto config mapped this."));
            }
            catch (Exception ex)
            {
                Assert.IsFalse(ex.GetType() != typeof(InvalidOperationException), "ex.GetType() != typeof( InvalidOperationException )");
            }
        }
        private byte[] GetSignatureFromSymmetricKey(SecurityKey key, string algorithm, byte[] rawBytes)
        {
            SymmetricSignatureProvider provider = new SymmetricSignatureProvider(key, algorithm);

            return(provider.Sign(rawBytes));
        }