Ejemplo n.º 1
0
        public static string IssueToken()
        {
            Microsoft.IdentityModel.Tokens.SecurityKey sKey = SecurityConstants.SymKey;

            sKey = SecurityConstants.RsaKey;

            // sKey = SecurityConstants.RsaKey;
            // sKey = new CustomAsymmetricKey();
            // System.Security.Cryptography.X509Certificates.X509Certificate2 cert2 = DotNetUtilities.CreateX509Cert2("mycert");
            // SecurityKey secKey = new X509SecurityKey(cert2);


            List <Claim> claimList = new List <Claim>()
            {
                new Claim(ClaimTypes.Name, "userName"),
                new Claim(ClaimTypes.Role, "role") // Not sure what this is for
            };



            //JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
            System.IdentityModel.Tokens.Jwt2.JwtSecurityTokenHandler tokenHandler = new System.IdentityModel.Tokens.Jwt2.JwtSecurityTokenHandler();
            SecurityTokenDescriptor desc = makeSecurityTokenDescriptor(sKey, claimList);
            string strToken = tokenHandler.CreateJwtSecurityToken(desc).ToString();

            System.Console.WriteLine(strToken);

            return(tokenHandler.CreateEncodedJwt(desc));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Create and sign JWT token.
        /// </summary>
        public static JwtSecurityToken CreateToken(MSTokens.SecurityKey securityKey, string issuer, IEnumerable <string> audiences, IEnumerable <Claim> claims, DateTimeOffset?issuedAt = null, int beforeIn = 60, int expiresIn = 3600,
                                                   string algorithm = IdentityConstants.Algorithms.Asymmetric.RS256, string typ = IdentityConstants.JwtHeaders.MediaTypes.Jwt)
        {
            if (securityKey == null)
            {
                throw new ArgumentNullException(nameof(securityKey));
            }
            if (issuer.IsNullOrEmpty())
            {
                throw new ArgumentNullException(nameof(issuer));
            }
            if (audiences?.Count() < 1)
            {
                throw new ArgumentException($"At least one audience is required.", nameof(audiences));
            }
            if (claims?.Count() < 1)
            {
                throw new ArgumentException($"At least one claim is required.", nameof(claims));
            }

            var key    = securityKey is MSTokens.JsonWebKey jsonWebKey ? jsonWebKey.ToSecurityKey() : securityKey;
            var header = new JwtHeader(new MSTokens.SigningCredentials(key, algorithm));

            if (!typ.IsNullOrEmpty())
            {
                header[IdentityConstants.JwtHeaders.Typ] = typ;
            }

            if (!issuedAt.HasValue)
            {
                issuedAt = DateTimeOffset.UtcNow;
            }
            var payload = new JwtPayload(issuer, audiences.First(), claims, issuedAt.Value.AddSeconds(-beforeIn).UtcDateTime, issuedAt.Value.AddSeconds(expiresIn).UtcDateTime, issuedAt.Value.UtcDateTime);

            if (audiences.Count() > 1)
            {
                foreach (var audience in audiences.Skip(1))
                {
                    payload.AddClaim(new Claim(JwtClaimTypes.Audience, audience));
                }
            }
            return(new JwtSecurityToken(header, payload));
        }
 // HasAlgorithmName was introduced into Net46
 internal AsymmetricAdapter(SecurityKey key, string algorithm, HashAlgorithm hashAlgorithm, HashAlgorithmName hashAlgorithmName, bool requirePrivateKey)
     : this(key, algorithm, hashAlgorithm, requirePrivateKey)
 {
     HashAlgorithmName = hashAlgorithmName;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Create and sign JWT token.
 /// </summary>
 public static JwtSecurityToken CreateToken(MSTokens.SecurityKey securityKey, string issuer, string audience, IEnumerable <Claim> claims, DateTimeOffset?issuedAt = null, int beforeIn = 60, int expiresIn = 3600,
                                            string algorithm = IdentityConstants.Algorithms.Asymmetric.RS256, string typ = IdentityConstants.JwtHeaders.MediaTypes.Jwt)
 {
     return(CreateToken(securityKey, issuer, new[] { audience }, claims, issuedAt: issuedAt, beforeIn: beforeIn, expiresIn: expiresIn, algorithm: algorithm, typ: typ));
 }
Ejemplo n.º 5
0
 internal AsymmetricSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures, CryptoProviderFactory cryptoProviderFactory)
     : this(key, algorithm, willCreateSignatures)
 {
     _cryptoProviderFactory = cryptoProviderFactory;
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SignatureProvider"/> class used to create and verify signatures.
 /// </summary>
 /// <param name="key">The <see cref="SecurityKey"/> that will be used for signature operations.</param>
 /// <param name="algorithm">The signature algorithm to apply.</param>
 /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="algorithm"/> is null or empty.</exception>
 protected SignatureProvider(SecurityKey key, string algorithm)
 {
     Key       = key ?? throw LogHelper.LogArgumentNullException(nameof(key));
     Algorithm = (string.IsNullOrEmpty(algorithm)) ? throw LogHelper.LogArgumentNullException(nameof(algorithm)) : algorithm;
 }
 /// <summary>
 /// Checks if an 'key, algorithm' pair is supported
 /// </summary>
 /// <param name="key">the <see cref="SecurityKey"/></param>
 /// <param name="algorithm">the algorithm to check.</param>
 /// <returns>true if 'key, algorithm' pair is supported.</returns>
 protected virtual bool IsSupportedAlgorithm(SecurityKey key, string algorithm)
 {
     return(SupportedAlgorithms.IsSupportedEncryptionAlgorithm(algorithm, key));
 }
        private SignatureProvider CreateSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

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

            if (CustomCryptoProvider != null && CustomCryptoProvider.IsSupportedAlgorithm(algorithm, key, willCreateSignatures))
            {
                SignatureProvider signatureProvider = CustomCryptoProvider.Create(algorithm, key, willCreateSignatures) as SignatureProvider;
                if (signatureProvider == null)
                {
                    throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10646, algorithm, key, typeof(SignatureProvider))));
                }

                return(signatureProvider);
            }

            if (!IsSupportedAlgorithm(algorithm, key))
            {
                throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10634, algorithm, key)));
            }

            AsymmetricSecurityKey asymmetricKey = key as AsymmetricSecurityKey;

            if (asymmetricKey != null)
            {
                return(new AsymmetricSignatureProvider(asymmetricKey, algorithm, willCreateSignatures));
            }

            SymmetricSecurityKey symmetricKey = key as SymmetricSecurityKey;

            if (symmetricKey != null)
            {
                return(new SymmetricSignatureProvider(symmetricKey, algorithm));
            }

            JsonWebKey jsonWebKey = key as JsonWebKey;

            if (jsonWebKey != null)
            {
                if (jsonWebKey.Kty != null)
                {
                    if (jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.RSA || jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.EllipticCurve)
                    {
                        return(new AsymmetricSignatureProvider(key, algorithm, willCreateSignatures));
                    }

                    if (jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.Octet)
                    {
                        return(new SymmetricSignatureProvider(key, algorithm));
                    }
                }
            }

            throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10800, typeof(SignatureProvider), typeof(SecurityKey), typeof(AsymmetricSecurityKey), typeof(SymmetricSecurityKey), key.GetType())));
        }
 /// <summary>
 /// Creates a <see cref="SignatureProvider"/> that supports the <see cref="SecurityKey"/> and algorithm.
 /// </summary>
 /// <param name="key">The <see cref="SecurityKey"/> to use for signing.</param>
 /// <param name="algorithm">The algorithm to use for signing.</param>
 /// <exception cref="ArgumentNullException">'key' is null.</exception>
 /// <exception cref="ArgumentNullException">'algorithm' is null or empty.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><see cref="AsymmetricSecurityKey"/>' is too small.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><see cref="SymmetricSecurityKey"/> is too small.</exception>
 /// <exception cref="ArgumentException"><see cref="SecurityKey"/> is not a <see cref="AsymmetricSecurityKey"/> or a <see cref="SymmetricSecurityKey"/>.</exception>
 /// <remarks>
 /// AsymmetricSignatureProviders require access to a PrivateKey for Signing.
 /// <para>When finished with the <see cref="SignatureProvider"/> call <see cref="ReleaseSignatureProvider(SignatureProvider)"/>.</para>
 /// </remarks>
 public virtual SignatureProvider CreateForSigning(SecurityKey key, string algorithm)
 {
     return(CreateSignatureProvider(key, algorithm, true));
 }
        internal static bool IsSupportedAuthenticatedEncryptionAlgorithm(string algorithm, SecurityKey key)
        {
            if (key == null)
            {
                return(false);
            }

            if (string.IsNullOrEmpty(algorithm))
            {
                return(false);
            }

            if (!(algorithm.Equals(SecurityAlgorithms.Aes128CbcHmacSha256, StringComparison.Ordinal) ||
                  algorithm.Equals(SecurityAlgorithms.Aes192CbcHmacSha384, StringComparison.Ordinal) ||
                  algorithm.Equals(SecurityAlgorithms.Aes256CbcHmacSha512, StringComparison.Ordinal)))
            {
                return(false);
            }

            if (key is SymmetricSecurityKey)
            {
                return(true);
            }

            if (key is JsonWebKey jsonWebKey)
            {
                return(jsonWebKey.K != null && jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.Octet);
            }

            return(false);
        }
