private static string GetCacheKeyPrivate(SecurityKey securityKey, string algorithm, string typeofProvider)
 {
     return(string.Format(CultureInfo.InvariantCulture,
                          "{0}-{1}-{2}-{3}",
                          securityKey.GetType(),
                          securityKey.InternalId,
                          algorithm,
                          typeofProvider));
 }
 /// <summary>
 /// Convert security key into json web key.
 /// </summary>
 /// <param name="key">Security Key</param>
 /// <returns>json web key</returns>
 public static JsonWebKey ConvertFromSecurityKey(SecurityKey key)
 {
     if (key.GetType() == typeof(RsaSecurityKey))
     {
         return(ConvertFromRSASecurityKey(key as RsaSecurityKey));
     }
     else if (key.GetType() == typeof(SymmetricSecurityKey))
     {
         return(ConvertFromSymmetricSecurityKey(key as SymmetricSecurityKey));
     }
     else if (key.GetType() == typeof(X509SecurityKey))
     {
         return(ConvertFromX509SecurityKey(key as X509SecurityKey));
     }
     else
     {
         throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10674, key.GetType().FullName)));
     }
 }
Exemplo n.º 3
0
 private string GetCacheKeyPrivate(SecurityKey securityKey, string algorithm, string typeofProvider)
 {
     return($"{securityKey.GetType()}-{securityKey.KeyId}-{algorithm}-{typeofProvider}");
 }
Exemplo n.º 4
0
        /// <summary>
        /// Converts a <see cref="SecurityKey"/> into a <see cref="JsonWebKey"/>
        /// </summary>
        /// <param name="key">a <see cref="SecurityKey"/> to convert.</param>
        /// <returns>a <see cref="JsonWebKey"/></returns>
        /// <exception cref="ArgumentNullException">if <paramref name="key"/>is null.</exception>
        /// <exception cref="NotSupportedException">if <paramref name="key"/>is not a supported type.</exception>
        /// <remarks>Supports: <see cref="RsaSecurityKey"/>, <see cref="X509SecurityKey"/> and <see cref=" SymmetricSecurityKey"/>.</remarks>
        public static JsonWebKey ConvertFromSecurityKey(SecurityKey key)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

            if (key is RsaSecurityKey rsaKey)
            {
                return(ConvertFromRSASecurityKey(rsaKey));
            }
            else if (key is SymmetricSecurityKey symmetricKey)
            {
                return(ConvertFromSymmetricSecurityKey(symmetricKey));
            }
            else if (key is X509SecurityKey x509Key)
            {
                return(ConvertFromX509SecurityKey(x509Key));
            }
            else
            {
                throw LogHelper.LogExceptionMessage(new NotSupportedException(LogHelper.FormatInvariant(LogMessages.IDX10674, key.GetType().FullName)));
            }
        }
        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(String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10646, algorithm, key, typeof(SignatureProvider))));
                }

                return(signatureProvider);
            }

            if (!IsSupportedAlgorithm(algorithm, key))
            {
                throw LogHelper.LogExceptionMessage(new ArgumentException(String.Format(CultureInfo.InvariantCulture, 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));
                    }
                }
            }

            // TODO improve this message. Nothing about JsonWebKey is mentioned.
            throw LogHelper.LogExceptionMessage(new ArgumentException(String.Format(CultureInfo.InvariantCulture, LogMessages.IDX10600, typeof(SignatureProvider), typeof(SecurityKey), typeof(AsymmetricSecurityKey), typeof(SymmetricSecurityKey), key.GetType())));
        }
