public ICryptographyProvider Build()
        {
            var provider = new CryptoProviderFactory(Settings.Default.EncryptionEngine, Settings.Default.EncryptionBlockCipherMode).Build();

            provider.KeyDerivationIterations = Settings.Default.EncryptionKeyDerivationIterations;
            return(provider);
        }
Ejemplo n.º 2
0
        /// <inheritdoc/>
        public string Generate(TimeSpan expireInInterval)
        {
            var signingFactory = new CryptoProviderFactory {
                CacheSignatureProviders = false
            };

            using var algorithm = ECDsa.Create();
            // ReSharper disable once PossibleNullReferenceException
            algorithm.ImportPkcs8PrivateKey(Convert.FromBase64String(_setting.PrivateKeyBody), out _);
            var credentials = new SigningCredentials(new ECDsaSecurityKey(algorithm)
            {
                KeyId = _setting.KeyId,
                CryptoProviderFactory = signingFactory
            }, SecurityAlgorithms.EcdsaSha256);

            var now   = DateTime.UtcNow;
            var exp   = now.Add(expireInInterval);
            var token = new SecurityTokenDescriptor
            {
                SigningCredentials = credentials,
                Expires            = exp,
                IssuedAt           = now,
                Issuer             = _teamId,
                Audience           = AppleJwtSettings.Issuer,
                Claims             = new Dictionary <string, object>()
                {
                    { "sub", _clientId }
                }
            };

            return(new JwtSecurityTokenHandler().CreateEncodedJwt(token));
        }
