本文整理汇总了C#中System.Security.Cryptography.Xml.KeyInfo类的典型用法代码示例。如果您正苦于以下问题:C# KeyInfo类的具体用法?C# KeyInfo怎么用?C# KeyInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
KeyInfo类属于System.Security.Cryptography.Xml命名空间,在下文中一共展示了KeyInfo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: EncodeCMS
public override object EncodeCMS(X509Certificate2 certificate, string xmlFilePath)
{
XmlDocument Document = new XmlDocument();
Document.PreserveWhitespace = true;
XmlTextReader XmlFile = new XmlTextReader(xmlFilePath);
Document.Load(XmlFile);
XmlFile.Close();
XmlNodeList SignaturesList = Document.GetElementsByTagName("Signature");
// Remove existing signatures, this is not a countersigning.
for (int i = 0; i < SignaturesList.Count; i++)
{
SignaturesList[i].ParentNode.RemoveChild(SignaturesList[i]);
i--;
}
SignedXml SignedXml = new SignedXml(Document);
SignedXml.SigningKey = certificate.PrivateKey;
Reference Reference = new Reference();
Reference.Uri = "";
XmlDsigEnvelopedSignatureTransform EnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
Reference.AddTransform(EnvelopedSignatureTransform);
SignedXml.AddReference(Reference);
KeyInfo Key = new KeyInfo();
Key.AddClause(new KeyInfoX509Data(certificate));
SignedXml.KeyInfo = Key;
SignedXml.ComputeSignature();
// Get the XML representation of the signature and save
// it to an XmlElement object.
XmlElement XmlDigitalSignature = SignedXml.GetXml();
return XmlDigitalSignature;
}
示例2: SignedXmlHelper
static SignedXmlHelper()
{
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(TestCert));
KeyInfoXml = keyInfo.GetXml().OuterXml;
}
示例3: SignRequestXml
/// <summary>
/// Adds a digital signature to the outgoing request message, before sending it to Acquirer.
/// </summary>
/// <param name="requestXml">
/// The unsigned request XML message.
/// </param>
/// <returns>
/// The request message, including digital signature.
/// </returns>
public string SignRequestXml(XDocument requestXml)
{
XmlDocument document = ToXmlDocument(requestXml);
RSACryptoServiceProvider key = ExtractPrivateKeyFrom(acceptantPrivateCertificate);
var signedXml = new SignedXml(document) { SigningKey = key };
signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
// Add a signing reference, the uri is empty and so the whole document is signed.
var reference = new Reference { DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256" };
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
reference.Uri = "";
signedXml.AddReference(reference);
// Add the certificate as key info. Because of this, the certificate
// with the public key will be added in the signature part.
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoName(acceptantPrivateCertificate.Thumbprint));
signedXml.KeyInfo = keyInfo;
// Generate the signature.
signedXml.ComputeSignature();
XmlElement xmlSignature = signedXml.GetXml();
document.DocumentElement.AppendChild(document.ImportNode(xmlSignature, true));
// Check that outgoing signature is valid. Private certificate also contains public part.
VerifyDocumentSignature(document, acceptantPrivateCertificate);
return GetContentsFrom(document);
}
示例4: Sign
public static string Sign(string xml, X509Certificate2 certificate)
{
if (xml == null) throw new ArgumentNullException("xml");
if (certificate == null) throw new ArgumentNullException("certificate");
if (!certificate.HasPrivateKey) throw new ArgumentException("certificate", "Certificate should have a private key");
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(xml);
SignedXml signedXml = new SignedXml(doc);
signedXml.SigningKey = certificate.PrivateKey;
// Attach certificate KeyInfo
KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(keyInfoData);
signedXml.KeyInfo = keyInfo;
// Attach transforms
var reference = new Reference("");
reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false));
reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false));
signedXml.AddReference(reference);
// Compute signature
signedXml.ComputeSignature();
var signatureElement = signedXml.GetXml();
// Add signature to bundle
doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true));
return doc.OuterXml;
}
示例5: SignXmlDocument
private static XmlDocument SignXmlDocument(XmlDocument xmlDocument, X509Certificate2 signingCertificate)
{
// Создание подписчика XML-документа
var signedXml = new GostSignedXml(xmlDocument);
// Установка ключа для создания подписи
signedXml.SetSigningCertificate(signingCertificate);
// Ссылка на узел, который нужно подписать, с указанием алгоритма хэширования
var dataReference = new Reference { Uri = "#Id1", DigestMethod = GostSignedXml.XmlDsigGost3411Url };
// Установка ссылки на узел
signedXml.AddReference(dataReference);
// Установка информации о сертификате, который использовался для создания подписи
var keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(signingCertificate));
signedXml.KeyInfo = keyInfo;
// Вычисление подписи
signedXml.ComputeSignature();
// Получение XML-представления подписи
var signatureXml = signedXml.GetXml();
// Добавление подписи в исходный документ
xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signatureXml, true));
return xmlDocument;
}
示例6: CreateKeyDescriptors
/// <summary>
/// Creates the necessary key descriptors for the metadata based on the certificate in the IDPConfig class.
/// </summary>
/// <returns></returns>
private static KeyDescriptor[] CreateKeyDescriptors()
{
List<KeyDescriptor> keys = new List<KeyDescriptor>();
// Pack the certificate.
KeyInfo keyinfo = new KeyInfo();
KeyInfoX509Data keyClause = new KeyInfoX509Data(IDPConfig.IDPCertificate, X509IncludeOption.EndCertOnly);
keyinfo.AddClause(keyClause);
{ // Create signing key element.
KeyDescriptor key = new KeyDescriptor();
keys.Add(key);
key.use = KeyTypes.signing;
key.useSpecified = true;
key.KeyInfo = Serialization.DeserializeFromXmlString<dk.nita.saml20.Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml);
}
{ // Create encryption key element
KeyDescriptor key = new KeyDescriptor();
keys.Add(key);
key.use = KeyTypes.encryption;
key.useSpecified = true;
key.KeyInfo = Serialization.DeserializeFromXmlString<dk.nita.saml20.Schema.XmlDSig.KeyInfo>(keyinfo.GetXml().OuterXml);
}
return keys.ToArray();
}
示例7: SignXml
private static XmlDocument SignXml()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load(".\\certificates\\samlRequestTemplate.xml");
X509Certificate2 certificate = CertificateHelper.GetCertificate(".\\certificates\\HuaweiCA.p12", "Pr0d1234");
//AsymmetricAlgorithm key = certificate.PrivateKey;
AsymmetricAlgorithm key = certificate.PrivateKey;
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
ns.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
XmlElement issuerNode = (XmlElement)xmlDoc.DocumentElement.SelectSingleNode("saml:Issuer", ns);
SignedXml signedXml = new SignedXml(xmlDoc.DocumentElement);
signedXml.SigningKey = key;
signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
KeyInfo keyInfo = new KeyInfo();
//XmlDocument keyDoc = new XmlDocument();
//keyDoc.LoadXml(certificate.PublicKey.Key.ToXmlString(false));
//keyInfo.LoadXml(keyDoc.DocumentElement);
keyInfo.AddClause(new KeyInfoX509Data(certificate));
signedXml.KeyInfo = keyInfo;
string refId = xmlDoc.DocumentElement.GetAttribute("ID");
Reference reference = new Reference();
reference.Uri = "#" + refId;
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
XmlDsigExcC14NTransform env2 = new XmlDsigExcC14NTransform();
env2.InclusiveNamespacesPrefixList = "#default code ds kind rw saml samlp typens";
reference.AddTransform(env2);
signedXml.AddReference(reference);
signedXml.ComputeSignature();
XmlElement xmlDigitalSignature = signedXml.GetXml();
xmlDoc.DocumentElement.InsertAfter(xmlDoc.ImportNode(xmlDigitalSignature, true), issuerNode);
//xmlDoc.NameTable.Add("samlp");
//XmlElement nameIDPolicyElem = xmlDoc.CreateElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol");
//nameIDPolicyElem.SetAttribute("AllowCreate", "False");
//xmlDoc.DocumentElement.AppendChild(nameIDPolicyElem);
xmlDoc.Save("samleRequestCSharp.xml");
return xmlDoc;
}
示例8: GetKeyInfoFromCertificate
/// <summary>
/// Obtiene la información de la firma asociada al certificado digital
/// </summary>
private KeyInfo GetKeyInfoFromCertificate(X509Certificate2 objCertificate)
{ KeyInfo objKeyInfo = new KeyInfo();
// Añade la cláusula con el certificado
objKeyInfo.AddClause(new KeyInfoX509Data(objCertificate));
// Devuelve la información
return objKeyInfo;
}
示例9: DecryptAssertion
/// <summary>
/// An example on how to decrypt an encrypted assertion.
/// </summary>
/// <param name="file">The file.</param>
public static void DecryptAssertion(string file)
{
var doc = new XmlDocument();
doc.Load(file);
var encryptedDataElement = GetElement(Schema.XEnc.EncryptedData.ElementName, Saml20Constants.Xenc, doc);
var encryptedData = new EncryptedData();
encryptedData.LoadXml(encryptedDataElement);
var nodelist = doc.GetElementsByTagName(Schema.XmlDSig.KeyInfo.ElementName, Saml20Constants.Xmldsig);
Assert.That(nodelist.Count > 0);
var key = new KeyInfo();
key.LoadXml((XmlElement)nodelist[0]);
// Review: Is it possible to figure out which certificate to load based on the Token?
/*
* Comment:
* It would be possible to provide a key/certificate identifier in the EncryptedKey element, which contains the "recipient" attribute.
* The implementation (Safewhere.Tokens.Saml20.Saml20EncryptedAssertion) currently just expects an appropriate asymmetric key to be provided,
* and is not not concerned about its origin.
* If the need arises, we can easily extend the Saml20EncryptedAssertion class with a property that allows extraction key info, eg. the "recipient"
* attribute.
*/
var cert = new X509Certificate2(@"Certificates\sts_dev_certificate.pfx", "test1234");
// ms-help://MS.MSDNQTR.v80.en/MS.MSDN.v80/MS.NETDEVFX.v20.en/CPref18/html/T_System_Security_Cryptography_Xml_KeyInfoClause_DerivedTypes.htm
// Look through the list of KeyInfo elements to find the encrypted key.
SymmetricAlgorithm symmetricKey = null;
foreach (KeyInfoClause keyInfoClause in key)
{
if (keyInfoClause is KeyInfoEncryptedKey)
{
var keyInfoEncryptedKey = (KeyInfoEncryptedKey)keyInfoClause;
var encryptedKey = keyInfoEncryptedKey.EncryptedKey;
symmetricKey = new RijndaelManaged
{
Key = EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)cert.PrivateKey, false)
};
}
}
// Explode if we didn't manage to find a viable key.
Assert.IsNotNull(symmetricKey);
var encryptedXml = new EncryptedXml();
var plaintext = encryptedXml.DecryptData(encryptedData, symmetricKey);
var assertion = new XmlDocument();
assertion.Load(new StringReader(System.Text.Encoding.UTF8.GetString(plaintext)));
// A very simple test to ensure that there is indeed an assertion in the plaintext.
Assert.AreEqual(Assertion.ElementName, assertion.DocumentElement.LocalName);
Assert.AreEqual(Saml20Constants.Assertion, assertion.DocumentElement.NamespaceURI);
// At this point, assertion will contain a decrypted assertion.
}
示例10: assinaturaXmlEnviar
public XmlDocument assinaturaXmlEnviar(XmlDocument _xml)
{
XmlDocument xmlDocAss = _xml;
try
{
if (cert == null)
throw new Exception("Nao foi encontrado o certificado: " + config.configNFCe.NomeCertificadoDigital);
Reference reference = new Reference();
SignedXml docXML = new SignedXml(xmlDocAss);
docXML.SigningKey = cert.PrivateKey;
XmlAttributeCollection uri = xmlDocAss.GetElementsByTagName("infNFe").Item(0).Attributes;
foreach (XmlAttribute atributo in uri)
{
if (atributo.Name == "Id")
reference.Uri = "#" + atributo.InnerText;
}
XmlDsigEnvelopedSignatureTransform envelopedSigntature = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(envelopedSigntature);
XmlDsigC14NTransform c14Transform = new XmlDsigC14NTransform();
reference.AddTransform(c14Transform);
docXML.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(new KeyInfoX509Data(cert));
docXML.KeyInfo = keyInfo;
docXML.ComputeSignature();
XmlElement xmlDigitalSignature = docXML.GetXml();
foreach (var _nfe in xmlDocAss.GetElementsByTagName("NFe").Cast<XmlElement>())
_nfe.AppendChild(xmlDocAss.ImportNode(xmlDigitalSignature, true));
xmlDocAss.PreserveWhitespace = true;
return xmlDocAss;
}
catch (Exception e)
{
Utils.Logger.getInstance.error(e);
return null;
throw new Exception(e.ToString());
}
}
示例11: EncryptedType
protected EncryptedType ()
{
cipherData = new CipherData ();
encoding = null;
encryptionMethod = null;
encryptionProperties = new EncryptionPropertyCollection ();
id = null;
keyInfo = new KeyInfo ();
mimeType = null;
type = null;
}
示例12: CreateKeyInfoFromCertificate
/// <summary>
/// Creates a KeyInfo object based on information from specified certificate
/// </summary>
/// <param name="certificate">The certificate used to create the KeyInfo from</param>
/// <returns>KeyInfo object</returns>
private static KeyInfo CreateKeyInfoFromCertificate(X509Certificate2 certificate)
{
// create KeyInfoX509Data object & include certificate subject
KeyInfoX509Data kiData = new KeyInfoX509Data(certificate);
kiData.AddSubjectName(certificate.Subject);
// create KeyInfo object with specified KeyInfoX509Data
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(kiData);
return keyInfo;
}
示例13: CreateMetadataDocument
private void CreateMetadataDocument(HttpContext context, bool sign)
{
SAML20FederationConfig configuration = ConfigurationReader.GetConfig<SAML20FederationConfig>();
KeyInfo keyinfo = new KeyInfo();
KeyInfoX509Data keyClause = new KeyInfoX509Data(ConfigurationReader.GetConfig<FederationConfig>().SigningCertificate.GetCertificate(), X509IncludeOption.EndCertOnly);
keyinfo.AddClause(keyClause);
Saml20MetadataDocument doc = new Saml20MetadataDocument(configuration, keyinfo, sign);
context.Response.Write(doc.ToXml( context.Response.ContentEncoding ));
}
示例14: SignXml
public string SignXml(XDocument xml)
{
using (MemoryStream streamIn = new MemoryStream())
{
xml.Save(streamIn);
streamIn.Position = 0;
// var rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey; // Create rsa crypto provider from private key contained in certificate, weirdest cast ever!;
// string sCertFileLocation = @"C:\plugins\idealtest\bin\Debug\certficate.pfx";
// X509Certificate2 certificate = new X509Certificate2(sCertFileLocation, "[email protected]");
RSA rsaKey = (RSACryptoServiceProvider)_privateCertificate.PrivateKey;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load(streamIn);
SignedXml signedXml = new SignedXml(xmlDoc);
signedXml.SigningKey = rsaKey;
Reference reference = new Reference();
reference.Uri = "";
XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
reference.AddTransform(env);
signedXml.AddReference(reference);
KeyInfo keyInfo = new KeyInfo();
KeyInfoName kin = new KeyInfoName();
kin.Value = _privateCertificate.Thumbprint;
keyInfo.AddClause(kin);
signedXml.KeyInfo = keyInfo;
signedXml.ComputeSignature();
XmlElement xmlDigitalSignature = signedXml.GetXml();
xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
using (MemoryStream sout = new MemoryStream())
{
xmlDoc.Save(sout);
sout.Position = 0;
using (StreamReader reader = new StreamReader(sout))
{
string xmlOut = reader.ReadToEnd();
return xmlOut;
}
}
}
}
示例15: getKeyInfo
private KeyInfo getKeyInfo()
{
X509Extension extension = this.settings.Certificate.Extensions[1];
AsnEncodedData asndata = new AsnEncodedData(extension.Oid, extension.RawData);
KeyInfoX509Data keyInfoData = new KeyInfoX509Data();
keyInfoData.AddIssuerSerial(this.settings.Certificate.Issuer, this.settings.Certificate.SerialNumber);
keyInfoData.AddSubjectName(this.settings.Certificate.SubjectName.Name);
KeyInfo keyInfo = new KeyInfo();
keyInfo.AddClause(keyInfoData);
return keyInfo;
}