public void AsymmetricSignatureProvider_Dispose()
        {
            AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(KeyingMaterial.AsymmetricKey_Public_2048, SecurityAlgorithms.RsaSha256Signature);

            provider.Dispose();

            try
            {
                provider.Sign(new byte[256]);
            }
            catch (Exception ex)
            {
                ExpectedException.ProcessException(ExpectedException.ObjDisp, ex);
            }

            try
            {
                provider.Verify(new byte[256], new byte[256]);
            }
            catch (Exception ex)
            {
                ExpectedException.ProcessException(ExpectedException.ObjDisp, ex);
            }

            try
            {
                provider.Dispose();
            }
            catch (Exception ex)
            {
                Assert.Fail(string.Format("AsymmetricSignatureProvider.Dispose called twice, caught exception: '{0}'", ex));
            }
        }
예제 #2
0
        private byte[] Sign(byte[] payload, byte[] publicKey, byte[] privateKey)
        {
            var key      = new ECDsaSecurityKey(LoadPrivateKey(privateKey));
            var provider = new AsymmetricSignatureProvider(key, SecurityAlgorithms.EcdsaSha256Signature);

            return(provider.Sign(payload));
        }
 private void AsymmetricSignatureProvidersSignVariation(SecurityKey key, string algorithm, byte[] input, ExpectedException ee, List <string> errors)
 {
     try
     {
         AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(key, algorithm, true);
         byte[] signature = provider.Sign(input);
         ee.ProcessNoException(errors);
     }
     catch (Exception ex)
     {
         ee.ProcessException(ex, errors);
     }
 }