Ejemplo n.º 11
0
        internal static RsaAlgorithm ResolveRsaAlgorithm(SecurityKey key, string algorithm, bool requirePrivateKey)
        {
            if (key == null)
            {
                return(null);
            }

            var rsaAlgorithm = new RsaAlgorithm();
            var rsaKey       = key as RsaSecurityKey;

            if (rsaKey != null)
            {
                if (rsaKey.Rsa != null)
                {
#if NETSTANDARD1_4
                    rsaAlgorithm.rsa = rsaKey.Rsa;
#else
                    rsaAlgorithm.rsaCryptoServiceProvider = rsaKey.Rsa as RSACryptoServiceProvider;
#endif
                    return(rsaAlgorithm);
                }
                else
                {
#if NETSTANDARD1_4
                    rsaAlgorithm.rsa = RSA.Create();
                    rsaAlgorithm.rsa.ImportParameters(rsaKey.Parameters);
                    rsaAlgorithm.dispose = true;
#else
                    rsaAlgorithm.rsaCryptoServiceProvider = new RSACryptoServiceProvider();
                    (rsaAlgorithm.rsaCryptoServiceProvider as RSA).ImportParameters(rsaKey.Parameters);
                    rsaAlgorithm.dispose = true;
#endif
                }

                return(rsaAlgorithm);
            }

            X509SecurityKey x509Key = key as X509SecurityKey;
            if (x509Key != null)
            {
#if NETSTANDARD1_4
                if (requirePrivateKey)
                {
                    rsaAlgorithm.rsa = x509Key.PrivateKey as RSA;
                }
                else
                {
                    rsaAlgorithm.rsa = x509Key.PublicKey as RSA;
                }
#else
                if (requirePrivateKey)
                {
                    rsaAlgorithm.rsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(x509Key.PrivateKey as RSACryptoServiceProvider);
                }
                else
                {
                    rsaAlgorithm.rsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(x509Key.PublicKey as RSACryptoServiceProvider);
                }
#endif
                return(rsaAlgorithm);
            }

            JsonWebKey webKey = key as JsonWebKey;
            if (webKey != null && webKey.Kty == JsonWebAlgorithmsKeyTypes.RSA)
            {
#if NETSTANDARD1_4
                RSAParameters parameters = webKey.CreateRsaParameters();
                rsaAlgorithm.rsa     = RSA.Create();
                rsaAlgorithm.dispose = true;
                if (rsaAlgorithm.rsa != null)
                {
                    rsaAlgorithm.rsa.ImportParameters(parameters);
                }
#else
                RSAParameters parameters = webKey.CreateRsaParameters();
                rsaAlgorithm.rsaCryptoServiceProvider = new RSACryptoServiceProvider();
                (rsaAlgorithm.rsaCryptoServiceProvider as RSA).ImportParameters(parameters);
#endif
                return(rsaAlgorithm);
            }

            return(null);
        }
 private string GetCacheKeyPrivate(SecurityKey securityKey, string algorithm, string typeofProvider)
 {
     return(string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2}-{3}", securityKey.GetType(), securityKey.KeyId, algorithm, typeofProvider));
 }
 /// <summary>
 /// Checks if an algorithm is supported.
 /// </summary>
 /// <param name="key">The <see cref="SecurityKey"/> that will be used for crypto operations.</param>
 /// <param name="algorithm">The KeyWrap algorithm to apply.</param>
 /// <returns>true if the algorithm is supported; otherwise, false.</returns>
 protected virtual bool IsSupportedAlgorithm(SecurityKey key, string algorithm)
 {
     return(SupportedAlgorithms.IsSupportedRsaKeyWrap(algorithm, key));
 }
 // Encryption algorithms do not need a HashAlgorithm, this is called by RSAKeyWrap
 internal AsymmetricAdapter(SecurityKey key, string algorithm, bool requirePrivateKey)
     : this(key, algorithm, null, requirePrivateKey)
 {
 }
 /// <summary>
 /// Creates an instance of <see cref="KeyWrapProvider"/> for a specific &lt;SecurityKey, Algorithm>.
 /// </summary>
 /// <param name="key">the <see cref="SecurityKey"/> to use.</param>
 /// <param name="algorithm">the algorithm to use.</param>
 /// <returns>an instance of <see cref="KeyWrapProvider"/></returns>
 /// <exception cref="ArgumentNullException">'key' is null.</exception>
 /// <exception cref="ArgumentNullException">'algorithm' is null or empty.</exception>
 /// <exception cref="ArgumentException">If <see cref="SecurityKey"/> and algorithm pair are not supported.</exception>
 /// <remarks>
 /// <para>When finished with the <see cref="KeyWrapProvider"/> call <see cref="ReleaseKeyWrapProvider(KeyWrapProvider)"/>.</para>
 /// </remarks>
 public virtual KeyWrapProvider CreateKeyWrapProvider(SecurityKey key, string algorithm)
 {
     return(CreateKeyWrapProvider(key, algorithm, false));
 }
 /// <summary>
 /// Creates an instance of <see cref="KeyWrapProvider"/> for a specific &lt;SecurityKey, Algorithm>.
 /// </summary>
 /// <param name="key">the <see cref="SecurityKey"/> to use.</param>
 /// <param name="algorithm">the algorithm to use.</param>
 /// <returns>an instance of <see cref="KeyWrapProvider"/></returns>
 /// <exception cref="ArgumentNullException">'key' is null.</exception>
 /// <exception cref="ArgumentNullException">'algorithm' is null or empty.</exception>
 /// <exception cref="ArgumentException">If <see cref="SecurityKey"/> and algorithm pair are not supported.</exception>
 /// <remarks>
 /// <para>When finished with the <see cref="KeyWrapProvider"/> call <see cref="ReleaseKeyWrapProvider(KeyWrapProvider)"/>.</para>
 /// </remarks>
 public virtual KeyWrapProvider CreateKeyWrapProviderForUnwrap(SecurityKey key, string algorithm)
 {
     return(CreateKeyWrapProvider(key, algorithm, true));
 }
 internal static bool IsSupportedRsaAlgorithm(string algorithm, SecurityKey key)
 {
     return(RsaSigningAlgorithms.Contains(algorithm) ||
            RsaEncryptionAlgorithms.Contains(algorithm) ||
            (RsaPssSigningAlgorithms.Contains(algorithm) && IsSupportedRsaPss(key)));
 }
 /// <summary>
 /// Returns a <see cref="SignatureProvider"/> instance supports the <see cref="SecurityKey"/> and algorithm.
 /// </summary>
 /// <param name="key">The <see cref="SecurityKey"/> to use for signing.</param>
 /// <param name="algorithm">The algorithm to use for verifying.</param>
 /// <exception cref="ArgumentNullException">'key' is null.</exception>
 /// <exception cref="ArgumentNullException">'algorithm' is null or empty.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><see cref="AsymmetricSecurityKey"/> is too small.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><see cref="SymmetricSecurityKey"/> is too small.</exception>
 /// <exception cref="ArgumentException"><see cref="SecurityKey"/>' is not a <see cref="AsymmetricSecurityKey"/> or a <see cref="SymmetricSecurityKey"/>.</exception>
 /// <remarks>When finished with the <see cref="SignatureProvider"/> call <see cref="ReleaseSignatureProvider(SignatureProvider)"/>.</remarks>
 public virtual SignatureProvider CreateForVerifying(SecurityKey key, string algorithm)
 {
     return(CreateSignatureProvider(key, algorithm, false));
 }
