Beispiel #1
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 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));
            }
        }
Beispiel #3
0
        private bool Verify(byte[] payload, byte[] signature, byte[] publicKey)
        {
            var key      = new ECDsaSecurityKey(LoadPublicKey(publicKey));
            var provider = new AsymmetricSignatureProvider(key, SecurityAlgorithms.EcdsaSha256Signature);

            return(provider.Verify(payload, signature));
        }
        private async Task ValidateSignatureAsync(AcmeRawPostRequest request, AcmeHeader header, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            if (header is null)
            {
                throw new ArgumentNullException(nameof(header));
            }

            _logger.LogDebug("Attempting to validate signature ...");

            var jwk = header.Jwk;

            if (jwk == null)
            {
                try
                {
                    var accountId = header.GetAccountId();
                    var account   = await _accountService.LoadAcountAsync(accountId, cancellationToken);

                    jwk = account?.Jwk;
                }
                catch (InvalidOperationException)
                {
                    throw new MalformedRequestException("KID could not be found.");
                }
            }

            if (jwk == null)
            {
                throw new MalformedRequestException("Could not load JWK.");
            }

            var securityKey = jwk.SecurityKey;

            using var signatureProvider = new AsymmetricSignatureProvider(securityKey, header.Alg);
            var plainText = System.Text.Encoding.UTF8.GetBytes($"{request.Header}.{request.Payload ?? ""}");
            var signature = Base64UrlEncoder.DecodeBytes(request.Signature);

            if (!signatureProvider.Verify(plainText, signature))
            {
                throw new MalformedRequestException("The signature could not be verified");
            }

            _logger.LogDebug("successfully validated signature.");
        }
        private void AsymmetricSignatureProviders_Verify_Variation(SecurityKey key, string algorithm, byte[] rawBytes, byte[] signature, ExpectedException ee, List <string> errors, bool shouldSignatureSucceed)
        {
            try
            {
                AsymmetricSignatureProvider provider = new AsymmetricSignatureProvider(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);
            }
        }
        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);
        }