예제 #4
0
        public void SignVerify(SignatureProviderTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.SignVerify", theoryData);
            var bytes   = Guid.NewGuid().ToByteArray();

            try
            {
                var providerForSigningDirect = new AsymmetricSignatureProvider(theoryData.SigningKey, theoryData.SigningAlgorithm, true);
                providerForSigningDirect.ValidKeySize();

                var providerForVerifyingDirect = new AsymmetricSignatureProvider(theoryData.VerifyKey, theoryData.VerifyAlgorithm, false);
                providerForVerifyingDirect.ValidKeySize();

                var providerForSigningFromFactory   = theoryData.SigningKey.CryptoProviderFactory.CreateForSigning(theoryData.SigningKey, theoryData.SigningAlgorithm);
                var providerForVerifyingFromFactory = theoryData.VerifyKey.CryptoProviderFactory.CreateForVerifying(theoryData.VerifyKey, theoryData.VerifyAlgorithm);

                byte[] signatureDirect      = providerForSigningDirect.Sign(bytes);
                byte[] signatureFromFactory = providerForSigningFromFactory.Sign(bytes);

                if (!providerForVerifyingDirect.Verify(bytes, signatureDirect))
                {
                    context.AddDiff($"providerForVerifyingDirect.Verify (signatureDirect) - FAILED. signingKey : signingAlgorithm '{theoryData.SigningKey}' : '{theoryData.SigningAlgorithm}. verifyKey : verifyAlgorithm '{theoryData.VerifyKey}' : '{theoryData.VerifyAlgorithm}");
                }

                if (!providerForVerifyingDirect.Verify(bytes, signatureFromFactory))
                {
                    context.AddDiff($"providerForVerifyingDirect.Verify (signatureFromFactory) - FAILED. signingKey : signingAlgorithm '{theoryData.SigningKey}' : '{theoryData.SigningAlgorithm}. verifyKey : verifyAlgorithm '{theoryData.VerifyKey}' : '{theoryData.VerifyAlgorithm}");
                }

                if (!providerForVerifyingFromFactory.Verify(bytes, signatureDirect))
                {
                    context.AddDiff($"providerForVerifyingFromFactory.Verify (signatureDirect) - FAILED. signingKey : signingAlgorithm '{theoryData.SigningKey}' : '{theoryData.SigningAlgorithm}. verifyKey : verifyAlgorithm '{theoryData.VerifyKey}' : '{theoryData.VerifyAlgorithm}");
                }

                if (!providerForVerifyingFromFactory.Verify(bytes, signatureFromFactory))
                {
                    context.AddDiff($"providerForVerifyingFromFactory.Verify (signatureFromFactory) - FAILED. signingKey : signingAlgorithm '{theoryData.SigningKey}' : '{theoryData.SigningAlgorithm}. verifyKey : verifyAlgorithm '{theoryData.VerifyKey}' : '{theoryData.VerifyAlgorithm}");
                }

                theoryData.ExpectedException.ProcessNoException(context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
        public void SignatureProviders_Sign()
        {
            List <string> errors = new List <string>();

            byte[] rawBytes = new byte[8192];
            (new Random()).NextBytes(rawBytes);

            // Asymmetric
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKey_2048, SecurityAlgorithms.RsaSha256Signature, null, ExpectedException.ArgumentNullException(), errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKey_2048, SecurityAlgorithms.RsaSha256Signature, new byte[0], ExpectedException.ArgumentException("IDX10624:"), errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKey_1024, SecurityAlgorithms.RsaSha256Signature, rawBytes, ExpectedException.ArgumentOutOfRangeException("IDX10630:"), errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKey_2048, SecurityAlgorithms.RsaSha256Signature, rawBytes, ExpectedException.NoExceptionExpected, errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKeyWithCspProvider_2048, SecurityAlgorithms.RsaSha256Signature, rawBytes, ExpectedException.NoExceptionExpected, errors);
#if NETCOREAPP1_0
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKeyWithCngProvider_2048, SecurityAlgorithms.RsaSha256Signature, rawBytes, ExpectedException.NoExceptionExpected, errors);
            Assert.ThrowsAny <CryptographicException>(() =>
            {
                AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(KeyingMaterial.RsaSecurityKeyWithCngProvider_2048_Public, SecurityAlgorithms.RsaSha256Signature);
                provider.Sign(rawBytes);
            });
#endif
            // since the actual exception thrown is private - WindowsCryptographicException, using this pattern to match the derived exception
            Assert.ThrowsAny <CryptographicException>(() =>
            {
                AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(KeyingMaterial.RsaSecurityKeyWithCspProvider_2048_Public, SecurityAlgorithms.RsaSha256Signature);
                provider.Sign(rawBytes);
            });

            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKey_2048_Public, SecurityAlgorithms.RsaSha256Signature, rawBytes, ExpectedException.InvalidOperationException("IDX10638:"), errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.RsaSecurityKey_2048, "NOT_SUPPORTED", rawBytes, ExpectedException.ArgumentException("IDX10634:"), errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.ECDsa256Key, SecurityAlgorithms.EcdsaSha256, rawBytes, ExpectedException.NoExceptionExpected, errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.ECDsa256Key_Public, SecurityAlgorithms.EcdsaSha256, rawBytes, ExpectedException.InvalidOperationException("IDX10638:"), errors);

            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.JsonWebKeyRsa256, SecurityAlgorithms.RsaSha256Signature, rawBytes, ExpectedException.NoExceptionExpected, errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.JsonWebKeyRsa256Public, SecurityAlgorithms.RsaSha256Signature, rawBytes, ExpectedException.InvalidOperationException("IDX10638:"), errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.JsonWebKeyEcdsa256, SecurityAlgorithms.EcdsaSha256, rawBytes, ExpectedException.NoExceptionExpected, errors);
            AsymmetricSignatureProvidersSignVariation(KeyingMaterial.JsonWebKeyEcdsa256Public, SecurityAlgorithms.EcdsaSha256, rawBytes, ExpectedException.InvalidOperationException("IDX10638:"), errors);

            // Symmetric
            SymmetricSignatureProvidersSignVariation(KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, null, ExpectedException.ArgumentNullException(), errors);
            SymmetricSignatureProvidersSignVariation(KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, new byte[0], ExpectedException.ArgumentException("IDX10624:"), errors);
            SymmetricSignatureProvidersSignVariation(KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, rawBytes, ExpectedException.NoExceptionExpected, errors);
            SymmetricSignatureProvidersSignVariation(KeyingMaterial.SymmetricSecurityKey_56, SecurityAlgorithms.HmacSha256Signature, rawBytes, ExpectedException.ArgumentOutOfRangeException("IDX10603:"), errors);
            SymmetricSignatureProvidersSignVariation(KeyingMaterial.JsonWebKeySymmetric256, SecurityAlgorithms.HmacSha256Signature, rawBytes, ExpectedException.NoExceptionExpected, errors);
            TestUtilities.AssertFailIfErrors("SignatureProviders_Sign", errors);
        }
        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 )");
            }
        }
        public void RsaCngAdapterTest(RsaCngAdapterTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.RsaCngAdapterTest", theoryData);

            var cert = KeyingMaterial.CertSelfSigned2048_SHA256;

            var rsaCapiPrivateKey = new RsaSecurityKey(cert.PrivateKey as RSA);
            var rsaCapiPublicKey  = new RsaSecurityKey(cert.PublicKey.Key as RSA);
            var clearBytes        = Encoding.UTF8.GetBytes("blue star");

            byte[] capiSignatureBytes = null;

            AsymmetricSignatureProvider providerCapiPrivate = null;
            AsymmetricSignatureProvider providerCapiPublic  = null;

            // create CAPI providers
            try
            {
                providerCapiPrivate = new AsymmetricSignatureProvider(rsaCapiPrivateKey, theoryData.Algorithm, true);
                capiSignatureBytes  = providerCapiPrivate.Sign(clearBytes);
                providerCapiPublic  = new AsymmetricSignatureProvider(rsaCapiPublicKey, theoryData.Algorithm, false);
                if (!providerCapiPublic.Verify(clearBytes, capiSignatureBytes))
                {
                    context.AddDiff("providerCapiPublic.Verify(clearBytes, capiSignatureBytes)");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            var rsaCngPrivateKey = new RsaSecurityKey(cert.GetRSAPrivateKey());
            var rsaCngPublicKey  = new RsaSecurityKey(cert.GetRSAPublicKey());

            byte[] cngSignatureBytes          = null;
            byte[] cngSignatureBytesByFactory = null;

            // create private signing
            AsymmetricSignatureProvider providerCngPrivate = null;

            try
            {
                providerCngPrivate = new AsymmetricSignatureProvider(rsaCngPrivateKey, theoryData.Algorithm, true);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // create private signing with CryptoProviderFactory.Default
            SignatureProvider providerCngPrivateByFactory = null;

            try
            {
                providerCngPrivateByFactory = CryptoProviderFactory.Default.CreateForSigning(rsaCngPrivateKey, theoryData.Algorithm);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // create public verifying
            AsymmetricSignatureProvider providerCngPublic = null;

            try
            {
                providerCngPublic = new AsymmetricSignatureProvider(rsaCngPublicKey, theoryData.Algorithm, false);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // create public verifying with CryptoProviderFactory.Default
            SignatureProvider providerCngPublicByFactory = null;

            try
            {
                providerCngPublicByFactory = CryptoProviderFactory.Default.CreateForVerifying(rsaCngPublicKey, theoryData.Algorithm);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            try
            {
                cngSignatureBytes = providerCngPrivate.Sign(clearBytes);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // cngByFactory Sign
            try
            {
                cngSignatureBytesByFactory = providerCngPrivateByFactory.Sign(clearBytes);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // CngPublic -> CngPrivate validates
            try
            {
                var cngVerify = providerCngPublic.Verify(clearBytes, cngSignatureBytes);
                if (!cngVerify)
                {
                    context.AddDiff($"cngVerify = providerCngPublic.Verify(clearBytes, cngSignatureBytes) == false.");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // CngPublicByFactory -> CngPrivate validates
            try
            {
                var cngVerify = providerCngPublicByFactory.Verify(clearBytes, cngSignatureBytes);
                if (!cngVerify)
                {
                    context.AddDiff($"cngVerify = providerCngPublicByFactory.Verify(clearBytes, cngSignatureBytes) == false.");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // CngPublic -> CAPI validates
            try
            {
                var cngVerify = providerCngPublic.Verify(clearBytes, capiSignatureBytes);
                if (!cngVerify)
                {
                    context.AddDiff($"cngVerify = providerCngPublic.Verify(clearBytes, capiSignatureBytes) == false.");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // CngPublicByFactory -> CAPI validates
            try
            {
                var verify = providerCngPublicByFactory.Verify(clearBytes, capiSignatureBytes);
                if (!verify)
                {
                    context.AddDiff($"verify = providerCngPublicByFactory.Verify(clearBytes, capiSignatureBytes) == false.");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // CAPIPublic -> Cng validates
            try
            {
                var verify = providerCapiPublic.Verify(clearBytes, cngSignatureBytes);
                if (!verify)
                {
                    context.AddDiff($"verify = providerCapiPublic.Verify(clearBytes, cngSignatureBytes) == false.");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            // CAPIPublic -> CngByFactory validates
            try
            {
                var verify = providerCapiPublic.Verify(clearBytes, cngSignatureBytesByFactory);
                if (!verify)
                {
                    context.AddDiff($"verify = providerCapiPublic.Verify(clearBytes, cngSignatureBytesByFactory) == false.");
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
        private byte[] GetSignature(SecurityKey key, string algorithm, byte[] rawBytes)
        {
            AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(key, algorithm, true);

            return(provider.Sign(rawBytes));
        }