static bool KeysEqual(SecurityKey k1, SecurityKey k2)
 {
     return
         (k1 != null && k2 != null &&
          k1.GetType() == k2.GetType() &&
          k1 is SymmetricSecurityKey k1s &&
          k2 is SymmetricSecurityKey k2s &&
          HelperTools.AreByteArraysEqual(k1s.Key, k2s.Key));
 }
        protected virtual KeyInfo CreateKeyInfo(SecurityKey key)
        {
            if (key is X509SecurityKey x509)
            {
                if (Options.UseSecurityTokenReference)
                {
                    var publicKey = x509.Certificate.Export(X509ContentType.Cert);
                    using (var sha1 = SHA1.Create())
                    {
                        var hashed = sha1.ComputeHash(publicKey);
                        return(new SecurityTokenReferenceKeyInfo
                        {
                            KeyIdValueType = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1",
                            KeyId = Convert.ToBase64String(hashed)
                        });
                    }
                }

                return(new KeyInfo
                {
                    X509Data =
                    {
                        new X509Data(x509.Certificate)
                    }
                });
            }
            else if (key is RsaSecurityKey rsa)
            {
                var id = Options.GenerateId(rsa);
                return(new KeyInfo {
                    KeyName = id
                });
            }

            throw new NotSupportedException($"Key type '{key.GetType().Name}' not supported.");
        }
Пример #3
0
        private static bool AreSecurityKeysEqual(SecurityKey securityKey1, SecurityKey securityKey2, CompareContext context)
        {
            if (context.IgnoreType && (securityKey1.GetType() != securityKey2.GetType()))
            {
                return(false);
            }

            // Check X509SecurityKey first so we don't have to use reflection to get cert.
            X509SecurityKey x509Key1 = securityKey1 as X509SecurityKey;

            if (x509Key1 != null)
            {
                X509SecurityKey x509Key2 = securityKey2 as X509SecurityKey;
                if (x509Key1.Certificate.Thumbprint == x509Key2.Certificate.Thumbprint)
                {
                    return(true);
                }

                return(false);
            }

            X509AsymmetricSecurityKey x509AsymmKey1 = securityKey1 as X509AsymmetricSecurityKey;

            if (x509AsymmKey1 != null)
            {
                X509AsymmetricSecurityKey x509AsymmKey2 = securityKey2 as X509AsymmetricSecurityKey;
                X509Certificate2          x509Cert1     = TestUtilities.GetField(x509AsymmKey1, "certificate") as X509Certificate2;
                X509Certificate2          x509Cert2     = TestUtilities.GetField(x509AsymmKey2, "certificate") as X509Certificate2;
                if (x509Cert1 == null && x509Cert2 == null)
                {
                    return(true);
                }

                if (x509Cert1 == null || x509Cert2 == null)
                {
                    return(false);
                }

                if (x509Cert1.Thumbprint != x509Cert2.Thumbprint)
                {
                    return(false);
                }
            }

            SymmetricSecurityKey symKey1 = securityKey1 as SymmetricSecurityKey;

            if (symKey1 != null)
            {
                SymmetricSecurityKey symKey2 = securityKey2 as SymmetricSecurityKey;
                if (!AreBytesEqual(symKey1.GetSymmetricKey(), symKey2.GetSymmetricKey()))
                {
                    return(false);
                }
            }

            RsaSecurityKey rsaKey = securityKey1 as RsaSecurityKey;

            if (rsaKey != null)
            {
                RSA rsa1 = (rsaKey.GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false)) as RSA;
                RSA rsa2 = ((securityKey2 as RsaSecurityKey).GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha256Signature, false)) as RSA;

                if (!string.Equals(rsa1.ToXmlString(false), rsa2.ToXmlString(false), StringComparison.Ordinal))
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="KeyVaultKeyWrapProvider"/> class.
        /// </summary>
        /// <param name="key">The <see cref="SecurityKey"/> that will be used for key wrap operations.</param>
        /// <param name="algorithm">The key wrap algorithm to apply.</param>
        /// <param name="client">A mock <see cref="IKeyVaultClient"/> used for testing purposes.</param>
        internal KeyVaultKeyWrapProvider(SecurityKey key, string algorithm, IKeyVaultClient client)
        {
            _algorithm = string.IsNullOrEmpty(algorithm) ? throw LogHelper.LogArgumentNullException(nameof(algorithm)) : algorithm;
            if (key == null)
            {
                throw LogHelper.LogArgumentNullException(nameof(key));
            }

            _key    = key as KeyVaultSecurityKey ?? throw LogHelper.LogExceptionMessage(new NotSupportedException(key.GetType().ToString()));
            _client = client ?? new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(_key.Callback));
        }
        /// <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));
            }
        }
