public void DeletePrivateKey(AsymmetricAlgorithm a)
        {
            for (Type t = a.GetType(); t != null; t = t.BaseType)
            {
                Action <AsymmetricAlgorithm> deleter;
                if (this.privateKeyDeleters.TryGetValue(t, out deleter))
                {
                    deleter(a);
                    return;
                }
            }

            FiddlerApplication.Log.LogString("No private key deleter found for " + a.GetType());
        }
Example #2
0
        public GostExternalAsymmetricAlgorithm(AsymmetricAlgorithm algorithm) : base(default(ProviderType), algorithm.KeySize)
        {
            var createSignatureMethod = algorithm.GetType().GetMethod(nameof(CreateSignature), new[] { typeof(byte[]) });
            var verifySignatureMethod = algorithm.GetType().GetMethod(nameof(VerifySignature), new[] { typeof(byte[]), typeof(byte[]) });

            if ((createSignatureMethod == null || createSignatureMethod.ReturnType != typeof(byte[])) ||
                (verifySignatureMethod == null || verifySignatureMethod.ReturnType != typeof(bool)))
            {
                throw ExceptionUtility.Argument(nameof(algorithm), Resources.ShouldSupportGost3410);
            }

            _algorithm       = algorithm;
            _createSignature = hash => (byte[])createSignatureMethod.Invoke(algorithm, new object[] { hash });
            _verifySignature = (hash, signature) => (bool)verifySignatureMethod.Invoke(algorithm, new object[] { hash, signature });
        }
Example #3
0
        private static bool CheckSignedInfo(SignedXml signedXml, AsymmetricAlgorithm key)
        {
            //Copied from reflected System.Security.Cryptography.Xml.SignedXml
            SignatureDescription signatureDescription = CryptoConfig.CreateFromName(signedXml.SignatureMethod) as SignatureDescription;

            if (signatureDescription == null)
            {
                throw new CryptographicException(SecurityResources.GetString("Cryptography_Xml_SignatureDescriptionNotCreated"));
            }

            Type type  = Type.GetType(signatureDescription.KeyAlgorithm);
            Type type2 = key.GetType();

            if (type != type2 && !type.IsSubclassOf(type2) && !type2.IsSubclassOf(type))
            {
                return(false);
            }

            HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest();

            if (hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }

            //Except this. The SignedXml class creates and cananicalizes a Signature element without any prefix, rather than using the element from the document provided
            byte[] c14NDigest = GetC14NDigest(signedXml, hashAlgorithm);

            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);

            return(asymmetricSignatureDeformatter.VerifySignature(c14NDigest, signedXml.Signature.SignatureValue));
        }
        /// <summary>CreateSameKeySizeSP</summary>
        /// <param name="aa1">AsymmetricAlgorithm</param>
        /// <returns>AsymmetricAlgorithm(RSA or DSA)</returns>
        public static AsymmetricAlgorithm CreateSameKeySizeSP(AsymmetricAlgorithm aa1)
        {
            AsymmetricAlgorithm aa2 = (AsymmetricAlgorithm)Activator.CreateInstance(aa1.GetType());

            aa2.KeySize = aa1.KeySize;
            return(aa2);
        }
