protected IEnumerable <X509Certificate2> ReadKeyDescriptorElements(XmlNodeList keyDescriptorElements) { foreach (XmlElement keyDescriptorElement in keyDescriptorElements) { var keyInfoElement = keyDescriptorElement.SelectSingleNode($"*[local-name()='{Saml2MetadataConstants.Message.KeyInfo}']") as XmlElement; if (keyInfoElement != null) { var keyInfo = new KeyInfo(); keyInfo.LoadXml(keyInfoElement); var keyInfoEnumerator = keyInfo.GetEnumerator(); while (keyInfoEnumerator.MoveNext()) { var keyInfoX509Data = keyInfoEnumerator.Current as KeyInfoX509Data; if (keyInfoX509Data != null) { foreach (var certificate in keyInfoX509Data.Certificates) { if (certificate is X509Certificate2) { yield return(certificate as X509Certificate2); } } } } } } }
/// <summary> /// Enumerate all public keys (with their certificate if available) in keyInfo /// </summary> /// <param name="keyInfo"></param> /// <returns></returns> private IEnumerable <KeyValuePair <AsymmetricAlgorithm, X509Certificate2> > GetPublicKeys(KeyInfo keyInfo) { System.Collections.IEnumerator enumerator = keyInfo.GetEnumerator(); while (enumerator.MoveNext()) { switch (enumerator.Current) { case KeyInfoX509Data keyInfoX509Data: foreach (X509Certificate2 certificate in keyInfoX509Data.Certificates) { AsymmetricAlgorithm asyncAlg = certificate.GetRSAPublicKey() ?? (AsymmetricAlgorithm)certificate.GetECDsaPublicKey(); if (asyncAlg != null) { yield return(new KeyValuePair <AsymmetricAlgorithm, X509Certificate2>(asyncAlg, certificate)); } } break; case RSAKeyValue rsaKeyValue: yield return(new KeyValuePair <AsymmetricAlgorithm, X509Certificate2>(rsaKeyValue.Key, null)); break; case DSAKeyValue dsaKeyValue: yield return(new KeyValuePair <AsymmetricAlgorithm, X509Certificate2>(dsaKeyValue.Key, null)); break; } } }
protected override AsymmetricAlgorithm GetPublicKey() { RSAKeyValue tempRSA; DSAKeyValue tempDSA; KeyInfoX509Data tempCert; if (m_keyInfoEnum == null) { m_keyInfoEnum = KeyInfo.GetEnumerator(); } while (m_keyInfoEnum.MoveNext()) { tempRSA = m_keyInfoEnum.Current as RSAKeyValue; if (tempRSA != null) { return(tempRSA.Key); } tempDSA = m_keyInfoEnum.Current as DSAKeyValue; if (tempDSA != null) { return(tempDSA.Key); } tempCert = m_keyInfoEnum.Current as KeyInfoX509Data; if (tempCert != null) { if (tempCert.Certificates != null) { // The code here doesn't look in all the certificates and doesn't check if they belong // to the same certificate chain, or whether they are valid if (tempCert.Certificates != null) { foreach (X509Certificate x509certificate in tempCert.Certificates) { IntPtr KeyBlob = IntPtr.Zero; uint KeyBlobSize = 0; int result = PublicKeyBlobFromCertificateRawData(x509certificate.GetRawCertData(), x509certificate.GetRawCertData().Length, out KeyBlob, out KeyBlobSize); byte[] blob = new byte[KeyBlobSize]; Marshal.Copy(KeyBlob, blob, 0, (int)KeyBlobSize); UnmanagedArrayFree(KeyBlob); RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters parameters = new RSAParameters(); IntPtr ExponentBlob = IntPtr.Zero, ModulusBlob = IntPtr.Zero; uint PubExponent = 0, ModulusSize = 0; ImportPublicKeyBlob(blob, blob.Length, out PubExponent, out ModulusBlob, out ModulusSize); parameters.Exponent = ConvertIntToByteArray(PubExponent); parameters.Modulus = new byte[ModulusSize]; Marshal.Copy(ModulusBlob, parameters.Modulus, 0, (int)ModulusSize); UnmanagedArrayFree(ModulusBlob); rsa.ImportParameters(parameters); return(rsa); } } } } } return(null); }
// Reads the X.509 certificates contained within an IdP or SP SSO descriptor private static void ReadX509Certificates(RoleDescriptorType roleDescriptor) { foreach (KeyDescriptor keyDescriptor in roleDescriptor.KeyDescriptors) { KeyInfo keyInfo = new KeyInfo(); keyInfo.LoadXml(keyDescriptor.KeyInfo); IEnumerator enumerator = keyInfo.GetEnumerator(typeof(KeyInfoX509Data)); while (enumerator.MoveNext()) { KeyInfoX509Data keyInfoX509Data = (KeyInfoX509Data)enumerator.Current; foreach (X509Certificate2 x509Certificate in keyInfoX509Data.Certificates) { Console.WriteLine("X509 certificate: " + x509Certificate.ToString()); } } foreach (XmlElement xmlElement in keyDescriptor.EncryptionMethods) { Console.WriteLine("Encryption method: " + KeyDescriptor.GetEncryptionMethodAlgorithm(xmlElement)); } } }
private static AsymmetricAlgorithm GetSigningKeyFromKeyInfo(KeyInfo keyInfo) { AsymmetricAlgorithm asymmetricAlgorithm = (AsymmetricAlgorithm)null; IEnumerator enumerator = keyInfo.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current is KeyInfoX509Data) { KeyInfoX509Data current = (KeyInfoX509Data)enumerator.Current; if (current.Certificates.Count != 0) { asymmetricAlgorithm = new X509Certificate2((X509Certificate)current.Certificates[0]).PublicKey.Key; break; } } else { if (enumerator.Current is RSAKeyValue) { asymmetricAlgorithm = (AsymmetricAlgorithm)((RSAKeyValue)enumerator.Current).Key; break; } if (enumerator.Current is DSAKeyValue) { asymmetricAlgorithm = (AsymmetricAlgorithm)((DSAKeyValue)enumerator.Current).Key; break; } } } return(asymmetricAlgorithm); }
private IEnumerable <X509Certificate2> ReadKeyDescriptorElements(XmlNodeList keyDescriptorElements) { foreach (XmlElement keyDescriptorElement in keyDescriptorElements) { var keyInfoElement = keyDescriptorElement.FirstChild as XmlElement; if (keyInfoElement != null) { var keyInfo = new KeyInfo(); keyInfo.LoadXml(keyInfoElement); var keyInfoEnumerator = keyInfo.GetEnumerator(); while (keyInfoEnumerator.MoveNext()) { var keyInfoX509Data = keyInfoEnumerator.Current as KeyInfoX509Data; if (keyInfoX509Data != null) { foreach (var certificate in keyInfoX509Data.Certificates) { if (certificate is X509Certificate2) { yield return(certificate as X509Certificate2); } } } } } } }
public void Constructor() { KeyInfo keyInfo = new KeyInfo(); Assert.Equal(0, keyInfo.Count); Assert.Null(keyInfo.Id); XmlElement xmlElement = keyInfo.GetXml(); Assert.NotNull(xmlElement); Assert.Equal("<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", xmlElement.OuterXml); IEnumerator enumerator = keyInfo.GetEnumerator(); Assert.NotNull(enumerator); Assert.False(enumerator.MoveNext()); }
/// <summary> /// Получает ключ для расшифровки на основе зашифрованных данных (из примеров криптопро) /// </summary> /// <param name="exml"></param> /// <param name="encryptedData"></param> /// <returns>Алгоритм для расшифровки</returns> private SymmetricAlgorithm GetDecryptionKey(EncryptedXml exml, EncryptedData encryptedData) { IEnumerator encryptedKeyEnumerator = encryptedData.KeyInfo.GetEnumerator(); // Проходим по всем KeyInfo while (encryptedKeyEnumerator.MoveNext()) { // Пропускам все что неизвестно. KeyInfoEncryptedKey current = encryptedKeyEnumerator.Current as KeyInfoEncryptedKey; if (current == null) { continue; } // До первого EncryptedKey EncryptedKey encryptedKey = current.EncryptedKey; if (encryptedKey == null) { continue; } KeyInfo keyinfo = encryptedKey.KeyInfo; // Проходим по всем KeyInfo зашифрования ключа. IEnumerator srcKeyEnumerator = keyinfo.GetEnumerator(); while (srcKeyEnumerator.MoveNext()) { // Пропускам все что неизвестно. KeyInfoX509Data keyInfoCert = srcKeyEnumerator.Current as KeyInfoX509Data; if (keyInfoCert == null) { continue; } AsymmetricAlgorithm alg = certOur.PrivateKey; // Приватный ключ, открытый ключ которого мы отправляли при шифровании запроса Gost3410 myKey = alg as Gost3410; // Преобразования if (myKey == null) { continue; } // Получаем и возвращаем ключ для расшифровки return(CPEncryptedXml.DecryptKeyClass(encryptedKey.CipherData.CipherValue, myKey, encryptedData.EncryptionMethod.KeyAlgorithm)); } } return(null); }
private void LoadResponse(string samlResponseXml) { try { XmlDocument samlResponse = new XmlDocument(); samlResponse.PreserveWhitespace = true; samlResponse.LoadXml(samlResponseXml); XmlNamespaceManager namespaceManager = new XmlNamespaceManager(samlResponse.NameTable); namespaceManager.AddNamespace("saml2p", Saml2Namespace.Protocol); namespaceManager.AddNamespace("ds", Saml2Namespace.DigitalSignature); namespaceManager.AddNamespace("saml2", Saml2Namespace.Assertion); XmlNode response = samlResponse.SelectSingleNode("saml2p:Response", namespaceManager); XmlElement responseSignature = (XmlElement)response.SelectSingleNode("ds:Signature", namespaceManager); _SignedResponse = new SignedXml((XmlElement)response); _SignedResponse.LoadXml(responseSignature); KeyInfo responseKeyInfo = _SignedResponse.KeyInfo; IEnumerator responseKeyInfoEnumerator = responseKeyInfo.GetEnumerator(); _ResponseCertificate = new X509Certificate2(); while (responseKeyInfoEnumerator.MoveNext()) { if (responseKeyInfoEnumerator.Current is KeyInfoX509Data) { KeyInfoX509Data x509Data = (KeyInfoX509Data)responseKeyInfoEnumerator.Current; if (x509Data.Certificates.Count >= 1) { X509Certificate certificate = (X509Certificate)x509Data.Certificates[0]; _ResponseCertificate = new X509Certificate2(certificate); } } } XmlNode assertion = response.SelectSingleNode("saml2:Assertion", namespaceManager).Clone(); AssertionXml = assertion.OuterXml; XmlElement assertionSignature = (XmlElement)assertion.SelectSingleNode("ds:Signature", namespaceManager); _SignedAssertion = new SignedXml((XmlElement)assertion); _SignedAssertion.LoadXml(assertionSignature); KeyInfo assertionKeyInfo = _SignedAssertion.KeyInfo; IEnumerator assertionKeyInfoEnumerator = assertionKeyInfo.GetEnumerator(); _AssertionCertificate = new X509Certificate2(); while (assertionKeyInfoEnumerator.MoveNext()) { if (assertionKeyInfoEnumerator.Current is KeyInfoX509Data) { KeyInfoX509Data x509Data = (KeyInfoX509Data)assertionKeyInfoEnumerator.Current; if (x509Data.Certificates.Count >= 1) { X509Certificate certificate = (X509Certificate)x509Data.Certificates[0]; _AssertionCertificate = new X509Certificate2(certificate); } } } XmlNode issuer = response.SelectSingleNode("saml2:Issuer", namespaceManager).Clone(); IssuerName = issuer.InnerText; XmlNode status = response.SelectSingleNode("smal2p:Status", namespaceManager).Clone(); XmlNode statusCode = status.SelectSingleNode("saml2p:StatusCode", namespaceManager); StatusCode = statusCode.Attributes["Value"].Value; } catch (Exception exception) { //TODO: log your exception here } }