Ejemplo n.º 3
0
        public void ReleaseSignatureProviders(SignatureProviderTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.ReleaseSignatureProviders", theoryData);
            var cryptoProviderFactory = new CryptoProviderFactory();

            try
            {
                if (theoryData.CustomCryptoProvider != null)
                {
                    cryptoProviderFactory.CustomCryptoProvider = theoryData.CustomCryptoProvider;
                }
                cryptoProviderFactory.ReleaseSignatureProvider(theoryData.SigningSignatureProvider);
                if (theoryData.CustomCryptoProvider != null && theoryData.SigningSignatureProvider != null && !((CustomCryptoProvider)theoryData.CustomCryptoProvider).ReleaseCalled)
                {
                    context.Diffs.Add("Release wasn't called on the CustomCryptoProvider.");
                }
                theoryData.ExpectedException.ProcessNoException(context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Ejemplo n.º 4
0
        // ReSharper disable once InconsistentNaming
        public byte[] Sign(string content)
        {
            var key        = Get();
            var cryptoProv = new CryptoProviderFactory();
            var provider   = cryptoProv.CreateForSigning(key, Algorithm);

            return(provider.Sign(Encoding.UTF8.GetBytes(content)));
        }
Ejemplo n.º 5
0
        public void DecryptedTextIsEqualToOriginalPlainText(BlockCipherEngines engine, BlockCipherModes mode)
        {
            var cryptoProvider      = new CryptoProviderFactory(engine, mode).Build();
            var cipherText          = cryptoProvider.Encrypt(_plainText, _encryptionKey);
            var decryptedCipherText = cryptoProvider.Decrypt(cipherText, _encryptionKey);

            Assert.That(decryptedCipherText, Is.EqualTo(_plainText));
        }
        public void EncryptionModeSerialized(BlockCipherEngines engine, BlockCipherModes mode)
        {
            var cryptoProvider = new CryptoProviderFactory(engine, mode).Build();
            var element        = _rootNodeSerializer.SerializeRootNodeInfo(_rootNodeInfo, cryptoProvider);
            var attributeValue = element.Attribute(XName.Get("BlockCipherMode"))?.Value;

            Assert.That(attributeValue, Is.EqualTo(mode.ToString()));
        }
 public DefaultAppleIdTokenValidator(
     [NotNull] AppleKeyStore keyStore,
     [NotNull] CryptoProviderFactory cryptoProviderFactory,
     [NotNull] ILogger <DefaultAppleIdTokenValidator> logger)
 {
     _keyStore = keyStore;
     _cryptoProviderFactory = cryptoProviderFactory;
     _logger = logger;
 }
        public void Setup()
        {
            var keyProvider = Substitute.For <IKeyProvider>();

            keyProvider.GetKey().Returns(_key);
            var cryptoProvider = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.CCM).Build();

            _serializer   = new XmlCredentialPasswordEncryptorDecorator(cryptoProvider, new XmlCredentialRecordSerializer());
            _deserializer = new XmlCredentialPasswordDecryptorDecorator(new XmlCredentialRecordDeserializer());
        }
Ejemplo n.º 9
0
        private static bool VerifySignature(WebAuthenticationSignInRequest request, IPublicKey publicKey)
        {
            var hash      = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(request.clientDataJSON));
            var assertion = Convert.FromBase64String(request.Base64CborAssertion);
            var data      = assertion.Concat(hash).ToArray();
            var signature = Convert.FromBase64String(request.Signature);

            var sigProvider = new CryptoProviderFactory().CreateForVerifying(publicKey.GetSecurityKey(), publicKey.Algorithum);

            return(sigProvider.Verify(data, signature));
        }
Ejemplo n.º 10
0
 public DefaultAppleClientSecretGenerator(
     [NotNull] IMemoryCache cache,
     [NotNull] ISystemClock clock,
     [NotNull] CryptoProviderFactory cryptoProviderFactory,
     [NotNull] ILogger <DefaultAppleClientSecretGenerator> logger)
 {
     _cache = cache;
     _clock = clock;
     _cryptoProviderFactory = cryptoProviderFactory;
     _logger = logger;
 }
        /// <summary>
        /// Verifies the digest of all <see cref="References"/>.
        /// </summary>
        /// <param name="cryptoProviderFactory">supplies any required cryptographic operators.</param>
        /// <exception cref="ArgumentNullException">if <paramref name="cryptoProviderFactory"/> is null.</exception>
        public void Verify(CryptoProviderFactory cryptoProviderFactory)
        {
            if (cryptoProviderFactory == null)
            {
                throw LogArgumentNullException(nameof(cryptoProviderFactory));
            }

            foreach (var reference in References)
            {
                reference.Verify(cryptoProviderFactory);
            }
        }
        public void Setup()
        {
            var connectionTreeModel      = SetupConnectionTreeModel();
            var cryptoProvider           = new CryptoProviderFactory(BlockCipherEngines.AES, BlockCipherModes.GCM).Build();
            var connectionNodeSerializer = new XmlConnectionNodeSerializer26(
                cryptoProvider,
                connectionTreeModel.RootNodes.OfType <RootNodeInfo>().First().PasswordString.ConvertToSecureString(),
                new SaveFilter());

            _originalDocument  = new XmlConnectionsDocumentCompiler(cryptoProvider, connectionNodeSerializer).CompileDocument(connectionTreeModel, false);
            _documentEncryptor = new XmlConnectionsDocumentEncryptor(cryptoProvider);
        }
        /// <summary>
        /// Creates a new instance of <see cref="OpenIdConnectProtocolValidator"/>,
        /// </summary>
        public OpenIdConnectProtocolValidator()
        {
            RequireAcr              = false;
            RequireAmr              = false;
            RequireAuthTime         = false;
            RequireAzp              = false;
            RequireNonce            = true;
            RequireState            = true;
            RequireTimeStampInNonce = true;
            RequireStateValidation  = true;

            _cryptoProviderFactory = new CryptoProviderFactory(CryptoProviderFactory.Default);
        }
 public DefaultAppleClientSecretGenerator(
     [NotNull] AppleKeyStore keyStore,
     [NotNull] ISystemClock clock,
     [NotNull] JwtSecurityTokenHandler tokenHandler,
     [NotNull] CryptoProviderFactory cryptoProviderFactory,
     [NotNull] ILogger <DefaultAppleClientSecretGenerator> logger)
 {
     _keyStore              = keyStore;
     _clock                 = clock;
     _tokenHandler          = tokenHandler;
     _cryptoProviderFactory = cryptoProviderFactory;
     _logger                = logger;
 }
Ejemplo n.º 15
0
        private SigningCredentials GetSigningCredentialsFromKeyVault(string keyVaultKeyString)
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();

            KeyVaultSecurityKey.AuthenticationCallback keyVaultAuthCallback = new KeyVaultSecurityKey.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback);
            KeyVaultSecurityKey   keyVaultSecurityKey   = new KeyVaultSecurityKey(keyVaultKeyString, keyVaultAuthCallback);
            CryptoProviderFactory cryptoProviderFactory = new CryptoProviderFactory {
                CustomCryptoProvider = new KeyVaultCryptoProvider()
            };

            return(new SigningCredentials(keyVaultSecurityKey, SecurityAlgorithms.RsaSha256)
            {
                CryptoProviderFactory = cryptoProviderFactory
            });
        }