Example #5
0
        public Saml2LogoutResponse GetLogoutReponse(Uri uri, AsymmetricAlgorithm key)
        {
            var response = new Saml2LogoutResponse();
            var parser   = new HttpRedirectBindingParser(uri);

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            response.OriginalLogoutRequest = parser.LogoutRequest;

            if (!parser.IsSigned)
            {
                response.StatusCode = Saml2Constants.StatusCodes.RequestDenied;
            }

            // Validates the signature using the public part of the asymmetric key given as parameter.
            var signatureProvider =
                _signatureProviderFactory.CreateFromAlgorithmUri(key.GetType(), parser.SignatureAlgorithm);

            if (!signatureProvider.VerifySignature(key, Encoding.UTF8.GetBytes(parser.SignedQuery),
                                                   parser.DecodeSignature()))
            {
                response.StatusCode = Saml2Constants.StatusCodes.RequestDenied;
            }

            response.StatusCode = Saml2Constants.StatusCodes.Success;
            return(response);
        }
        private static X509Certificate2 CloneWithPrivateKey(X509Certificate2 cert, AsymmetricAlgorithm key)
        {
            RSA rsa = key as RSA;

            if (rsa != null)
            {
                return(cert.CopyWithPrivateKey(rsa));
            }

            ECDsa ecdsa = key as ECDsa;

            if (ecdsa != null)
            {
                return(cert.CopyWithPrivateKey(ecdsa));
            }

            DSA dsa = key as DSA;

            if (dsa != null)
            {
                return(cert.CopyWithPrivateKey(dsa));
            }

            throw new InvalidOperationException(
                      $"Had no handler for key of type {key?.GetType().FullName ?? "null"}");
        }
        private bool CheckSignedInfo(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            SignedXmlDebugLog.LogBeginCheckSignedInfo(this, this.m_signature.SignedInfo);
            SignatureDescription signatureDescription = CryptoConfig.CreateFromName(this.SignatureMethod) as SignatureDescription;

            if (signatureDescription == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated"));
            }
            Type c    = Type.GetType(signatureDescription.KeyAlgorithm);
            Type type = key.GetType();

            if (((c != type) && !c.IsSubclassOf(type)) && !type.IsSubclassOf(c))
            {
                return(false);
            }
            HashAlgorithm hash = signatureDescription.CreateDigest();

            if (hash == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            byte[] actualHashValue = this.GetC14NDigest(hash);
            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);

            SignedXmlDebugLog.LogVerifySignedInfo(this, key, signatureDescription, hash, asymmetricSignatureDeformatter, actualHashValue, this.m_signature.SignatureValue);
            return(asymmetricSignatureDeformatter.VerifySignature(actualHashValue, this.m_signature.SignatureValue));
        }
Example #8
0
        public string GetLogoutResponseMessage(Uri uri, AsymmetricAlgorithm key)
        {
            var parser = new HttpRedirectBindingParser(uri);

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (!parser.IsSigned)
            {
                throw new InvalidOperationException("Query is not signed, so there is no signature to verify.");
            }

            // Validates the signature using the public part of the asymmetric key given as parameter.
            var signatureProvider =
                _signatureProviderFactory.CreateFromAlgorithmUri(key.GetType(), parser.SignatureAlgorithm);

            if (!signatureProvider.VerifySignature(key, Encoding.UTF8.GetBytes(parser.SignedQuery),
                                                   parser.DecodeSignature()))
            {
                throw new InvalidOperationException("Logout request signature verification failed");
            }

            return(parser.Message);
        }
Example #9
0
        /// <summary>
        /// Create a self-signed certificate using the established subject, key, and optional
        /// extensions.
        /// </summary>
        /// <param name="notBefore">
        ///   The oldest date and time where this certificate is considered valid.
        ///   Typically <see cref="DateTimeOffset.UtcNow"/>, plus or minus a few seconds.
        /// </param>
        /// <param name="notAfter">
        ///   The date and time where this certificate is no longer considered valid.
        /// </param>
        /// <returns>
        ///   An <see cref="X509Certificate2"/> with the specified values. The returned object will
        ///   assert <see cref="X509Certificate2.HasPrivateKey" />.
        /// </returns>
        /// <exception cref="ArgumentException">
        ///   <paramref name="notAfter"/> represents a date and time before <paramref name="notAfter"/>.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        ///   A constructor was used which did not accept a signing key.
        /// </exception>>
        /// <exception cref="CryptographicException">
        ///   Other errors during the certificate creation process.
        /// </exception>
        public X509Certificate2 CreateSelfSigned(DateTimeOffset notBefore, DateTimeOffset notAfter)
        {
            if (notAfter < notBefore)
            {
                throw new ArgumentException(SR.Cryptography_CertReq_DatesReversed);
            }
            if (_key == null)
            {
                throw new InvalidOperationException(SR.Cryptography_CertReq_NoKeyProvided);
            }

            Debug.Assert(_generator != null);

            byte[] serialNumber = new byte[8];
            RandomNumberGenerator.Fill(serialNumber);

            using (X509Certificate2 certificate = Create(
                       SubjectName,
                       _generator,
                       notBefore,
                       notAfter,
                       serialNumber))
            {
                RSA rsa = _key as RSA;

                if (rsa != null)
                {
                    return(certificate.CopyWithPrivateKey(rsa));
                }

                ECDsa ecdsa = _key as ECDsa;

                if (ecdsa != null)
                {
                    return(certificate.CopyWithPrivateKey(ecdsa));
                }

                Gost3410 gost3410 = _key as Gost3410;
                if (gost3410 != null)
                {
                    return(certificate.CopyWithPrivateKey(gost3410));
                }
                Gost3410_2012_256 gost3410_2012_256 = _key as Gost3410_2012_256;
                if (gost3410_2012_256 != null)
                {
                    return(certificate.CopyWithPrivateKey(gost3410_2012_256));
                }
                Gost3410_2012_512 gost3410_2012_512 = _key as Gost3410_2012_512;
                if (gost3410_2012_512 != null)
                {
                    return(certificate.CopyWithPrivateKey(gost3410_2012_512));
                }
            }

            Debug.Fail($"Key was of no known type: {_key?.GetType().FullName ?? "null"}");
            throw new CryptographicException();
        }
