/// <summary>
        /// Decrypts ciphertext into plaintext
        /// </summary>
        /// <param name="ciphertext">the encrypted text to decrypt.</param>
        /// <param name="authenticatedData">the authenticateData that is used in verification.</param>
        /// <param name="iv">the initialization vector used when creating the ciphertext.</param>
        /// <param name="authenticationTag">the authenticationTag that was created during the encyption.</param>
        /// <returns>decrypted ciphertext</returns>
        /// <exception cref="ArgumentNullException">'ciphertext' is null or empty.</exception>
        /// <exception cref="ArgumentNullException">'authenticatedData' is null or empty.</exception>
        /// <exception cref="ArgumentNullException">'iv' is null or empty.</exception>
        /// <exception cref="ArgumentNullException">'authenticationTag' is null or empty.</exception>
        /// <exception cref="SecurityTokenDecryptionFailedException">signature over authenticationTag fails to verify.</exception>
        /// <exception cref="SecurityTokenDecryptionFailedException">AES crypto operation threw. See inner exception.</exception>
        public virtual byte[] Decrypt(byte[] ciphertext, byte[] authenticatedData, byte[] iv, byte[] authenticationTag)
        {
            if (ciphertext == null || ciphertext.Length == 0)
            {
                throw LogHelper.LogArgumentNullException(nameof(ciphertext));
            }

            if (authenticatedData == null || authenticatedData.Length == 0)
            {
                throw LogHelper.LogArgumentNullException(nameof(authenticatedData));
            }

            if (iv == null || iv.Length == 0)
            {
                throw LogHelper.LogArgumentNullException(nameof(iv));
            }

            if (authenticationTag == null || authenticationTag.Length == 0)
            {
                throw LogHelper.LogArgumentNullException(nameof(authenticationTag));
            }

            // Verify authentication Tag
            byte[] al       = Utility.ConvertToBigEndian(authenticatedData.Length * 8);
            byte[] macBytes = new byte[authenticatedData.Length + iv.Length + ciphertext.Length + al.Length];
            Array.Copy(authenticatedData, 0, macBytes, 0, authenticatedData.Length);
            Array.Copy(iv, 0, macBytes, authenticatedData.Length, iv.Length);
            Array.Copy(ciphertext, 0, macBytes, authenticatedData.Length + iv.Length, ciphertext.Length);
            Array.Copy(al, 0, macBytes, authenticatedData.Length + iv.Length + ciphertext.Length, al.Length);
            if (!_symmetricSignatureProvider.Verify(macBytes, authenticationTag, _authenticatedkeys.HmacKey.Key.Length))
            {
                throw LogHelper.LogExceptionMessage(new SecurityTokenDecryptionFailedException(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10650, Base64UrlEncoder.Encode(authenticatedData), Base64UrlEncoder.Encode(iv), Base64UrlEncoder.Encode(authenticationTag))));
            }

            Aes aes = Aes.Create();

            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key     = _authenticatedkeys.AesKey.Key;
            aes.IV      = iv;
            try
            {
                return(Utility.Transform(aes.CreateDecryptor(), ciphertext, 0, ciphertext.Length));
            }
            catch (Exception ex)
            {
                throw LogHelper.LogExceptionMessage(new SecurityTokenDecryptionFailedException(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10654, 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);
            }
        }
Esempio n. 3
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));
        }
        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 )");
            }
        }