Ejemplo n.º 16
0
        private static void Main(string[] args)
        {
            var jsonConfigurationFile = new JsonFile();

            jsonConfigurationFile.Read(new FileData("odcryptor.conf"));

            var decryptedFolderPath = jsonConfigurationFile.GetTag("DecryptedFolder");
            var encryptedFolderPath = jsonConfigurationFile.GetTag("EncryptedFolder");
            var masterKey           = Encoding.UTF8.GetBytes(jsonConfigurationFile.GetTag("MasterPassword"));

            var cryptor      = new Cryptor(CryptoProviderFactory.GetInfernoCryptoProvider(masterKey));
            var cryptoWorker = new CryptoWorker(cryptor);

            cryptoWorker.Sync(decryptedFolderPath, encryptedFolderPath);
        }
        private static byte[] DecryptToken(CryptoProviderFactory cryptoProviderFactory, SecurityKey key, JwtTokenDecryptionParameters decryptionParameters)
        {
            using (AuthenticatedEncryptionProvider decryptionProvider = cryptoProviderFactory.CreateAuthenticatedEncryptionProvider(key, decryptionParameters.Enc))
            {
                if (decryptionProvider == null)
                {
                    throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(TokenLogMessages.IDX10610, key, LogHelper.MarkAsNonPII(decryptionParameters.Enc))));
                }

                return(decryptionProvider.Decrypt(
                           Base64UrlEncoder.DecodeBytes(decryptionParameters.Ciphertext),
                           Encoding.ASCII.GetBytes(decryptionParameters.EncodedHeader),
                           Base64UrlEncoder.DecodeBytes(decryptionParameters.InitializationVector),
                           Base64UrlEncoder.DecodeBytes(decryptionParameters.AuthenticationTag)));
            }
        }