Ejemplo n.º 19
0
        private void ResolveAsymmetricAlgorithm(SecurityKey key, string algorithm, bool willCreateSignatures)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException("key");
            }

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

            _hashAlgorithm = GetHashAlgorithmString(algorithm);
            RsaSecurityKey rsaKey = key as RsaSecurityKey;

            if (rsaKey != null)
            {
                if (rsaKey.Rsa != null)
                {
                    _rsaCryptoServiceProvider = rsaKey.Rsa as RSACryptoServiceProvider;
                }

                if (_rsaCryptoServiceProvider == null)
                {
                    _rsaCryptoServiceProvider = new RSACryptoServiceProvider();
                    (_rsaCryptoServiceProvider as RSA).ImportParameters(rsaKey.Parameters);
                    _disposeRsa = true;
                }
                return;
            }

            X509SecurityKey x509Key = key as X509SecurityKey;

            if (x509Key != null)
            {
                if (willCreateSignatures)
                {
                    _rsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(x509Key.PrivateKey as RSACryptoServiceProvider);
                }
                else
                {
                    _rsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(x509Key.PublicKey as RSACryptoServiceProvider);
                }
                return;
            }

            ECDsaSecurityKey ecdsaKey = key as ECDsaSecurityKey;

            if (ecdsaKey != null)
            {
                if (ecdsaKey.ECDsa != null)
                {
                    _ecdsa = ecdsaKey.ECDsa as ECDsaCng;
                    _ecdsa.HashAlgorithm = new CngAlgorithm(_hashAlgorithm);
                    return;
                }
            }

            JsonWebKey webKey = key as JsonWebKey;

            if (webKey.Kty == JsonWebAlgorithmsKeyTypes.RSA)
            {
                RSAParameters parameters = CreateRsaParametersFromJsonWebKey(webKey, willCreateSignatures);
                _rsaCryptoServiceProvider = new RSACryptoServiceProvider();
                (_rsaCryptoServiceProvider as RSA).ImportParameters(parameters);
                return;
            }
            else if (webKey.Kty == JsonWebAlgorithmsKeyTypes.EllipticCurve)
            {
                CreateECDsaFromJsonWebKey(webKey, willCreateSignatures);
                return;
            }

            throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10641, key)));
        }