Example #10
0
        /// <summary>
        /// Signs an <see cref="XmlDocument"/> with the specified private asymmetric key.
        /// </summary>
        /// <param name="doc">The <see cref="XmlDocument"/>.</param>
        /// <param name="key">The private asymmetric key.</param>
        /// <returns></returns>
        public static XmlDocument SignXmlDocument(XmlDocument doc, AsymmetricAlgorithm key)
        {
            SignedXml signedXml = new SignedXml(doc)
            {
                SigningKey = key
            };

            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            XmlDsigExcC14NTransform canMethod = (XmlDsigExcC14NTransform)signedXml.SignedInfo.CanonicalizationMethodObject;

            canMethod.InclusiveNamespacesPrefixList = "Sign";

            Reference reference = new Reference()
            {
                Uri = string.Empty
            };

            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            signedXml.AddReference(reference);

            KeyInfo keyInfo = new KeyInfo();

            if (key.GetType().BaseType == typeof(RSA))
            {
                keyInfo.AddClause(new RSAKeyValue((RSA)key));
            }
            else if (key.GetType().BaseType == typeof(DSA))
            {
                keyInfo.AddClause(new DSAKeyValue((DSA)key));
            }

            signedXml.KeyInfo = keyInfo;

            signedXml.ComputeSignature();

            doc.DocumentElement.AppendChild(doc.ImportNode(signedXml.GetXml(), true));
            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            return(doc);
        }
Example #11
0
        internal static SafeKeyHandle GetPrivateKey(AsymmetricAlgorithm key)
        {
            if (key is ECDsaImplementation.ECDsaAndroid ecdsa)
            {
                return(ecdsa.DuplicateKeyHandle());
            }

            // TODO: [AndroidCrypto] Handle RSA / DSA
            throw new NotImplementedException($"{nameof(GetPrivateKey)} ({key.GetType()})");
        }
Example #12
0
 public void DeletePrivateKey(AsymmetricAlgorithm asymmetricAlgorithm)
 {
     for (Type type = asymmetricAlgorithm.GetType(); type != null; type = type.BaseType)
     {
         if (privateKeyDeleters.TryGetValue(type, out Action <AsymmetricAlgorithm> deleter))
         {
             deleter(asymmetricAlgorithm);
             return;
         }
     }
 }