Ejemplo n.º 18
0
        public void ReleaseSignatureProviders(SignatureProviderTheoryData theoryData)
        {
            IdentityModelEventSource.ShowPII = true;
            var context = TestUtilities.WriteHeader($"{this}.ReleaseSignatureProviders", theoryData);
            var cryptoProviderFactory = new CryptoProviderFactory();

            try
            {
                cryptoProviderFactory.ReleaseSignatureProvider(theoryData.SigningSignatureProvider);
                theoryData.ExpectedException.ProcessNoException(context);
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            TestUtilities.AssertFailIfErrors(context);
        }
Ejemplo n.º 19
0
        public void CreateAndReleaseSignatureProviders(SignatureProviderTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.CreateAndReleaseSignatureProvidersTheoryData", theoryData);
            var cryptoProviderFactory = new CryptoProviderFactory()
            {
                CacheSignatureProviders = false
            };

            try
            {
                var signatureProvider = cryptoProviderFactory.CreateForSigning(theoryData.SigningKey, theoryData.SigningAlgorithm);
                if (cryptoProviderFactory.CryptoProviderCache.TryGetSignatureProvider(theoryData.SigningKey, theoryData.SigningAlgorithm, theoryData.SignatureProviderType, true, out var _))
                {
                    context.Diffs.Add("A SignatureProvider was added to CryptoProviderFactory.CryptoProviderCache, but CryptoProviderFactory.CacheSignatureProviders is false.");
                }

                cryptoProviderFactory.ReleaseSignatureProvider(signatureProvider);

                // If the signatureProvider is cached Dispose() will not be called on it.
                if (signatureProvider.GetType().Equals(typeof(AsymmetricSignatureProvider)))
                {
                    var disposeCalled = (bool)typeof(AsymmetricSignatureProvider).GetField("_disposed", BindingFlags.NonPublic | BindingFlags.Instance).GetValue((AsymmetricSignatureProvider)signatureProvider);
                    if (!disposeCalled)
                    {
                        context.Diffs.Add("Dispose wasn't called on the AsymmetricSignatureProvider.");
                    }
                }
                else // signatureProvider.GetType().Equals(typeof(SymmetricSignatureProvider))
                {
                    var disposeCalled = (bool)typeof(SymmetricSignatureProvider).GetField("_disposed", BindingFlags.NonPublic | BindingFlags.Instance).GetValue((SymmetricSignatureProvider)signatureProvider);
                    if (!disposeCalled)
                    {
                        context.Diffs.Add("Dispose wasn't called on the SymmetricSignatureProvider.");
                    }
                }
            }
            catch (Exception ex)
            {
                theoryData.ExpectedException.ProcessException(ex, context);
            }

            theoryData.ExpectedException.ProcessNoException(context);
            TestUtilities.AssertFailIfErrors(context);
        }
Ejemplo n.º 20
0
        /// <inheritdoc/>
        public void PostConfigure(
            [NotNull] string name,
            [NotNull] AppleAuthenticationOptions options)
        {
            if (options.JwtSecurityTokenHandler is null)
            {
                options.JwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            }

            // Use a custom CryptoProviderFactory so that keys are not cached and then disposed of, see below:
            // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1302
            var cryptoProviderFactory = new CryptoProviderFactory()
            {
                CacheSignatureProviders = false
            };

            if (options.KeyStore is null)
            {
                options.KeyStore = new DefaultAppleKeyStore(
                    _clock,
                    _loggerFactory.CreateLogger <DefaultAppleKeyStore>());
            }

            if (options.ClientSecretGenerator is null)
            {
                options.ClientSecretGenerator = new DefaultAppleClientSecretGenerator(
                    options.KeyStore,
                    _cache,
                    _clock,
                    cryptoProviderFactory,
                    _loggerFactory.CreateLogger <DefaultAppleClientSecretGenerator>());
            }

            if (options.TokenValidator is null)
            {
                options.TokenValidator = new DefaultAppleIdTokenValidator(
                    options.KeyStore,
                    cryptoProviderFactory,
                    _loggerFactory.CreateLogger <DefaultAppleIdTokenValidator>());
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Returns a cryptographic operator that supports the algorithm.
        /// </summary>
        /// <param name="algorithm">the algorithm that defines the cryptographic operator.</param>
        /// <param name="args">the arguments required by the cryptographic operator. May be null.</param>
        /// <exception cref="ArgumentNullException">if <paramref name="algorithm"/> is null or empty.</exception>
        /// <exception cref="ArgumentNullException">if <paramref name="args"/> is null.</exception>
        /// <exception cref="NotSupportedException">if <paramref name="args"/> does not contain a <see cref="KeyVaultSecurityKey"/>.</exception>
        /// <remarks>call <see cref="ICryptoProvider.Release(object)"/> when finished with the object.</remarks>
        public object Create(string algorithm, params object[] args)
        {
            if (string.IsNullOrEmpty(algorithm))
            {
                throw LogHelper.LogArgumentNullException(nameof(algorithm));
            }

            if (args == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(args));
            }

            if (args.FirstOrDefault() is KeyVaultSecurityKey key)
            {
                if (JsonWebKeyEncryptionAlgorithm.AllAlgorithms.Contains(algorithm, StringComparer.Ordinal))
                {
                    return(new KeyVaultKeyWrapProvider(key, algorithm));
                }
                else if (JsonWebKeySignatureAlgorithm.AllAlgorithms.Contains(algorithm, StringComparer.Ordinal))
                {
                    var willCreateSignatures = (bool)(args.Skip(1).FirstOrDefault() ?? false);

                    if (_cache.TryGetSignatureProvider(key, algorithm, typeofProvider: key.GetType().ToString(), willCreateSignatures, out var cachedProvider))
                    {
                        return(cachedProvider);
                    }

                    var signatureProvider = new KeyVaultSignatureProvider(key, algorithm, willCreateSignatures);
                    if (CryptoProviderFactory.ShouldCacheSignatureProvider(signatureProvider))
                    {
                        _cache.TryAdd(signatureProvider);
                    }

                    return(signatureProvider);
                }
            }

            throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10652, LogHelper.MarkAsNonPII(algorithm))));
        }
        /// <summary>
        /// Returns a <see cref="HashAlgorithm"/> corresponding to string 'algorithm' after translation using <see cref="HashAlgorithmMap"/>.
        /// </summary>
        /// <param name="algorithm">string representing the hash algorithm</param>
        /// <returns>A <see cref="HashAlgorithm"/>.</returns>
        public virtual HashAlgorithm GetHashAlgorithm(string algorithm)
        {
            if (string.IsNullOrEmpty(algorithm))
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogMessages.IDX21350));
            }

            try
            {
                if (!HashAlgorithmMap.TryGetValue(algorithm, out string hashAlgorithm))
                {
                    hashAlgorithm = algorithm;
                }

                return(CryptoProviderFactory.CreateHashAlgorithm(hashAlgorithm));
            }
            catch (Exception ex)
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogHelper.FormatInvariant(LogMessages.IDX21301, algorithm, typeof(HashAlgorithm)), ex));
            }

            throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(LogHelper.FormatInvariant(LogMessages.IDX21302, algorithm)));
        }
        public void TryAdd(CryptoProviderCacheTheoryData theoryData)
        {
            var context = TestUtilities.WriteHeader($"{this}.TryAdd", theoryData);

            try
            {
                bool shouldCreate = CryptoProviderFactory.ShouldCacheSignatureProvider(theoryData.SignatureProvider);

                var added = theoryData.CryptoProviderCache.TryAdd(theoryData.SignatureProvider);
                if (theoryData.Added != added && shouldCreate)
                {
                    context.Diffs.Add($"theoryData.Added:'{theoryData.Added}' != theoryData.CryptoProviderCache.TryAdd(theoryData.SignatureProvider)");
                }

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

            TestUtilities.AssertFailIfErrors(context);
        }
        public void CryptoProviderFactory_Tests()
        {
            CryptoProviderFactory factory = new CryptoProviderFactory();

            // Asymmetric / Symmetric both need signature alg specified
            FactoryCreateFor("Signing: algorithm string.Empty", KeyingMaterial.X509SecurityKey_1024, string.Empty, factory, ExpectedException.ArgumentNullException());
            FactoryCreateFor("Verifying: algorithm string.Empty", KeyingMaterial.X509SecurityKey_1024, string.Empty, factory, ExpectedException.ArgumentNullException());

            // Json Web Keys
            FactoryCreateFor("Signing: No exception", KeyingMaterial.JsonWebKeyRsa256, SecurityAlgorithms.RsaSha256, factory, ExpectedException.NoExceptionExpected);
            FactoryCreateFor("Signing: security key without private key", KeyingMaterial.JsonWebKeyRsa256Public, SecurityAlgorithms.RsaSha256, factory, ExpectedException.InvalidOperationException("IDX10638:"));
            FactoryCreateFor("Verifying: No exception", KeyingMaterial.JsonWebKeyRsa256Public, SecurityAlgorithms.RsaSha256, factory, ExpectedException.NoExceptionExpected);
            FactoryCreateFor("Signing: No exception", KeyingMaterial.JsonWebKeySymmetric256, SecurityAlgorithms.HmacSha256, factory, ExpectedException.NoExceptionExpected);
            FactoryCreateFor("Verifying: No exception", KeyingMaterial.JsonWebKeySymmetric256, SecurityAlgorithms.HmacSha256, factory, ExpectedException.NoExceptionExpected);

            // Keytype not supported
            FactoryCreateFor("Signing: SecurityKey type not Asymmetric or Symmetric", NotAsymmetricOrSymmetricSecurityKey.New, SecurityAlgorithms.HmacSha256Signature, factory, ExpectedException.ArgumentException("IDX10634:"));
            FactoryCreateFor("Verifying: SecurityKey type not Asymmetric or Symmetric", NotAsymmetricOrSymmetricSecurityKey.New, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.ArgumentException("IDX10634:"));

            // Private keys missing
            FactoryCreateFor("Signing RsaSecurityKey_2048_Public: SecurityKey without private key", KeyingMaterial.RsaSecurityKey_2048_Public, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.InvalidOperationException(substringExpected: "IDX10638:"));
            FactoryCreateFor("Verifying RsaSecurityKey_2048_Public: SecurityKey without private key", KeyingMaterial.RsaSecurityKey_2048_Public, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.NoExceptionExpected);
            FactoryCreateFor("Signing ECDsa256Key_Public: SecurityKey without private key", KeyingMaterial.ECDsa256Key_Public, SecurityAlgorithms.EcdsaSha256, factory, ExpectedException.InvalidOperationException(substringExpected: "IDX10638:"));

            // Key size checks
            FactoryCreateFor("Signing: AsymmetricKeySize Key to small", KeyingMaterial.X509SecurityKey_1024, SecurityAlgorithms.RsaSha256Signature, factory, ExpectedException.ArgumentOutOfRangeException("IDX10630:"));
            FactoryCreateFor("Signing: SymmetricKeySize Key to small", KeyingMaterial.SymmetricSecurityKey_56, SecurityAlgorithms.HmacSha256Signature, factory, ExpectedException.ArgumentOutOfRangeException("IDX10603:"));

            FactoryCreateFor("Signing: SymmetricKeySize Key", KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, factory, ExpectedException.NoExceptionExpected);
            FactoryCreateFor("Verifying: SymmetricKeySize Key", KeyingMaterial.DefaultSymmetricSecurityKey_256, SecurityAlgorithms.HmacSha256Signature, factory, ExpectedException.NoExceptionExpected);

            // extensibility tests
            // smaller key sizes but no exceptions using custom crypto factory
            FactoryCreateFor("Signing: AsymmetricKeySize Key to small", KeyingMaterial.X509SecurityKey_1024, SecurityAlgorithms.RsaSha256Signature, new CustomCryptoProviderFactory(new string[] { SecurityAlgorithms.RsaSha256Signature }), ExpectedException.NoExceptionExpected);
            FactoryCreateFor("Signing: SymmetricKeySize Key to small", KeyingMaterial.SymmetricSecurityKey_56, SecurityAlgorithms.HmacSha256Signature, new CustomCryptoProviderFactory(new string[] { SecurityAlgorithms.HmacSha256Signature }), ExpectedException.NoExceptionExpected);
        }
        /// <summary>
        /// Returns a <see cref="HashAlgorithm"/> corresponding to string 'algorithm' after translation using <see cref="HashAlgorithmMap"/>.
        /// </summary>
        /// <param name="algorithm">string representing the hash algorithm</param>
        /// <returns>A <see cref="HashAlgorithm"/>.</returns>
        public virtual HashAlgorithm GetHashAlgorithm(string algorithm)
        {
            if (algorithm == null)
            {
                algorithm = SecurityAlgorithms.RsaSha256;
            }

            try
            {
                string hashAlgorithm;
                if (!HashAlgorithmMap.TryGetValue(algorithm, out hashAlgorithm))
                {
                    hashAlgorithm = algorithm;
                }

                return(CryptoProviderFactory.CreateHashAlgorithm(hashAlgorithm));
            }
            catch (Exception ex)
            {
                throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10301, algorithm, typeof(HashAlgorithm)), ex));
            }

            throw LogHelper.LogExceptionMessage(new OpenIdConnectProtocolException(String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10302, algorithm)));
        }