Пример #6
0
 /// <summary>
 /// Gets the X509 certificate.
 /// </summary>
 /// <param name="key">The key.</param>
 /// <param name="store">The store.</param>
 /// <returns></returns>
 /// <exception cref="System.InvalidOperationException">Cannot use signing credential with key of type '{key.GetType().Name}'</exception>
 /// <exception cref="InvalidOperationException">Cannot use signing credential with key of type '{key.GetType().Name}'</exception>
 public static X509Certificate2 GetX509Certificate(this SecurityKey key, ISigningCredentialStore store)
 {
     if (key is RsaSecurityKey rsaKey)
     {
         var rsa         = rsaKey.Rsa ?? RSA.Create(rsaKey.Parameters);
         var certRequest = new CertificateRequest("cn=theidserver", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
         if (store is IKeyRingStores keyRingStore)
         {
             var defaultKey = keyRingStore.DefaultKey;
             return(certRequest.CreateSelfSigned(defaultKey.ActivationDate, defaultKey.ExpirationDate));
         }
         return(certRequest.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1)));
     }
     else if (key is X509SecurityKey x509)
     {
         return(x509.Certificate);
     }
     else
     {
         throw new InvalidOperationException($"Cannot use signing credential with key of type '{key.GetType().Name}'");
     }
 }
Пример #7
0
 internal static string GetHeaderCacheKey(SecurityKey securityKey, string algorithm)
 {
     return(string.Format(CultureInfo.InvariantCulture, "{0}-{1}-{2}", securityKey.GetType(), securityKey.KeyId, algorithm));
 }
 internal static string GetHeaderCacheKey(SecurityKey securityKey, string algorithm)
 {
     return($"{securityKey.GetType()}-{securityKey.KeyId}-{algorithm}");
 }
Пример #9
0
        private static SignatureProvider CreateProvider(SecurityKey key, string algorithm, bool willCreateSignatures)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            if (algorithm == null)
            {
                throw new ArgumentNullException("algorithm");
            }

            if (string.IsNullOrWhiteSpace(algorithm))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10002, "algorithm "));
            }

            AsymmetricSecurityKey asymmetricKey = key as AsymmetricSecurityKey;

            if (asymmetricKey != null)
            {
                if (willCreateSignatures)
                {
                    if (asymmetricKey.KeySize < MinimumAsymmetricKeySizeInBitsForSigning)
                    {
                        throw new ArgumentOutOfRangeException("key.KeySize", asymmetricKey.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10630, key.GetType(), MinimumAsymmetricKeySizeInBitsForSigning));
                    }
                }

                if (asymmetricKey.KeySize < MinimumAsymmetricKeySizeInBitsForVerifying)
                {
                    throw new ArgumentOutOfRangeException("key.KeySize", asymmetricKey.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10631, key.GetType(), MinimumAsymmetricKeySizeInBitsForVerifying));
                }

                return(new AsymmetricSignatureProvider(asymmetricKey, algorithm, willCreateSignatures));
            }

            SymmetricSecurityKey symmetricKey = key as SymmetricSecurityKey;

            if (symmetricKey != null)
            {
                if (symmetricKey.KeySize < MinimumSymmetricKeySizeInBits)
                {
                    throw new ArgumentOutOfRangeException("key.KeySize", key.KeySize, string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10603, key.GetType(), MinimumSymmetricKeySizeInBits));
                }

                return(new SymmetricSignatureProvider(symmetricKey, algorithm));
            }

            throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorMessages.IDX10600, typeof(SignatureProvider).ToString(), typeof(SecurityKey), typeof(AsymmetricSecurityKey), typeof(SymmetricSecurityKey), key.GetType()));
        }