Ejemplo n.º 20
0
        public static SymmetricAlgorithm CreateSymmetricAlgorithm(this CryptoProviderFactory crypto, SecurityKey securityKey, string algorithm)
        {
            if (securityKey == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(securityKey));
            }

            if (!(securityKey is SymmetricSecurityKey symmetricKey))
            {
                throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(InvalidSecurityKey, securityKey.GetType().Name)));
            }

            var symmetric = crypto.CreateSymmetricAlgorithm(algorithm);

            symmetric.Key = symmetricKey.Key;
            return(symmetric);
        }
 static EmissorTokenJwt()
 {
     chave = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(GetBytes(ConfigurationManager.AppSettings["ChaveToken"]));
 }
        /// <summary>
        /// Checks that the key has sufficient length
        /// </summary>
        /// <param name="key"><see cref="SecurityKey"/> that contains bytes.</param>
        /// <param name="algorithm">the algorithm to apply.</param>
        /// <exception cref="ArgumentNullException">if <paramref name="key"/> is null.</exception>
        /// <exception cref="ArgumentNullException">if <paramref name="algorithm"/> is null or empty.</exception>
        /// <exception cref="ArgumentException">if <paramref name="algorithm"/> is not a supported algorithm.</exception>
        protected virtual void ValidateKeySize(SecurityKey key, string algorithm)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

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

            if (SecurityAlgorithms.Aes128CbcHmacSha256.Equals(algorithm))
            {
                if (key.KeySize < 256)
                {
                    throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10653, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes128CbcHmacSha256), LogHelper.MarkAsNonPII(256), key.KeyId, LogHelper.MarkAsNonPII(key.KeySize))));
                }

                return;
            }

            if (SecurityAlgorithms.Aes192CbcHmacSha384.Equals(algorithm))
            {
                if (key.KeySize < 384)
                {
                    throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10653, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes192CbcHmacSha384), LogHelper.MarkAsNonPII(384), key.KeyId, LogHelper.MarkAsNonPII(key.KeySize))));
                }

                return;
            }

            if (SecurityAlgorithms.Aes256CbcHmacSha512.Equals(algorithm))
            {
                if (key.KeySize < 512)
                {
                    throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10653, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes256CbcHmacSha512), LogHelper.MarkAsNonPII(512), key.KeyId, LogHelper.MarkAsNonPII(key.KeySize))));
                }

                return;
            }

            if (SecurityAlgorithms.Aes128Gcm.Equals(algorithm))
            {
                if (key.KeySize < 128)
                {
                    throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10653, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes128Gcm), LogHelper.MarkAsNonPII(128), key.KeyId, LogHelper.MarkAsNonPII(key.KeySize))));
                }

                return;
            }

            if (SecurityAlgorithms.Aes192Gcm.Equals(algorithm))
            {
                if (key.KeySize < 192)
                {
                    throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10653, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes192Gcm), LogHelper.MarkAsNonPII(192), key.KeyId, LogHelper.MarkAsNonPII(key.KeySize))));
                }

                return;
            }

            if (SecurityAlgorithms.Aes256Gcm.Equals(algorithm))
            {
                if (key.KeySize < 256)
                {
                    throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(key), LogHelper.FormatInvariant(LogMessages.IDX10653, LogHelper.MarkAsNonPII(SecurityAlgorithms.Aes256Gcm), LogHelper.MarkAsNonPII(256), key.KeyId, LogHelper.MarkAsNonPII(key.KeySize))));
                }

                return;
            }

            throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX10652, LogHelper.MarkAsNonPII(algorithm))));
        }