Ejemplo n.º 26
0
        public void Initialize()
        {
            var cryptoProvider = CryptoProviderFactory.GetInfernoCryptoProvider(Encoding.UTF8.GetBytes("Password"));

            _cryptor = new Cryptor(cryptoProvider);
        }
Ejemplo n.º 27
0
 /// <inheritdoc/>
 public override bool IsSupportedAlgorithm(string algorithm)
 {
     return(CryptoProviderFactory?.IsSupportedAlgorithm(algorithm) == true);
 }
Ejemplo n.º 28
0
    /// <inheritdoc/>
    public void PostConfigure(
        [NotNull] string name,
        [NotNull] AppleAuthenticationOptions options)
    {
        // Use a custom CryptoProviderFactory so that keys are not cached and then disposed of, see below:
        // https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/1302
        var cryptoProviderFactory = new CryptoProviderFactory()
        {
            CacheSignatureProviders = false
        };

        if (options.ClientSecretGenerator is null)
        {
            options.ClientSecretGenerator = new DefaultAppleClientSecretGenerator(
                _cache,
                _clock,
                cryptoProviderFactory,
                _loggerFactory.CreateLogger <DefaultAppleClientSecretGenerator>());
        }

        if (options.TokenValidator is null)
        {
            options.TokenValidator = new DefaultAppleIdTokenValidator(
                _loggerFactory.CreateLogger <DefaultAppleIdTokenValidator>());
        }

        if (options.ConfigurationManager is null)
        {
            if (string.IsNullOrEmpty(options.MetadataEndpoint))
            {
                throw new InvalidOperationException($"The {nameof(AppleAuthenticationOptions.MetadataEndpoint)} property must be set on the {nameof(AppleAuthenticationOptions)} instance.");
            }

            // As seen in:
            // github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/OpenIdConnect/src/OpenIdConnectPostConfigureOptions.cs#L71-L102
            // need this now to successfully instantiate ConfigurationManager below.
            if (options.Backchannel is null)
            {
#pragma warning disable CA2000 // Dispose objects before losing scope
                options.Backchannel = new HttpClient(options.BackchannelHttpHandler ?? new HttpClientHandler());
#pragma warning restore CA2000 // Dispose objects before losing scope
                options.Backchannel.DefaultRequestHeaders.UserAgent.ParseAdd("Apple OAuth handler");
                options.Backchannel.Timeout = options.BackchannelTimeout;
                options.Backchannel.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
            }

            options.ConfigurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(
                options.MetadataEndpoint,
                new OpenIdConnectConfigurationRetriever(),
                new HttpDocumentRetriever(options.Backchannel));
        }

        if (options.SecurityTokenHandler is null)
        {
            options.SecurityTokenHandler = new JsonWebTokenHandler();
        }

        if (options.TokenValidationParameters is null)
        {
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                CryptoProviderFactory = cryptoProviderFactory,
                ValidateAudience      = true,
                ValidateIssuer        = true,
                ValidAudience         = options.ClientId,
                ValidIssuer           = options.TokenAudience
            };
        }
    }