Example #13
0
        private static CertificateRequest OpenCertRequest(
            string dn,
            AsymmetricAlgorithm key,
            HashAlgorithmName hashAlgorithm)
        {
            X500DistinguishedName x500dn = new X500DistinguishedName(dn);

            return(key switch {
                RSA rsa => new CertificateRequest(x500dn, rsa, hashAlgorithm, RSASignaturePadding.Pkcs1),
                ECDsa ecdsa => new CertificateRequest(x500dn, ecdsa, hashAlgorithm),
                ECDiffieHellman ecdh => new CertificateRequest(x500dn, new PublicKey(ecdh), hashAlgorithm),
                _ => throw new InvalidOperationException(
                    $"Had no handler for key of type {key?.GetType().FullName ?? "null"}")
            });
Example #14
0
        internal static bool CanProduceSha1Signature(AsymmetricAlgorithm algorithm)
        {
#if NETFRAMEWORK
            algorithm.Dispose();
            return(true);
#else
            // We expect all non-Linux platforms to support SHA1 signatures, currently.
            if (!OperatingSystem.IsLinux())
            {
                return(true);
            }

            switch (algorithm)
            {
            case ECDsa ecdsa:
                try
                {
                    ecdsa.SignData(Array.Empty <byte>(), HashAlgorithmName.SHA1);
                    return(true);
                }
                catch (CryptographicException)
                {
                    return(false);
                }
                finally
                {
                    algorithm.Dispose();
                }

            case RSA rsa:
                try
                {
                    rsa.SignData(Array.Empty <byte>(), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
                    return(true);
                }
                catch (CryptographicException)
                {
                    return(false);
                }
                finally
                {
                    algorithm.Dispose();
                }

            default:
                throw new NotSupportedException($"Algorithm type {algorithm.GetType()} is not supported.");
            }
#endif
        }
Example #15
0
        public JsonWebKey(AsymmetricAlgorithm key, bool exportPrivate)
        {
            if (key is RSA rsaKey)
            {
                SetRsaKey(rsaKey, exportPrivate);
                return;
            }

            if (key is ECDsa ecdsaKey)
            {
                SetEcdsaKey(ecdsaKey, exportPrivate);
                return;
            }

            throw new ArgumentException($"Unsupported key type: {key.GetType()}");
        }
Example #16
0
        public static ECDsa ValidateEcDsaKey(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var ecKey = key as ECDsa;

            if (ecKey == null)
            {
                throw new InvalidOperationException(
                          $"SetKey called with a key of type other than ECDsa: {key.GetType()}");
            }

            return(ecKey);
        }
        public static X509Certificate2 CloneWithPrivateKey(
            this X509Certificate2 cert,
            AsymmetricAlgorithm key)
        {
            if (key is RSA rsa)
            {
                return(cert.CopyWithPrivateKey(rsa));
            }

            if (key is ECDsa ecdsa)
            {
                return(cert.CopyWithPrivateKey(ecdsa));
            }

            throw new InvalidOperationException(
                      $"Had no handler for key of type {key?.GetType().FullName ?? "null"}");
        }
Example #18
0
        private bool CheckSignedInfo(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            SignedXmlDebugLog.LogBeginCheckSignedInfo(this, m_signature.SignedInfo);

            SignatureDescription signatureDescription = CryptoConfig.CreateFromName(SignatureMethod) as SignatureDescription;

            if (signatureDescription == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated"));
            }

            // Let's see if the key corresponds with the SignatureMethod
            Type ta = Type.GetType(signatureDescription.KeyAlgorithm);
            Type tb = key.GetType();

            if ((ta != tb) && !ta.IsSubclassOf(tb) && !tb.IsSubclassOf(ta))
            {
                // Signature method key mismatch
                return(false);
            }

            HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest();

            if (hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            byte[] hashval = GetC14NDigest(hashAlgorithm);

            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);

            SignedXmlDebugLog.LogVerifySignedInfo(this,
                                                  key,
                                                  signatureDescription,
                                                  hashAlgorithm,
                                                  asymmetricSignatureDeformatter,
                                                  hashval,
                                                  m_signature.SignatureValue);
            return(asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue));
        }
        private static CertificateRequest OpenCertRequest(
            string dn,
            AsymmetricAlgorithm key,
            HashAlgorithmName hashAlgorithm)
        {
            if (key is RSA rsa)
            {
                return(new CertificateRequest(dn, rsa, hashAlgorithm, RSASignaturePadding.Pkcs1));
            }

            if (key is ECDsa ecdsa)
            {
                return(new CertificateRequest(dn, ecdsa, hashAlgorithm));
            }

            throw new InvalidOperationException(
                      $"Had no handler for key of type {key?.GetType().FullName ?? "null"}");
        }
Example #20
0
        private static bool VerifyAsym(string plainText, string signature, string ts)
        {
            SHA1 sha1 = SHA1.Create();

            byte[] bsignature = ASCIIEncoding.ASCII.GetBytes(signature);
            byte[] cleartext  = ASCIIEncoding.ASCII.GetBytes(plainText + ts);
            byte[] hash       = sha1.ComputeHash(cleartext);

            object[] arr = new object[3];
            arr[0] = hash;
            arr[1] = CryptoConfig.MapNameToOID("SHA1");
            arr[2] = bsignature;
            bool verify = (bool)asymVerifyProvider.GetType()
                          .GetMethod("VerifyHash")
                          .Invoke(asymVerifyProvider, arr);

            return(verify);
        }
Example #21
0
        internal static SafeKeyHandle GetPrivateKey(AsymmetricAlgorithm key)
        {
            if (key is ECDsaImplementation.ECDsaAndroid ecdsa)
            {
                return(ecdsa.DuplicateKeyHandle());
            }

            if (key is RSAImplementation.RSAAndroid rsa)
            {
                return(rsa.DuplicateKeyHandle());
            }

            if (key is DSAImplementation.DSAAndroid dsa)
            {
                return(dsa.DuplicateKeyHandle());
            }

            throw new NotImplementedException($"{nameof(GetPrivateKey)} ({key.GetType()})");
        }
        public bool Verify(AsymmetricAlgorithm key)
        {
            byte[]            signature     = GetSignature();
            byte[]            data          = ToByteSign();
            HashAlgorithmName hashAlgorithm = GetHashAlgorithmName();

            if (key is RSA rsaKey)
            {
                RSASignaturePadding signaturePadding = GetRSASignaturePadding();
                return(rsaKey.VerifyData(data, signature, hashAlgorithm, signaturePadding));
            }

            if (key is ECDsa ecdsaKey)
            {
                return(ecdsaKey.VerifyData(data, signature, hashAlgorithm));
            }

            throw new ArgumentException($"Unsupported key type: {key.GetType()}");
        }
        private static X509SignatureGenerator OpenGenerator(AsymmetricAlgorithm key)
        {
            RSA rsa = key as RSA;

            if (rsa != null)
            {
                return(X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pkcs1));
            }

            ECDsa ecdsa = key as ECDsa;

            if (ecdsa != null)
            {
                return(X509SignatureGenerator.CreateForECDsa(ecdsa));
            }

            throw new InvalidOperationException(
                      $"Had no handler for key of type {key?.GetType().FullName ?? "null"}");
        }