Ejemplo n.º 23
0
        private SignatureProvider CreateSignatureProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

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

            SignatureProvider signatureProvider = null;

            if (CustomCryptoProvider != null && CustomCryptoProvider.IsSupportedAlgorithm(algorithm, key, willCreateSignatures))
            {
                signatureProvider = CustomCryptoProvider.Create(algorithm, key, willCreateSignatures) as SignatureProvider;
                if (signatureProvider == null)
                {
                    throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10646, algorithm, key, typeof(SignatureProvider))));
                }

                return(signatureProvider);
            }

            // types are checked in order of expected occurrence
            string typeofSignatureProvider = null;
            bool   createAsymmetric        = true;

            if (key is AsymmetricSecurityKey asymmetricSecurityKey)
            {
                typeofSignatureProvider = typeof(AsymmetricSignatureProvider).ToString();
            }
            else if (key is JsonWebKey jsonWebKey)
            {
                if (jsonWebKey.Kty != null)
                {
                    if (jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.RSA || jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.EllipticCurve)
                    {
                        typeofSignatureProvider = typeof(AsymmetricSignatureProvider).ToString();
                    }

                    if (jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.Octet)
                    {
                        typeofSignatureProvider = typeof(SymmetricSignatureProvider).ToString();
                        createAsymmetric        = false;
                    }
                }
            }
            else if (key is SymmetricSecurityKey symmetricSecurityKey)
            {
                typeofSignatureProvider = typeof(SymmetricSignatureProvider).ToString();
                createAsymmetric        = false;
            }

            if (typeofSignatureProvider == null)
            {
                throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10621, typeof(SymmetricSignatureProvider), typeof(SecurityKey), typeof(AsymmetricSecurityKey), typeof(SymmetricSecurityKey), key.GetType())));
            }

            if (!IsSupportedAlgorithm(algorithm, key))
            {
                throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10634, algorithm, key)));
            }

            if (CacheSignatureProviders)
            {
                if (CryptoProviderCache.TryGetSignatureProvider(key, algorithm, typeofSignatureProvider, willCreateSignatures, out signatureProvider))
                {
                    return(signatureProvider);
                }

                lock (_cacheLock)
                {
                    if (CryptoProviderCache.TryGetSignatureProvider(key, algorithm, typeofSignatureProvider, willCreateSignatures, out signatureProvider))
                    {
                        return(signatureProvider);
                    }

                    if (createAsymmetric)
                    {
                        signatureProvider = new AsymmetricSignatureProvider(key, algorithm, willCreateSignatures, this);
                    }
                    else
                    {
                        signatureProvider = new SymmetricSignatureProvider(key, algorithm, willCreateSignatures);
                    }

                    CryptoProviderCache.TryAdd(signatureProvider);
                }
            }
            else if (createAsymmetric)
            {
                signatureProvider = new AsymmetricSignatureProvider(key, algorithm, willCreateSignatures);
            }
            else
            {
                signatureProvider = new SymmetricSignatureProvider(key, algorithm, willCreateSignatures);
            }

            return(signatureProvider);
        }