Ejemplo n.º 29
0
        public void CanCreateAeadProvidersWithCorrectMode(BlockCipherEngines engine, BlockCipherModes mode)
        {
            var cryptoProvider = new CryptoProviderFactory(engine, mode).Build();

            Assert.That(cryptoProvider.CipherMode, Is.EqualTo(mode));
        }
Ejemplo n.º 30
0
        public void GetSets()
        {
            TestUtilities.WriteHeader($"{this}.GetSets");
            var context = new CompareContext($"{this}.GetSets");

            CryptoProviderFactory cryptoProviderFactory = new CryptoProviderFactory();
            Type type = typeof(CryptoProviderFactory);

            PropertyInfo[] properties = type.GetProperties();
            if (properties.Length != 7)
            {
                Assert.True(false, "Number of public fields has changed from 7 to: " + properties.Length + ", adjust tests");
            }

            CustomCryptoProvider customCryptoProvider = new CustomCryptoProvider();
            GetSetContext        getSetContext        =
                new GetSetContext
            {
                PropertyNamesAndSetGetValue = new List <KeyValuePair <string, List <object> > >
                {
                    new KeyValuePair <string, List <object> >("SignatureProviderObjectPoolCacheSize", new List <object> {
                        CryptoProviderFactory.DefaultSignatureProviderObjectPoolCacheSize, 20, 10
                    }),
                    new KeyValuePair <string, List <object> >("CacheSignatureProviders", new List <object> {
                        CryptoProviderFactory.DefaultCacheSignatureProviders, false, true
                    }),
                    new KeyValuePair <string, List <object> >("CustomCryptoProvider", new List <object> {
                        (ICryptoProvider)null, customCryptoProvider, null
                    }),
                },
                Object = cryptoProviderFactory,
            };

            TestUtilities.GetSet(getSetContext);

            cryptoProviderFactory.SignatureProviderObjectPoolCacheSize = 42;
            cryptoProviderFactory.CacheSignatureProviders = false;
            cryptoProviderFactory.CustomCryptoProvider    = customCryptoProvider;
            CryptoProviderFactory clone = new CryptoProviderFactory(cryptoProviderFactory);

            IdentityComparer.CompareAllPublicProperties(clone, cryptoProviderFactory, context);

            try
            {
                cryptoProviderFactory.SignatureProviderObjectPoolCacheSize = 0;
                context.AddDiff("cryptoProviderFactory.SignatureProviderObjectPoolCacheSize = 0; - Succeeded");
            }
            catch
            {
            }

            try
            {
                cryptoProviderFactory.SignatureProviderObjectPoolCacheSize = -1;
                context.AddDiff("cryptoProviderFactory.SignatureProviderObjectPoolCacheSize = -1; - Succeeded");
            }
            catch
            {
            }

            context.Diffs.AddRange(getSetContext.Errors);
            TestUtilities.AssertFailIfErrors(context);
        }