Example #24
0
        private static string SignAsym(string plainText, long ts)
        {
            if (asymSignProvider == null)
            {
                return(null);
            }
            SHA1 sha1 = SHA1.Create();

            byte[]   cleartext = ASCIIEncoding.ASCII.GetBytes(plainText + ts);
            byte[]   hash      = sha1.ComputeHash(cleartext);
            object[] arr       = new object[2];
            arr[0] = hash;
            arr[1] = CryptoConfig.MapNameToOID("SHA1");
            byte[] sign1 = (byte[])
                           asymSignProvider.GetType().GetMethod("SignHash")
                           .Invoke(asymSignProvider, arr);
            string b64signature = Convert.ToBase64String(sign1);

            return(b64signature);
        }
Example #25
0
        /// <summary>
        ///     If an asymmetric key has been specified, sign the request.
        /// </summary>
        private void AddSignature(StringBuilder result, AsymmetricAlgorithm signingKey,
                                  ShaHashingAlgorithm hashingAlgorithm)
        {
            System.Console.WriteLine("");
            System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => result: " + result);
            System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => signingKey: " + signingKey);
            System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => hashingAlgorithm: " + hashingAlgorithm);
            System.Console.WriteLine("");

            if (signingKey == null)
            {
                return;
            }

            result.Append(string.Format("&{0}=", HttpRedirectBindingConstants.SigAlg));
            //System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => result: " + result);

            var signingProvider =
                _signatureProviderFactory.CreateFromAlgorithmName(signingKey.GetType(), hashingAlgorithm);

            System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => signingProvider: " + signingProvider);

            var urlEncoded = signingProvider.SignatureUri.UrlEncode();

            System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => urlEncoded: " + urlEncoded);

            result.Append(urlEncoded.UpperCaseUrlEncode());
            //System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => result: " + result);

            // Calculate the signature of the URL as described in [SAMLBind] section 3.4.4.1.
            var signature = signingProvider.SignData(signingKey, Encoding.UTF8.GetBytes(result.ToString()));

            System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => signature: " + signature);

            result.AppendFormat("&{0}=", HttpRedirectBindingConstants.Signature);
            result.Append(HttpUtility.UrlEncode(Convert.ToBase64String(signature)));

            System.Console.WriteLine("");
            System.Console.WriteLine("[HttpRedirectBinding][AddSignature] => result: " + result);
            System.Console.WriteLine("");
        }
Example #26
0
        private static bool IsKeyTheCorrectAlgorithm(AsymmetricAlgorithm key, Type expectedType)
        {
            Type actualType = key.GetType();

            if (actualType == expectedType)
            {
                return(true);
            }

            // This check exists solely for compatibility with 4.6. Normally, we would expect "expectedType" to be the superclass type and
            // the actualType to be the subclass.
            if (expectedType.IsSubclassOf(actualType))
            {
                return(true);
            }

            //
            // "expectedType" comes from the KeyAlgorithm property of a SignatureDescription. The BCL SignatureDescription classes have historically
            // denoted provider-specific implementations ("RSACryptoServiceProvider") rather than the base class for the algorithm ("RSA"). We could
            // change those (at the risk of creating other compat problems) but we have no control over third party SignatureDescriptions.
            //
            // So, in the absence of a better approach, walk up the parent hierarchy until we find the ancestor that's a direct subclass of
            // AsymmetricAlgorithm and treat that as the algorithm identifier.
            //
            while (expectedType != null && expectedType.BaseType != typeof(AsymmetricAlgorithm))
            {
                expectedType = expectedType.BaseType;
            }

            if (expectedType == null)
            {
                return(false);   // SignatureDescription specified something that isn't even a subclass of AsymmetricAlgorithm. For compatibility with 4.6, return false rather throw.
            }
            if (actualType.IsSubclassOf(expectedType))
            {
                return(true);
            }

            return(false);
        }