Ejemplo n.º 24
0
 internal AsymmetricSignatureProvider(SecurityKey key, string algorithm, CryptoProviderFactory cryptoProviderFactory)
     : this(key, algorithm)
 {
     _cryptoProviderFactory = cryptoProviderFactory;
 }
Ejemplo n.º 25
0
 public TokenBuilder AddSecurityKey(Microsoft.IdentityModel.Tokens.SecurityKey securityKey)
 {
     this.securityKey = securityKey;
     return(this);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AsymmetricSignatureProvider"/> class used to create and verify signatures.
 /// </summary>
 /// <param name="key">The <see cref="SecurityKey"/> that will be used for signature operations.<see cref="SecurityKey"/></param>
 /// <param name="algorithm">The signature algorithm to apply.</param>
 public AsymmetricSignatureProvider(SecurityKey key, string algorithm)
     : this(key, algorithm, false)
 {
 }
        /// <summary>
        /// Checks if an 'algorithm, key' pair is supported.
        /// </summary>
        /// <param name="algorithm">the algorithm to check.</param>
        /// <param name="key">the <see cref="SecurityKey"/>.</param>
        /// <returns>true if 'algorithm, key' pair is supported.</returns>
        public virtual bool IsSupportedAlgorithm(string algorithm, SecurityKey key)
        {
            if (CustomCryptoProvider != null && CustomCryptoProvider.IsSupportedAlgorithm(algorithm, key))
            {
                return(true);
            }

            if (key as RsaSecurityKey != null)
            {
                return(IsRsaAlgorithmSupported(algorithm));
            }

            var x509Key = key as X509SecurityKey;

            if (x509Key != null)
            {
#if NETSTANDARD1_4
                if (x509Key.PublicKey as RSA == null)
                {
                    return(false);
                }
#else
                if (x509Key.PublicKey as RSACryptoServiceProvider == null)
                {
                    return(false);
                }
#endif
                return(IsRsaAlgorithmSupported(algorithm));
            }

            JsonWebKey jsonWebKey = key as JsonWebKey;
            if (jsonWebKey != null)
            {
                if (jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.RSA)
                {
                    return(IsRsaAlgorithmSupported(algorithm));
                }
                else if (jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.EllipticCurve)
                {
                    return(IsEcdsaAlgorithmSupported(algorithm));
                }
                else if (jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.Octet)
                {
                    return(IsSymmetricAlgorithmSupported(algorithm));
                }

                return(false);
            }

            ECDsaSecurityKey ecdsaSecurityKey = key as ECDsaSecurityKey;
            if (ecdsaSecurityKey != null)
            {
                return(IsEcdsaAlgorithmSupported(algorithm));
            }

            if (key as SymmetricSecurityKey != null)
            {
                return(IsSymmetricAlgorithmSupported(algorithm));
            }

            return(false);
        }
        /// <summary>
        /// Creates an instance of <see cref="AuthenticatedEncryptionProvider"/> for a specific &lt;SecurityKey, Algorithm>.
        /// </summary>
        /// <param name="key">the <see cref="SecurityKey"/> to use.</param>
        /// <param name="algorithm">the algorithm to use.</param>
        /// <returns>an instance of <see cref="AuthenticatedEncryptionProvider"/></returns>
        /// <exception cref="ArgumentNullException">'key' is null.</exception>
        /// <exception cref="ArgumentNullException">'algorithm' is null or empty.</exception>
        /// <exception cref="ArgumentException">'key' is not a <see cref="SymmetricSecurityKey"/>.</exception>
        /// <exception cref="ArgumentException">'algorithm, key' pair is not supported.</exception>
        public virtual AuthenticatedEncryptionProvider CreateAuthenticatedEncryptionProvider(SecurityKey key, string algorithm)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

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

            if (CustomCryptoProvider != null && CustomCryptoProvider.IsSupportedAlgorithm(algorithm, key))
            {
                var cryptoProvider = CustomCryptoProvider.Create(algorithm, key) as AuthenticatedEncryptionProvider;
                if (cryptoProvider == null)
                {
                    throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10646, algorithm, key, typeof(AuthenticatedEncryptionProvider))));
                }

                return(cryptoProvider);
            }

            if (IsSupportedAuthenticatedEncryptionAlgorithm(algorithm, key))
            {
                return(new AuthenticatedEncryptionProvider(key, algorithm));
            }

            throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX10652, algorithm), nameof(algorithm)));
        }
        private void ResolveAsymmetricAlgorithm(SecurityKey key, string algorithm, bool willCreateSignatures)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException("key");
            }

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

            _hashAlgorithm = GetHashAlgorithmName(algorithm);
            RsaSecurityKey rsaKey = key as RsaSecurityKey;

            if (rsaKey != null)
            {
                if (rsaKey.Rsa != null)
                {
                    _rsa = rsaKey.Rsa;
                    return;
                }

                _rsa = RSA.Create();
                if (_rsa != null)
                {
                    _rsa.ImportParameters(rsaKey.Parameters);
                    _disposeRsa = true;
                    return;
                }
            }

            X509SecurityKey x509Key = key as X509SecurityKey;

            if (x509Key != null)
            {
                if (willCreateSignatures)
                {
                    RSACryptoServiceProvider rsaCsp = x509Key.PrivateKey as RSACryptoServiceProvider;
                    if (rsaCsp != null)
                    {
                        _rsaCryptoServiceProviderProxy = new RSACryptoServiceProviderProxy(rsaCsp);
                    }
                    else
                    {
                        _rsa = x509Key.PrivateKey as RSA;
                    }
                }
                else
                {
                    _rsa = x509Key.PublicKey as RSA;
                }

                return;
            }

            ECDsaSecurityKey ecdsaKey = key as ECDsaSecurityKey;

            if (ecdsaKey != null)
            {
                if (ecdsaKey.ECDsa != null)
                {
                    _ecdsa = ecdsaKey.ECDsa;
                    return;
                }
            }

            JsonWebKey webKey = key as JsonWebKey;

            if (webKey.Kty == JsonWebAlgorithmsKeyTypes.RSA)
            {
                RSAParameters parameters = CreateRsaParametersFromJsonWebKey(webKey, willCreateSignatures);

                _rsa = RSA.Create();
                if (_rsa != null)
                {
                    _rsa.ImportParameters(parameters);
                    _disposeRsa = true;
                    return;
                }
            }
            else if (webKey.Kty == JsonWebAlgorithmsKeyTypes.EllipticCurve)
            {
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    throw new PlatformNotSupportedException();
                }

                CreateECDsaFromJsonWebKey(webKey, willCreateSignatures);
                return;
            }

            throw LogHelper.LogArgumentException <ArgumentOutOfRangeException>(nameof(key), LogMessages.IDX10641, key);
        }