virtual protected void SignWithKeyInfo(String src, String dest, ICipherParameters pk, AsymmetricAlgorithm publicKey, String digestAlgorithm) { // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileStream os = new FileStream(dest, FileMode.Create); PdfStamper stamper = PdfStamper.createXmlSignature(reader, os); // Creating the appearance XmlSignatureAppearance appearance = stamper.XmlSignatureAppearance; //Set XfaXmlLocator to control getting and setting Document appearance.SetXmlLocator(new XfaXmlLocator(stamper)); // Creating the signature IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm); KeyInfoClause keyInfo; if (publicKey is DSA) { keyInfo = new DSAKeyValue((DSA)publicKey); } else if (publicKey is RSA) { keyInfo = new RSAKeyValue((RSA)publicKey); } else { throw new ArgumentException("Invalid public key algorithm", "publicKey"); } MakeXmlSignature.SignXmlDSig(appearance, pks, keyInfo); }
/// <summary> /// Attempts to read the <see cref="XmlSignatureConstants.Elements.RSAKeyValue"/> element conforming to https://www.w3.org/TR/2001/PR-xmldsig-core-20010820/#sec-RSAKeyValue. /// </summary> /// <param name="reader">A <see cref="XmlReader"/> positioned on a <see cref="XmlSignatureConstants.Elements.RSAKeyValue"/> element.</param> /// <param name="value">The parsed <see cref="XmlSignatureConstants.Elements.RSAKeyValue"/> element.</param> protected virtual bool TryReadRSAKeyValue(XmlReader reader, out RSAKeyValue value) { if (reader == null) { throw LogArgumentNullException(nameof(reader)); } if (!reader.IsStartElement(XmlSignatureConstants.Elements.RSAKeyValue, XmlSignatureConstants.Namespace)) { value = null; return(false); } reader.ReadStartElement(XmlSignatureConstants.Elements.RSAKeyValue, XmlSignatureConstants.Namespace); if (!reader.IsStartElement(XmlSignatureConstants.Elements.Modulus, XmlSignatureConstants.Namespace)) { throw XmlUtil.LogReadException(GetLogMessage("IDX30011"), XmlSignatureConstants.Namespace, XmlSignatureConstants.Elements.Modulus, reader.NamespaceURI, reader.LocalName); } var modulus = reader.ReadElementContentAsString(XmlSignatureConstants.Elements.Modulus, XmlSignatureConstants.Namespace); if (!reader.IsStartElement(XmlSignatureConstants.Elements.Exponent, XmlSignatureConstants.Namespace)) { throw XmlUtil.LogReadException(GetLogMessage("IDX30011"), XmlSignatureConstants.Namespace, XmlSignatureConstants.Elements.Exponent, reader.NamespaceURI, reader.LocalName); } var exponent = reader.ReadElementContentAsString(XmlSignatureConstants.Elements.Exponent, XmlSignatureConstants.Namespace); reader.ReadEndElement(); value = new RSAKeyValue(modulus, exponent); return(true); }
public void Ctor_Rsa() { using (RSA rsa = RSA.Create()) { RSAKeyValue rsaKeyValue = new RSAKeyValue(rsa); Assert.Equal(rsa, rsaKeyValue.Key); } }
/// <summary> /// Signs the specified xmldocument with the given key and the finderprint. /// </summary> /// <param name="doc">The XMl representation of a request to iDeal</param> /// <param name="key">The key used to sign</param> /// <param name="fingerprintHex">The fingerprint</param> /// <returns>Returns the modified xml with the signature</returns> public static XmlElement Sign(ref XmlDocument doc, RSA key, string fingerprintHex) { doc.PreserveWhitespace = true; Trace.WriteLine("Message to sign:" + doc.OuterXml); SignedXml signedXml = new SignedXml(doc); signedXml.SigningKey = key; // Get the signature object from the SignedXml object. Signature signatureRef = signedXml.Signature; //Pass "" to specify that all of the current XML document should be signed. Reference reference = new Reference(""); reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256"; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the Reference object to the Signature object. signatureRef.SignedInfo.AddReference(reference); signatureRef.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; signatureRef.SignedInfo.SignatureMethod = XmlDigSignRSASHA256Namespace; // Add an RSAKeyValue KeyInfo KeyInfo keyInfo = new KeyInfo(); KeyInfoClause clause = new RSAKeyValue(key); keyInfo.AddClause(clause); signatureRef.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement xmlSignature = signedXml.GetXml(); // Append the element to the XML document. doc.DocumentElement.AppendChild(doc.ImportNode(xmlSignature, true)); //xmlSignature.Prefix = "ds"; if (doc.FirstChild is XmlDeclaration) { doc.RemoveChild(doc.FirstChild); } string xml = doc.OuterXml; //replace KeyValue with KeyName containing the fingerprint of the signing certificate string keyNameTag = "<KeyName>" + fingerprintHex.Replace("-", "") + "</KeyName>"; xml = System.Text.RegularExpressions.Regex.Replace(xml, "<KeyValue>.*</KeyValue>", keyNameTag); //reload the xml document from customized xml source doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); //} return((XmlElement)doc.DocumentElement.ChildNodes[doc.DocumentElement.ChildNodes.Count - 1]); }
public void GetXml_SameRsa() { using (RSA rsa = RSA.Create()) { RSAKeyValue rsaKeyValue1 = new RSAKeyValue(rsa); RSAKeyValue rsaKeyValue2 = new RSAKeyValue(rsa); Assert.Equal(rsaKeyValue1.GetXml(), rsaKeyValue2.GetXml()); } }
public void LoadXml_InvalidXml(string xml) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); RSAKeyValue rsa = new RSAKeyValue(); Assert.Throws <CryptographicException>(() => rsa.LoadXml(xmlDocument.DocumentElement)); }
public void Ctor_Rsa() { var keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); var pair = keyGen.GenerateKeyPair(); RSAKeyValue rsaKeyValue = new RSAKeyValue((RsaKeyParameters)pair.Public); Assert.Equal(pair.Public, rsaKeyValue.Key); }
public void InvalidValue2() { string badKey = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(badKey); RSAKeyValue rsa = new RSAKeyValue(); rsa.LoadXml(doc.DocumentElement); }
public void GetXml_SameRsa() { var keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA"); keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); var pair = keyGen.GenerateKeyPair(); RSAKeyValue rsaKeyValue1 = new RSAKeyValue((RsaKeyParameters)pair.Public); RSAKeyValue rsaKeyValue2 = new RSAKeyValue((RsaKeyParameters)pair.Public); Assert.Equal(rsaKeyValue1.GetXml(), rsaKeyValue2.GetXml()); }
public void RSAKeyValue() { RSA key = RSA.Create(); key.FromXmlString(xmlRSA); RSAKeyValue rsa = new RSAKeyValue(key); info.AddClause(rsa); AssertCrypto.AssertXmlEquals("rsa", "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" + xmlRSA + "</KeyValue></KeyInfo>", (info.GetXml().OuterXml)); Assert.AreEqual(1, info.Count, "rsa count"); }
public void GetXml() { RSAKeyValue rsa = new RSAKeyValue(); XmlElement xmlkey = rsa.GetXml(); // Schema check. Should not throw. const string schema = "http://www.w3.org/2000/09/xmldsig#"; new[] { "Exponent", "Modulus" } .Select(elementName => Convert.FromBase64String(xmlkey.SelectSingleNode($"*[local-name()='RSAKeyValue' and namespace-uri()='{schema}']/*[local-name()='{elementName}' and namespace-uri()='{schema}']").InnerText)) .ToArray(); }
public void LoadXml_ValidXml(string xml, byte[] expectedModulus, byte[] expectedExponent) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); RSAKeyValue rsa = new RSAKeyValue(); rsa.LoadXml(xmlDocument.DocumentElement); Assert.Equal(expectedModulus, rsa.Key.Modulus.ToByteArrayUnsigned()); Assert.Equal(expectedExponent, rsa.Key.Exponent.ToByteArrayUnsigned()); }
public void RsaKeyValue_ListCollectionTests() { var rsaKeyValue = new RSAKeyValue(string.Empty, string.Empty); var secondrsaKeyValue = new RSAKeyValue("modulus", "exponent"); var list = new List <RSAKeyValue> { rsaKeyValue, secondrsaKeyValue }; var secondList = new List <RSAKeyValue> { rsaKeyValue, secondrsaKeyValue }; Assert.True(Enumerable.SequenceEqual(list, secondList)); }
public void Complex() { KeyInfoName name = new KeyInfoName(); name.Value = "CoreFx::"; info.AddClause(name); using (DSA keyDSA = DSA.Create()) { keyDSA.ImportParameters(new DSAParameters { P = Convert.FromBase64String(dsaP), Q = Convert.FromBase64String(dsaQ), G = Convert.FromBase64String(dsaG), Y = Convert.FromBase64String(dsaY), }); DSAKeyValue dsa = new DSAKeyValue(keyDSA); info.AddClause(dsa); using (RSA keyRSA = RSA.Create()) { keyRSA.ImportParameters(new RSAParameters() { Modulus = Convert.FromBase64String(rsaModulus), Exponent = Convert.FromBase64String(rsaExponent) }); RSAKeyValue rsa = new RSAKeyValue(keyRSA); info.AddClause(rsa); KeyInfoRetrievalMethod retrieval = new KeyInfoRetrievalMethod(); retrieval.Uri = "https://github.com/dotnet/corefx"; info.AddClause(retrieval); using (X509Certificate x509 = new X509Certificate(cert)) { KeyInfoX509Data x509data = new KeyInfoX509Data(x509); info.AddClause(x509data); string s = "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyName>CoreFx::</KeyName><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><DSAKeyValue><P>rjxsMU368YOCTQejWkiuO9e/vUVwkLtq1jKiU3TtJ53hBJqjFRuTa228vZe+BH2su9RPn/vYFWfQDv6zgBYe3eNdu4Afw+Ny0FatX6dl3E77Ra6Tsd3MmLXBiGSQ1mMNd5G2XQGpbt9zsGlUaexXekeMLxIufgfZLwYp67M+2WM=</P><Q>tf0K9rMyvUrU4cIkwbCrDRhQAJk=</Q><G>S8Z+1pGCed00w6DtVcqZLKjfqlCJ7JsugEFIgSy/Vxtu9YGCMclV4ijGEbPo/jU8YOSMuD7E9M7UaopMRcmKQjoKZzoJjkgVFP48Ohxl1f08lERnButsxanx3+OstFwUGQ8XNaGg3KrIoZt1FUnfxN3RHHTvVhjzNSHxMGULGaU=</G><Y>LnrxxRGLYeV2XLtK3SYz8RQHlHFZYrtznDZyMotuRfO5uC5YODhSFyLXvb1qB3WeGtF4h3Eo4KzHgMgfN2ZMlffxFRhJgTtH3ctbL8lfQoDkjeiPPnYGhspdJxr0tyZmiy0gkjJG3vwHYrLnvZWx9Wm/unqiOlGBPNuxJ+hOeP8=</Y></DSAKeyValue></KeyValue>"; s += "<KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RSAKeyValue><Modulus>9DC4XNdQJwMRnz5pP2a6U51MHCODRilaIoVXqUPhCUb0lJdGroeqVYT84ZyIVrcarzD7Tqs3aEOIa3rKox0N1bxQpZPqayVQeLAkjLLtzJW/ScRJx3uEDJdgT1JnM1FH0GZTinmEdCUXdLc7+Y/c/qqIkTfbwHbRZjW0bBJyExM=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>"; s += "<RetrievalMethod URI=\"https://github.com/dotnet/corefx\" />"; s += "<X509Data xmlns=\"http://www.w3.org/2000/09/xmldsig#\">"; s += "<X509Certificate>MIICHTCCAYYCARQwDQYJKoZIhvcNAQEEBQAwWDELMAkGA1UEBhMCQ0ExHzAdBgNVBAMTFktleXdpdG5lc3MgQ2FuYWRhIEluYy4xKDAmBgorBgEEASoCCwIBExhrZXl3aXRuZXNzQGtleXdpdG5lc3MuY2EwHhcNOTYwNTA3MDAwMDAwWhcNOTkwNTA3MDAwMDAwWjBYMQswCQYDVQQGEwJDQTEfMB0GA1UEAxMWS2V5d2l0bmVzcyBDYW5hZGEgSW5jLjEoMCYGCisGAQQBKgILAgETGGtleXdpdG5lc3NAa2V5d2l0bmVzcy5jYTCBnTANBgkqhkiG9w0BAQEFAAOBiwAwgYcCgYEAzSP6KuHtmPTp0JM+13qAAkzMwQKvXLYff/pXQm8w0SDFtSEHQCyphsLzZISuPYUu7YW9VLAYKO9q+BvnCxYfkyVPx/iOw7nKmIQOVdAv73h3xXIoX2C/GSvRcqK32D/glzRaAb0EnMh4Rc2TjRXydhARq7hbLp5S3YE+nGTIKZMCAQMwDQYJKoZIhvcNAQEEBQADgYEAMho1ur9DJ9a01Lh25eObTWzAhsl3NbprFi0TRkqwMlOhW1rpmeIMhogXTg3+gqxOR+/7/zms7jXI+lI3CkmtWa3iiqkcxl8f+G9zfs2gMegMvvVN2bKrihK2MHhoEXwN8UlNo/2y6f8d8JH6VIX/M5Dowb+km6RiRr1hElmYQYk=</X509Certificate></X509Data></KeyInfo>"; AssertCrypto.AssertXmlEquals("Complex", s, (info.GetXml().OuterXml)); Assert.Equal(5, info.Count); } } } }
public void LoadXml_ValidXml(string xml, byte[] expectedModulus, byte[] expectedExponent) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); RSAKeyValue rsa = new RSAKeyValue(); rsa.LoadXml(xmlDocument.DocumentElement); RSAParameters rsaParameters = rsa.Key.ExportParameters(false); Assert.Equal(expectedModulus, rsaParameters.Modulus); Assert.Equal(expectedExponent, rsaParameters.Exponent); }
public void ImportKey() { string rsaKey = "<KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RSAKeyValue><Modulus>ogZ1/O7iks9ncETqNxLDKoPvgrT4nFx1a3lOmpywEmgbc5+8vI5dSzReH4v0YrflY75rIJx13CYWMsaHfQ78GtXvaeshHlQ3lLTuSdYEJceKll/URlBoKQtOj5qYIVSFOIVGHv4Y/0lnLftOzIydem29KKH6lJQlJawBBssR12s=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(rsaKey); RSAKeyValue rsa1 = new RSAKeyValue(); rsa1.LoadXml(doc.DocumentElement); string s = (rsa1.GetXml().OuterXml); Assert.AreEqual(rsaKey, s, "RSA Key"); }
public void RSAKeyValue() { var key = new RsaKeyParameters( isPrivate: false, modulus: new BigInteger(1, Convert.FromBase64String(rsaModulus)), exponent: new BigInteger(1, Convert.FromBase64String(rsaExponent)) ); RSAKeyValue rsa = new RSAKeyValue(key); info.AddClause(rsa); AssertCrypto.AssertXmlEquals("rsa", "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" + xmlRSA + "</KeyValue></KeyInfo>", (info.GetXml().OuterXml)); Assert.Equal(1, info.Count); }
/// <summary> /// Attempts to retrieve an asymmetric key from the KeyInfoClause given as parameter. /// </summary> /// <param name="keyInfoClause"></param> /// <returns>null if the key could not be found.</returns> public static AsymmetricAlgorithm ExtractKey(KeyInfoClause keyInfoClause) { if (keyInfoClause is RSAKeyValue) { RSAKeyValue key = (RSAKeyValue)keyInfoClause; return(key.Key); } else if (keyInfoClause is KeyInfoX509Data) { X509Certificate2 cert = GetCertificateFromKeyInfo((KeyInfoX509Data)keyInfoClause); return(cert != null ? cert.PublicKey.Key : null); } return(null); }
public static XmlDocument Sign <T>(T data, X509Certificate2 certificate) where T : class { CspParameters cspParams = new CspParameters(); cspParams.KeyContainerName = "XML_DSIG_RSA_KEY"; var xmlDoc = new XmlDocument(); xmlDoc.PreserveWhitespace = true; // WARNING: pozor. Pri podpisu pri overeni musis obsah sedet! var str = Serialization.Xml.Serializer.SerializeToString(data); xmlDoc.LoadXml(str); var signedXml = new SignedXml(xmlDoc); signedXml.SigningKey = certificate.PrivateKey; var rsaprovider = (RSACryptoServiceProvider)certificate.PublicKey.Key; var rkv = new RSAKeyValue(rsaprovider); var keyInfo = new KeyInfo(); var keyInfoData = new KeyInfoX509Data(certificate); keyInfo.AddClause(keyInfoData); keyInfo.AddClause(rkv); signedXml.KeyInfo = keyInfo; // which part of xml to sign var reference = new Reference(); reference.Uri = ""; // "" indicates that we want to sign whole xml (main element) var env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); signedXml.ComputeSignature(); XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); // add signature to raw form of request return(xmlDoc); }
public void LoadXml_GetXml_With_NS_Prefix() { string rsaKeyWithPrefix = "<ds:KeyValue xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:RSAKeyValue><ds:Modulus>ogZ1/O7iks9ncETqNxLDKoPvgrT4nFx1a3lOmpywEmgbc5+8vI5dSzReH4v0YrflY75rIJx13CYWMsaHfQ78GtXvaeshHlQ3lLTuSdYEJceKll/URlBoKQtOj5qYIVSFOIVGHv4Y/0lnLftOzIydem29KKH6lJQlJawBBssR12s=</ds:Modulus><ds:Exponent>AQAB</ds:Exponent></ds:RSAKeyValue></ds:KeyValue>"; string rsaKeyWithoutPrefix = "<KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><RSAKeyValue><Modulus>ogZ1/O7iks9ncETqNxLDKoPvgrT4nFx1a3lOmpywEmgbc5+8vI5dSzReH4v0YrflY75rIJx13CYWMsaHfQ78GtXvaeshHlQ3lLTuSdYEJceKll/URlBoKQtOj5qYIVSFOIVGHv4Y/0lnLftOzIydem29KKH6lJQlJawBBssR12s=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(rsaKeyWithPrefix); RSAKeyValue rsa1 = new RSAKeyValue(); rsa1.LoadXml(doc.DocumentElement); string s = rsa1.GetXml().OuterXml; //Comparing with rsaKeyWithoutPrefix because RSAKeyValue.GetXml().OuterXml returns the markup without the namespace prefixes Assert.Equal(rsaKeyWithoutPrefix, s); }
public void RsaKeyValue_HashSetCollectionTests() { var set = new HashSet <RSAKeyValue>(); var rsaKeyValue = new RSAKeyValue(string.Empty, string.Empty); set.Add(rsaKeyValue); bool inCollection = set.Contains(rsaKeyValue); Assert.True(inCollection); var secondRSAKeyValue = new RSAKeyValue(string.Empty, string.Empty); // hashcode is determined by immutable property values, not reference inCollection = set.Contains(secondRSAKeyValue); Assert.True(inCollection); }
public KeyInfo CreateKeyInfo(X509Certificate2 certificate) { var keyData = new KeyInfoX509Data(certificate); var keyInfo = new KeyInfo(); keyInfo.AddClause(keyData); if (certificate.HasPrivateKey) { var rsa = new RSAKeyValue((RSA)certificate.PrivateKey); keyInfo.AddClause(rsa); } return(keyInfo);; }
public void RSAKeyValue() { using (RSA key = RSA.Create()) { key.ImportParameters(new RSAParameters() { Modulus = Convert.FromBase64String(rsaModulus), Exponent = Convert.FromBase64String(rsaExponent) }); RSAKeyValue rsa = new RSAKeyValue(key); info.AddClause(rsa); AssertCrypto.AssertXmlEquals("rsa", "<KeyInfo xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><KeyValue xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" + xmlRSA + "</KeyValue></KeyInfo>", (info.GetXml().OuterXml)); Assert.Equal(1, info.Count); } }
public void LoadXml_InvalidXml(string xml) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); RSAKeyValue rsa = new RSAKeyValue(); // FormatException exception because desktop does not // check if Convert.FromBase64String throws // Related to: https://github.com/dotnet/corefx/issues/18690 try { rsa.LoadXml(xmlDocument.DocumentElement); } catch (System.Security.Cryptography.CryptographicException) { } catch (FormatException) { } }
/// <summary> /// Verify the given document using a KeyInfo instance. The KeyInfo instance's KeyClauses will be traversed for /// elements that can verify the signature, eg. certificates or keys. If nothing is found, an exception is thrown. /// </summary> public static bool CheckSignature(XmlDocument doc, KeyInfo keyinfo) { CheckDocument(doc); SignedXml signedXml = RetrieveSignature(doc); AsymmetricAlgorithm alg = null; X509Certificate2 cert = null; foreach (KeyInfoClause clause in keyinfo) { if (clause is RSAKeyValue) { RSAKeyValue key = (RSAKeyValue)clause; alg = key.Key; break; } else if (clause is KeyInfoX509Data) { KeyInfoX509Data x509data = (KeyInfoX509Data)clause; int count = x509data.Certificates.Count; cert = (X509Certificate2)x509data.Certificates[count - 1]; } else if (clause is DSAKeyValue) { DSAKeyValue key = (DSAKeyValue)clause; alg = key.Key; break; } } if (alg == null && cert == null) { throw new InvalidOperationException("Unable to locate the key or certificate to verify the signature."); } if (alg != null) { return(signedXml.CheckSignature(alg)); } else { return(signedXml.CheckSignature(cert, true)); } }
public void GeneratedKey() { RSAKeyValue rsa1 = new RSAKeyValue(); Assert.IsNotNull(rsa1.Key, "Key"); XmlElement xmlkey = rsa1.GetXml(); RSAKeyValue rsa2 = new RSAKeyValue(); rsa2.LoadXml(xmlkey); Assert.IsTrue((rsa1.GetXml().OuterXml) == (rsa2.GetXml().OuterXml), "rsa1==rsa2"); RSA key = rsa1.Key; RSAKeyValue rsa3 = new RSAKeyValue(key); Assert.IsTrue((rsa3.GetXml().OuterXml) == (rsa1.GetXml().OuterXml), "rsa3==rsa1"); Assert.IsTrue((rsa3.GetXml().OuterXml) == (rsa2.GetXml().OuterXml), "rsa3==rsa2"); }
public void LoadXml_InvalidXml(string xml) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); RSAKeyValue rsa = new RSAKeyValue(); // FormatException exception because .NET Framework does not // check if Convert.FromBase64String throws // Related to: https://github.com/dotnet/runtime/issues/21236 try { rsa.LoadXml(xmlDocument.DocumentElement); } catch (CryptographicException) { } catch (FormatException) when(PlatformDetection.IsNetFramework) { } }
public static void SignXmlDocumentWithCertificate(XmlDocument xmlDoc, X509Certificate2 cert) { SignedXml signedXml = new SignedXml(xmlDoc); //we will sign it with private key signedXml.SigningKey = cert.PrivateKey; if (cert.PrivateKey == null) { throw new ArgumentException("Please make sure the application for electronic signatures is installed, so the private key can be obtained from the smart card!"); } Reference reference = new Reference(); //sign the entire doc reference.Uri = ""; XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); signedXml.AddReference(reference); //PublicKey part RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key; RSAKeyValue rkv = new RSAKeyValue(rsaprovider); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert)); //We add the public key here keyInfo.AddClause(rkv); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); // Append the element to the XML document. xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true)); }
private void assinarArquivo(ArquivoDTO arquivo) { try { int index = assinado - 1; X509Certificate2 certificado = listaCertificados.ElementAt(index); RSACryptoServiceProvider crypto = (RSACryptoServiceProvider)certificado.PrivateKey; SignedXml signedXml = new SignedXml(); signedXml.SigningKey = certificado.PrivateKey; Reference reference = new Reference(); reference.Uri = uriImagem; signedXml.AddReference(reference); KeyInfo keyInfo = new KeyInfo(); RSAKeyValue rsaKeyValue = new RSAKeyValue(crypto); keyInfo.AddClause(rsaKeyValue); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature(); XmlElement signatureXml = signedXml.GetXml(); arquivo.streamAssinatura = new MemoryStream(); MemoryStream msAssinatura = new MemoryStream(); using (XmlTextWriter signatureWriter = new XmlTextWriter(msAssinatura, new UTF8Encoding(false))) { signatureWriter.Formatting = Formatting.Indented; signatureXml.WriteTo(signatureWriter); signatureWriter.Flush(); msAssinatura.Position = 0; msAssinatura.CopyTo(arquivo.streamAssinatura); } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Erro"); } }
//tutorial - https://www.asptricks.net/2015/09/sign-xmldocument-with-x509certificate2.html internal static XmlDocument GetSignedXMLDocument(XmlDocument xmlDocument, X509Certificate2 certificate, long procedureSerial = -1, string reason = "") { //Before signing, should check if current document sign is valid or not, if current document is invalid, then new sign should not be added - not implemented yet, but should be if (CheckIfDocumentPreviouslySigned(xmlDocument)) { bool?isLastSignVerified = VerifyLastSign(xmlDocument); if (isLastSignVerified == false) { MessageBox.Show("The file was TEMPERED after last sign !!"); return(null); //Last Sign Not Verified } } //Then sign the xml try { //MessageBox.Show(certificate.Subject); SignedXml signedXml = new SignedXml(xmlDocument); signedXml.SigningKey = certificate.PrivateKey; // Create a reference to be signed Reference reference = new Reference(); ///////////////////// reference.Uri = ""; //"#" + procedureSerial; //reference.Type = reason; //reference.Id = DateTime.UtcNow.Ticks.ToString(); Tsa tsa = new Tsa(); string signedTsaString = tsa.GetSignedHashFromTsa(xmlDocument); DateTime?tsaTime = Tsa.GetTsaTimeFromSignedHash(signedTsaString); //reference.Id = Base64EncodedCurrentTime(tsaTime); reference.Id = signedTsaString; //bool status = Tsa.ValidateTimestamp(xmlDocument, reference.Id); //reference.TransformChain = ; ///////////////////// // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(true); reference.AddTransform(env); // Add the reference to the SignedXml object. signedXml.AddReference(reference); //canonicalize XmlDsigC14NTransform c14t = new XmlDsigC14NTransform(); reference.AddTransform(c14t); KeyInfo keyInfo = new KeyInfo(); KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate); KeyInfoName kin = new KeyInfoName(); //kin.Value = "Public key of certificate"; kin.Value = certificate.FriendlyName; RSA rsa = (RSA)certificate.PublicKey.Key; RSAKeyValue rkv = new RSAKeyValue(rsa); keyInfo.AddClause(rkv); keyInfo.AddClause(kin); keyInfo.AddClause(keyInfoData); signedXml.KeyInfo = keyInfo; //////////////////////////////////////////Add Other Data as we need//// // Add the data object to the signature. //CreateMetaDataObject("Name", GetNetworkTime()); signedXml.AddObject(CreateMetaDataObject(procedureSerial, reason)); /////////////////////////////////////////////////////////////////////// // Compute the signature. signedXml.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = signedXml.GetXml(); xmlDocument.DocumentElement.AppendChild( xmlDocument.ImportNode(xmlDigitalSignature, true) ); ///////////////////// } catch (Exception exception) { MessageBox.Show("Internal System Error during sign"); throw exception; } return(xmlDocument); }