Example #27
0
        private static CertificateRequest OpenCertRequest(
            string dn,
            AsymmetricAlgorithm key,
            HashAlgorithmName hashAlgorithm)
        {
            RSA rsa = key as RSA;

            if (rsa != null)
            {
                return(new CertificateRequest(dn, rsa, hashAlgorithm));
            }

            ECDsa ecdsa = key as ECDsa;

            if (ecdsa != null)
            {
                return(new CertificateRequest(dn, ecdsa, hashAlgorithm));
            }

            throw new InvalidOperationException(
                      $"Had no handler for key of type {key?.GetType().FullName ?? "null"}");
        }
Example #28
0
        public byte[] Collect()
        {
            var rsaKey = privateKey as RSA;

            if (rsaKey != null)
            {
#if NET452
                var rsaProviderKey = rsaKey  as RSACryptoServiceProvider;
                return(rsaProviderKey.SignHash(hashAlgorithm.Hash, hashOid.Value));
#else
                HashAlgorithmName han;
                switch (hashOid.FriendlyName)
                {
                case "SHA256":
                    han = HashAlgorithmName.SHA256;
                    break;

                case "SHA512":
                    han = HashAlgorithmName.SHA512;
                    break;

                default:
                    throw new InvalidOperationException("Hash algorithm not supported :" + hashOid.FriendlyName);
                }
                return(rsaKey.SignHash(hashAlgorithm.Hash, han, RSASignaturePadding.Pkcs1));
#endif
            }

            var dsaKey = privateKey as DSA;
            if (dsaKey != null)
            {
                return(dsaKey.CreateSignature(hashAlgorithm.Hash));
            }

            throw new InvalidOperationException("Unsuported key type: " + privateKey.GetType());
        }
        public void Sign(AsymmetricAlgorithm key)
        {
            byte[]            data          = ToByteSign();
            HashAlgorithmName hashAlgorithm = GetHashAlgorithmName();

            if (key is RSA rsaKey)
            {
                RSASignaturePadding signaturePadding = GetRSASignaturePadding();
                byte[] signedData = rsaKey.SignData(data, hashAlgorithm, signaturePadding);

                Signature = Base64Url.Encode(signedData);
                return;
            }

            if (key is ECDsa ecdsaKey)
            {
                byte[] signedData = ecdsaKey.SignData(data, hashAlgorithm);

                Signature = Base64Url.Encode(signedData);
                return;
            }

            throw new ArgumentException($"Unsupported key type: {key.GetType()}");
        }
Example #30
0
        /// <summary>
        /// Convert an AsymmetricAlgorithm into a BouncyCastle AsymmetricCipherKeyPair.
        /// </summary>
        /// <remarks>
        /// <para>Converts an AsymmetricAlgorithm into a BouncyCastle AsymmetricCipherKeyPair.</para>
        /// <note type="note">Currently, only RSA and DSA keys are supported.</note>
        /// </remarks>
        /// <returns>The Bouncy Castle AsymmetricCipherKeyPair.</returns>
        /// <param name="key">The key.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="key"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// <paramref name="key"/> is a public key.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// <paramref name="key"/> is an unsupported asymmetric algorithm.
        /// </exception>
        public static AsymmetricCipherKeyPair AsAsymmetricCipherKeyPair(this AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

#if NET46 || NET47 || NET48
            if (key is RSACng rsaCng)
            {
                return(GetAsymmetricCipherKeyPair(rsaCng));
            }
#endif

#if NET47 || NET48
            if (key is DSACng dsaCng)
            {
                return(GetAsymmetricCipherKeyPair(dsaCng));
            }
#endif

            if (key is RSACryptoServiceProvider rsaKey)
            {
                return(GetAsymmetricCipherKeyPair(rsaKey));
            }

            if (key is DSACryptoServiceProvider dsaKey)
            {
                return(GetAsymmetricCipherKeyPair(dsaKey));
            }

            // TODO: support ECDiffieHellman and ECDsa?

            throw new NotSupportedException(string.Format("'{0}' is currently not supported.", key.GetType().Name));
        }