Exemplo n.º 6
0
        private SignatureProvider CreateProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

            if (string.IsNullOrWhiteSpace(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.LogException <InvalidOperationException>(LogMessages.IDX10646, key, algorithm, typeof(SignatureProvider));
                }

                return(signatureProvider);
            }

            if (!IsSupportedAlgorithm(algorithm, key))
            {
                throw LogHelper.LogException <ArgumentException>(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.LogException <ArgumentException>(LogMessages.IDX10600, typeof(SignatureProvider), typeof(SecurityKey), typeof(AsymmetricSecurityKey), typeof(SymmetricSecurityKey), key.GetType());
        }
        /// <summary>
        /// Returns the <see cref="SymmetricAlgorithm"/>.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentException">The <see cref="SecurityKey"/> cannot be converted to byte array</exception>
        /// <exception cref="ArgumentOutOfRangeException">The keysize doesn't match the algorithm.</exception>
        /// <exception cref="InvalidOperationException">Failed to create symmetric algorithm with provided key and algorithm.</exception>
        protected virtual SymmetricAlgorithm GetSymmetricAlgorithm(SecurityKey key, string algorithm)
        {
            byte[] keyBytes = null;

            SymmetricSecurityKey symmetricSecurityKey = key as SymmetricSecurityKey;

            if (symmetricSecurityKey != null)
            {
                keyBytes = symmetricSecurityKey.Key;
            }
            else
            {
                JsonWebKey jsonWebKey = key as JsonWebKey;
                if (jsonWebKey != null && jsonWebKey.K != null && jsonWebKey.Kty == JsonWebAlgorithmsKeyTypes.Octet)
                {
                    keyBytes = Base64UrlEncoder.DecodeBytes(jsonWebKey.K);
                }
            }

            if (keyBytes == null)
            {
                throw LogHelper.LogExceptionMessage(new ArgumentException(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10657, key.GetType())));
            }

            ValidateKeySize(keyBytes, algorithm);

            try
            {
                // Create the AES provider
                SymmetricAlgorithm symmetricAlgorithm = Aes.Create();
                symmetricAlgorithm.Mode    = CipherMode.ECB;
                symmetricAlgorithm.Padding = PaddingMode.None;
                symmetricAlgorithm.KeySize = keyBytes.Length * 8;
                symmetricAlgorithm.Key     = keyBytes;

                // Set the AES IV to Zeroes
                var aesIv = new byte[symmetricAlgorithm.BlockSize >> 3];
                Utility.Zero(aesIv);
                symmetricAlgorithm.IV = aesIv;

                return(symmetricAlgorithm);
            }
            catch (Exception ex)
            {
                throw LogHelper.LogExceptionMessage(new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10663, key, algorithm), ex));
            }
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
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);
        }
        /// <summary>
        /// Returns the <see cref="SymmetricAlgorithm"/>.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentException">The <see cref="SecurityKey"/> cannot be converted to byte array</exception>
        /// <exception cref="ArgumentOutOfRangeException">The keysize doesn't match the algorithm.</exception>
        /// <exception cref="InvalidOperationException">Failed to create symmetric algorithm with provided key and algorithm.</exception>
        protected virtual SymmetricAlgorithm GetSymmetricAlgorithm(SecurityKey key, string algorithm)
        {
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

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

            byte[] keyBytes = null;

            if (key is SymmetricSecurityKey symmetricSecurityKey)
            {
                keyBytes = symmetricSecurityKey.Key;
            }
            else if (key is JsonWebKey jsonWebKey)
            {
                if (JsonWebKeyConverter.TryConvertToSymmetricSecurityKey(jsonWebKey, out SecurityKey securityKey))
                {
                    keyBytes = (securityKey as SymmetricSecurityKey).Key;
                }
            }

            if (keyBytes == null)
            {
                throw LogHelper.LogExceptionMessage(new ArgumentException(LogHelper.FormatInvariant(LogMessages.IDX10657, key.GetType())));
            }

            ValidateKeySize(keyBytes, algorithm);

            try
            {
                // Create the AES provider
                SymmetricAlgorithm symmetricAlgorithm = Aes.Create();
                symmetricAlgorithm.Mode    = CipherMode.ECB;
                symmetricAlgorithm.Padding = PaddingMode.None;
                symmetricAlgorithm.KeySize = keyBytes.Length * 8;
                symmetricAlgorithm.Key     = keyBytes;

                // Set the AES IV to Zeroes
                var aesIv = new byte[symmetricAlgorithm.BlockSize >> 3];
                Utility.Zero(aesIv);
                symmetricAlgorithm.IV = aesIv;

                return(symmetricAlgorithm);
            }
            catch (Exception ex)
            {
                throw LogHelper.LogExceptionMessage(new InvalidOperationException(LogHelper.FormatInvariant(LogMessages.IDX10663, key, algorithm), ex));
            }
        }