/// <summary> /// Формирование сигнатуры по хэшу для серверной подписи /// </summary> /// <param name="hash"></param> /// <returns></returns> public static byte[] ComputeSignatureDigest(byte[] hash) { using (var g = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm()) { return(ComputeSignatureDigest(g, hash)); } }
private static SymmetricAlgorithm DecryptKeyClass(byte[] keyData, RSA algorithm, bool useOaep, string symmetricAlgorithmUri) { if (keyData == null) { throw ExceptionUtility.ArgumentNull("keyData"); } if (algorithm == null) { throw ExceptionUtility.ArgumentNull("algorithm"); } SymmetricAlgorithm decryptionKey = null; var decryptionKeyBytes = DecryptKey(keyData, algorithm, useOaep); if (decryptionKeyBytes != null) { decryptionKey = (SymmetricAlgorithm)GostCryptoConfig.CreateFromName(symmetricAlgorithmUri); decryptionKey.Key = decryptionKeyBytes; } if (decryptionKey == null) { throw ExceptionUtility.CryptographicException(Resources.XmlMissingAlgorithm); } return(decryptionKey); }
/// <summary> /// Формирование сигнатуры для серверной подписи /// </summary> /// <param name="data"></param> /// <param name="detached"></param> /// <returns></returns> public static byte[] ComputeSignature(byte[] data, bool detached = true) { using (var g = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm()) { return(ComputeSignature(g, data, detached)); } }
public byte[] ComputeDigest() { BuildDigestedReferences(); // Check the signature algorithm if (SignedInfo.SignatureMethod == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreatedKeyFailed")); } // See if there is a signature description class defined in the Config file SignatureDescription signatureDescription = GostCryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } return(GetC14NDigest(hashAlg)); }
public void ComputeSignature(string prefix) { BuildDigestedReferences(); SignatureDescription description = GostCryptoConfig.CreateFromName(this.SignedInfo.SignatureMethod) as SignatureDescription; HashAlgorithm hash = description.CreateDigest(); GetDigest(hash, prefix); this.m_signature.SignatureValue = description.CreateFormatter(this.SigningKey).CreateSignature(hash); }
public void SetUp() { var certificate = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm().ContainerCertificate; // Отправитель имеет открытый асимметричный ключ для шифрации сессионного ключа _publicKey = certificate.PublicKey.Key; // Получатель имеет закрытый асимметричный ключ для дешифрации сессионного ключа _privateKey = certificate.PrivateKey; }
public void ShouldSignXml() { // Given var signingCertificate = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm(); var xmlDocument = CreateXmlDocument(); // When var signedXmlDocument = SignXmlDocument(xmlDocument, signingCertificate); // Then Assert.IsTrue(VerifyXmlDocumentSignature(signedXmlDocument)); }
public void ComputeSignature() { BuildDigestedReferences(); // Load the key AsymmetricAlgorithm key = SigningKey; if (key == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_LoadKeyFailed")); } // Check the signature algorithm associated with the key so that we can accordingly set the signature method if (SignedInfo.SignatureMethod == null) { if (key is DSA) { SignedInfo.SignatureMethod = XmlDsigDSAUrl; } else if (key is RSA) { // Default to RSA-SHA1 if (SignedInfo.SignatureMethod == null) { SignedInfo.SignatureMethod = XmlDsigRSASHA1Url; } } else { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreatedKeyFailed")); } } // See if there is a signature description class defined in the Config file SignatureDescription signatureDescription = GostCryptoConfig.CreateFromName(SignedInfo.SignatureMethod) as SignatureDescription; if (signatureDescription == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated")); } HashAlgorithm hashAlg = signatureDescription.CreateDigest(); if (hashAlg == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } byte[] hashvalue = GetC14NDigest(hashAlg); AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key); m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg); }
public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } XmlElement keyInfoElement = value; m_id = Utils.GetAttribute(keyInfoElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNode child = keyInfoElement.FirstChild; while (child != null) { XmlElement elem = child as XmlElement; if (elem != null) { // Create the right type of KeyInfoClause; we use a combination of the namespace and tag name (local name) String kicString = elem.NamespaceURI + " " + elem.LocalName; // Special-case handling for KeyValue -- we have to go one level deeper if (kicString == "http://www.w3.org/2000/09/xmldsig# KeyValue") { XmlNodeList nodeList2 = elem.ChildNodes; foreach (XmlNode node2 in nodeList2) { XmlElement elem2 = node2 as XmlElement; if (elem2 != null) { kicString += "/" + elem2.LocalName; break; } } } KeyInfoClause keyInfoClause = (KeyInfoClause)GostCryptoConfig.CreateFromName(kicString); // if we don't know what kind of KeyInfoClause we're looking at, use a generic KeyInfoNode: if (keyInfoClause == null) { keyInfoClause = new KeyInfoNode(); } // Ask the create clause to fill itself with the corresponding XML keyInfoClause.LoadXml(elem); // Add it to our list of KeyInfoClauses AddClause(keyInfoClause); } child = child.NextSibling; } }
public void ShouldEncryptXml() { // Given var certificate = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm().ContainerCertificate; var xmlDocument = CreateXmlDocument(); var expectedXml = xmlDocument.OuterXml; // When var encryptedXmlDocument = EncryptXmlDocument(xmlDocument, certificate); var decryptedXmlDocument = DecryptXmlDocument(encryptedXmlDocument); var actualXml = decryptedXmlDocument.OuterXml; // Then Assert.AreEqual(expectedXml, actualXml); }
private static XmlElement Smev3Signed(Stream message, string id) { var document = new XmlDocument(); document.PreserveWhitespace = false; document.Load(message); var signedXml = new SmevSignedXml(document); using (var key = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm()) { var reference = new Reference(); reference.Uri = "#" + id; reference.AddTransform(new XmlDsigExcC14NTransform()); reference.AddTransform(new XmlDsigSmevTransform()); signedXml.SigningKey = key; signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl; if (GostCryptoConfig.ProviderType == ProviderTypes.CryptoPro256) { signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigGost3410_2012_256Url; reference.DigestMethod = SignedXml.XmlDsigGost3411_2012_256Url; } else if (GostCryptoConfig.ProviderType == ProviderTypes.CryptoPro512) { signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigGost3410_2012_512Url; reference.DigestMethod = SignedXml.XmlDsigGost3411_2012_512Url; } else { signedXml.SignedInfo.SignatureMethod = SignedXml.XmlDsigGost3410UrlObsolete; reference.DigestMethod = SignedXml.XmlDsigGost3411UrlObsolete; } signedXml.AddReference(reference); var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(key.ContainerCertificate)); signedXml.KeyInfo = keyInfo; signedXml.ComputeSignature("ds"); } var smevSign = signedXml.GetXml("ds"); return(smevSign); }
private static bool VerifySignature(AsymmetricAlgorithm publicKey, Stream dataStream, byte[] signature) { var signatureDescription = (SignatureDescription)GostCryptoConfig.CreateFromName(publicKey.SignatureAlgorithm); byte[] hash; using (var hashAlg = signatureDescription.CreateDigest()) { hash = hashAlg.ComputeHash(dataStream); } var deformatter = signatureDescription.CreateDeformatter(publicKey); deformatter.SetHashAlgorithm(signatureDescription.DigestAlgorithm); return(deformatter.VerifySignature(hash, signature)); }
private static byte[] CreateSignature(AsymmetricAlgorithm privateKey, Stream dataStream) { var signatureDescription = (SignatureDescription)GostCryptoConfig.CreateFromName(privateKey.SignatureAlgorithm); byte[] hash; using (var hashAlg = signatureDescription.CreateDigest()) { hash = hashAlg.ComputeHash(dataStream); } var formatter = signatureDescription.CreateFormatter(privateKey); formatter.SetHashAlgorithm(signatureDescription.DigestAlgorithm); return(formatter.CreateSignature(hash)); }
public void SetUp() { // Получатель формирует закрытый ключ для дешифрации XML var privateKey = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm(); // Получатель экспортирует отправителю информацию о своем открытом ключе var publicKeyInfo = privateKey.ExportParameters(false); // Отправитель импортирует от получателя информацию о его открытом ключе var publicKey = new Gost3410AsymmetricAlgorithm(); // Отправитель формирует открытый ключ для шифрации XML publicKey.ImportParameters(publicKeyInfo); _privateKey = privateKey; _publicKey = publicKey; }
private static SymmetricAlgorithm DecryptKeyClass(byte[] keyData, SymmetricAlgorithm algorithm, string symmetricAlgorithmUri, string encryptionKeyAlgorithm) { if (keyData == null) { throw ExceptionUtility.ArgumentNull("keyData"); } if (algorithm == null) { throw ExceptionUtility.ArgumentNull("algorithm"); } SymmetricAlgorithm decryptionKey = null; var gost28147 = algorithm as Gost28147SymmetricAlgorithmBase; if (gost28147 != null) { if (string.Equals(encryptionKeyAlgorithm, GostEncryptedXml.XmlEncGostKeyExportUrl, StringComparison.OrdinalIgnoreCase)) { decryptionKey = gost28147.DecodePrivateKey(keyData, GostKeyExchangeExportMethod.GostKeyExport); } if (string.Equals(encryptionKeyAlgorithm, GostEncryptedXml.XmlEncGostCryptoProKeyExportUrl, StringComparison.OrdinalIgnoreCase)) { decryptionKey = gost28147.DecodePrivateKey(keyData, GostKeyExchangeExportMethod.CryptoProKeyExport); } } else { var decryptionKeyBytes = DecryptKey(keyData, algorithm); if (decryptionKeyBytes != null) { decryptionKey = (SymmetricAlgorithm)GostCryptoConfig.CreateFromName(symmetricAlgorithmUri); decryptionKey.Key = decryptionKeyBytes; } } if (decryptionKey == null) { throw ExceptionUtility.CryptographicException(Resources.XmlMissingAlgorithm); } return(decryptionKey); }
public void ShouldSignDataStream() { // Given var certificate = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm().ContainerCertificate; var privateKey = certificate.PrivateKey; var publicKey = certificate.PublicKey.Key; var dataStream = CreateDataStream(); // When dataStream.Seek(0, SeekOrigin.Begin); var signature = CreateSignature(privateKey, dataStream); dataStream.Seek(0, SeekOrigin.Begin); var isValidSignature = VerifySignature(publicKey, dataStream, signature); // Then Assert.IsTrue(isValidSignature); }
static void Main(string[] args) { GostCryptoConfig.ProviderType = ProviderTypes.CryptoPro256; Config.InitCommon(); var alg = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm(); var par = alg.ExportParameters(false); var b = Pkcs.SignedPkcs7.ComputeSignature(File.ReadAllBytes("d:/2018-09-12.zip")); File.WriteAllBytes("d:/2018-09-12.zip.sig", b); var smev = new Xml.SMEV.XmlDsigSmevTransform(); var bytes = File.ReadAllBytes("d:/test_2.xml"); XmlDocument doc = new XmlDocument(); doc.LoadXml(Encoding.UTF8.GetString(bytes)); smev.LoadInput(doc); var output = (MemoryStream)smev.GetOutput(typeof(Stream)); File.WriteAllBytes("d:/test_2_result.xml", output.ToArray()); //var signedXmlDocument = new XmlDocument(); //signedXmlDocument.LoadXml(File.ReadAllText("saml.xml")); //// Создание подписчика XML-документа //var signedXml = new SignedXml(signedXmlDocument); //// Поиск узла с подписью //var nodeList = signedXmlDocument.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl); //// Загрузка найденной подписи //signedXml.LoadXml((XmlElement)nodeList[0]); //// Проверка подписи //bool b = signedXml.CheckSignature(); //var t = new SignedXmlKeyContainerTest(); //t.SetUp(); //t.ShouldSignXml(); //t.TearDown(); }
private bool CheckSignedInfo(AsymmetricAlgorithm key) { if (key == null) { throw new ArgumentNullException("key"); } SignatureDescription signatureDescription = GostCryptoConfig.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); return(asymmetricSignatureDeformatter.VerifySignature(hashval, m_signature.SignatureValue)); }
// default behaviour is to look for keys defined by an EncryptedKey clause // either directly or through a KeyInfoRetrievalMethod, and key names in the key mapping public virtual SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri) { if (encryptedData == null) { throw new ArgumentNullException("encryptedData"); } if (encryptedData.KeyInfo == null) { return(null); } IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator(); KeyInfoRetrievalMethod kiRetrievalMethod; KeyInfoName kiName; KeyInfoEncryptedKey kiEncKey; EncryptedKey ek = null; while (keyInfoEnum.MoveNext()) { kiName = keyInfoEnum.Current as KeyInfoName; if (kiName != null) { // Get the decryption key from the key mapping string keyName = kiName.Value; if ((SymmetricAlgorithm)m_keyNameMapping[keyName] != null) { return((SymmetricAlgorithm)m_keyNameMapping[keyName]); } // try to get it from a CarriedKeyName XmlNamespaceManager nsm = new XmlNamespaceManager(m_document.NameTable); nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl); XmlNodeList encryptedKeyList = m_document.SelectNodes("//enc:EncryptedKey", nsm); if (encryptedKeyList != null) { foreach (XmlNode encryptedKeyNode in encryptedKeyList) { XmlElement encryptedKeyElement = encryptedKeyNode as XmlElement; EncryptedKey ek1 = new EncryptedKey(); ek1.LoadXml(encryptedKeyElement); if (ek1.CarriedKeyName == keyName && ek1.Recipient == this.Recipient) { ek = ek1; break; } } } break; } kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; if (kiRetrievalMethod != null) { string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); ek = new EncryptedKey(); ek.LoadXml(GetIdElement(m_document, idref)); break; } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; if (kiEncKey != null) { ek = kiEncKey.EncryptedKey; break; } } // if we have an EncryptedKey, decrypt to get the symmetric key if (ek != null) { // now process the EncryptedKey, loop recursively // If the Uri is not provided by the application, try to get it from the EncryptionMethod if (symmetricAlgorithmUri == null) { if (encryptedData.EncryptionMethod == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingAlgorithm")); } symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm; } byte[] key = DecryptEncryptedKey(ek); if (key == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_MissingDecryptionKey")); } SymmetricAlgorithm symAlg = (SymmetricAlgorithm)GostCryptoConfig.CreateFromName(symmetricAlgorithmUri); symAlg.Key = key; return(symAlg); } return(null); }
static GostSignedXml() { GostCryptoConfig.Initialize(); }
// Try to decrypt the EncryptedKey given the key mapping public virtual byte[] DecryptEncryptedKey(EncryptedKey encryptedKey) { if (encryptedKey == null) { throw new ArgumentNullException("encryptedKey"); } if (encryptedKey.KeyInfo == null) { return(null); } IEnumerator keyInfoEnum = encryptedKey.KeyInfo.GetEnumerator(); KeyInfoName kiName; KeyInfoX509Data kiX509Data; KeyInfoRetrievalMethod kiRetrievalMethod; KeyInfoEncryptedKey kiEncKey; EncryptedKey ek = null; bool fOAEP = false; while (keyInfoEnum.MoveNext()) { kiName = keyInfoEnum.Current as KeyInfoName; if (kiName != null) { // Get the decryption key from the key mapping string keyName = kiName.Value; Object kek = m_keyNameMapping[keyName]; if (kek != null) { // kek is either a SymmetricAlgorithm or an RSA key, otherwise, we wouldn't be able to insert it in the hash table if (kek is SymmetricAlgorithm) { return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm)kek)); } // kek is an RSA key: get fOAEP from the algorithm, default to false fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, (RSA)kek, fOAEP)); } break; } kiX509Data = keyInfoEnum.Current as KeyInfoX509Data; if (kiX509Data != null) { X509CertificateCollection collection = Utils.BuildBagOfCerts(kiX509Data, CertUsageType.Decryption); foreach (X509Certificate certificate in collection) { RSA privateKey = certificate.PrivateKey as RSA; if (privateKey != null) { fOAEP = (encryptedKey.EncryptionMethod != null && encryptedKey.EncryptionMethod.KeyAlgorithm == EncryptedXml.XmlEncRSAOAEPUrl); return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, privateKey, fOAEP)); } } break; } kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod; if (kiRetrievalMethod != null) { string idref = Utils.ExtractIdFromLocalUri(kiRetrievalMethod.Uri); ek = new EncryptedKey(); ek.LoadXml(GetIdElement(m_document, idref)); return(DecryptEncryptedKey(ek)); } kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey; if (kiEncKey != null) { ek = kiEncKey.EncryptedKey; // recursively process EncryptedKey elements byte[] encryptionKey = DecryptEncryptedKey(ek); if (encryptionKey != null) { // this is a symmetric algorithm for sure SymmetricAlgorithm symAlg = (SymmetricAlgorithm)GostCryptoConfig.CreateFromName(encryptedKey.EncryptionMethod.KeyAlgorithm); symAlg.Key = encryptionKey; return(EncryptedXml.DecryptKey(encryptedKey.CipherData.CipherValue, symAlg)); } } } return(null); }
static void PKCS7() { GostCryptoConfig.ProviderType = ProviderTypes.VipNet; Config.InitCommon(); BCX509.X509Certificate bcCert = null; using (var g = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm()) { bool detached = false; byte[] data = File.ReadAllBytes("test.xml"); var certBytes = g.ContainerCertificateRaw; BCX509.X509CertificateParser _x509CertificateParser = new BCX509.X509CertificateParser(); bcCert = _x509CertificateParser.ReadCertificate(certBytes); ICollection <BCX509.X509Certificate> certPath = new List <BCX509.X509Certificate>(); certPath.Add(bcCert); IDigest digest = new Gost3411Digest(); string hashOid = GostCryptoConfig.DefaultHashOid; byte[] dataHash = ComputeDigest(digest, data); // Construct SignerInfo.signedAttrs Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector(); // Add PKCS#9 contentType signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier("1.2.840.113549.1.9.3"), new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1")))); // Add PKCS#9 messageDigest signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier("1.2.840.113549.1.9.4"), new DerSet(new DerOctetString(dataHash)))); // Add PKCS#9 signingTime signed attribute signedAttributesVector.Add( new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier("1.2.840.113549.1.9.5"), new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow))))); DerSet signedAttributes = new DerSet(signedAttributesVector); byte[] pkcs1Digest = ComputeDigest(digest, signedAttributes.GetDerEncoded()); byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, hashOid); // hash //var signature = g.CreateSignature(hash); var formatter = new GostSignatureFormatter(g); var signature = formatter.CreateSignature(pkcs1Digest); // Construct SignerInfo SignerInfo signerInfo = new SignerInfo( new SignerIdentifier(new IssuerAndSerialNumber(bcCert.IssuerDN, bcCert.SerialNumber)), new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null), signedAttributes, new AlgorithmIdentifier(new DerObjectIdentifier(GostCryptoConfig.DefaultSignOid), null), new DerOctetString(signature), null); // Construct SignedData.digestAlgorithms Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector(); digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null)); // Construct SignedData.encapContentInfo ContentInfo encapContentInfo = new ContentInfo( new DerObjectIdentifier("1.2.840.113549.1.7.1"), (detached) ? null : new DerOctetString(data)); // Construct SignedData.certificates Asn1EncodableVector certificatesVector = new Asn1EncodableVector(); foreach (BCX509.X509Certificate cert in certPath) { certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded()))); } // Construct SignedData.signerInfos Asn1EncodableVector signerInfosVector = new Asn1EncodableVector(); signerInfosVector.Add(signerInfo.ToAsn1Object()); // Construct SignedData SignedData signedData = new SignedData( new DerSet(digestAlgorithmsVector), encapContentInfo, new BerSet(certificatesVector), null, new DerSet(signerInfosVector)); // Construct top level ContentInfo ContentInfo contentInfo = new ContentInfo( new DerObjectIdentifier("1.2.840.113549.1.7.2"), signedData); var res = contentInfo.GetDerEncoded(); File.WriteAllBytes("test.p7", res); CmsSignedData cms = new CmsSignedData(res); var certStore = cms.GetCertificates("Collection"); SignerInformationStore signers = cms.GetSignerInfos(); var it = signers.GetSigners().GetEnumerator(); it.MoveNext(); var signer = it.Current as SignerInformation; var b = signer.Verify(bcCert); } }
public void LoadXml(XmlElement value) { if (value == null) { throw new ArgumentNullException("value"); } m_id = Utils.GetAttribute(value, "Id", SignedXml.XmlDsigNamespaceUrl); m_uri = Utils.GetAttribute(value, "URI", SignedXml.XmlDsigNamespaceUrl); m_type = Utils.GetAttribute(value, "Type", SignedXml.XmlDsigNamespaceUrl); XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable); nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl); // Transforms this.TransformChain = new TransformChain(); XmlElement transformsElement = value.SelectSingleNode("ds:Transforms", nsm) as XmlElement; if (transformsElement != null) { XmlNodeList transformNodes = transformsElement.SelectNodes("ds:Transform", nsm); if (transformNodes != null) { foreach (XmlNode transformNode in transformNodes) { XmlElement transformElement = transformNode as XmlElement; string algorithm = Utils.GetAttribute(transformElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); Transform transform = GostCryptoConfig.CreateFromName(algorithm) as Transform; if (transform == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UnknownTransform")); } AddTransform(transform); // let the transform read the children of the transformElement for data transform.LoadInnerXml(transformElement.ChildNodes); // Hack! this is done to get around the lack of here() function support in XPath if (transform is XmlDsigEnvelopedSignatureTransform) { // Walk back to the Signature tag. Find the nearest signature ancestor // Signature-->SignedInfo-->Reference-->Transforms-->Transform XmlNode signatureTag = transformElement.SelectSingleNode("ancestor::ds:Signature[1]", nsm); XmlNodeList signatureList = transformElement.SelectNodes("//ds:Signature", nsm); if (signatureList != null) { int position = 0; foreach (XmlNode node in signatureList) { position++; if (node == signatureTag) { ((XmlDsigEnvelopedSignatureTransform)transform).SignaturePosition = position; break; } } } } } } } // DigestMethod XmlElement digestMethodElement = value.SelectSingleNode("ds:DigestMethod", nsm) as XmlElement; if (digestMethodElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestMethod"); } m_digestMethod = Utils.GetAttribute(digestMethodElement, "Algorithm", SignedXml.XmlDsigNamespaceUrl); // DigestValue XmlElement digestValueElement = value.SelectSingleNode("ds:DigestValue", nsm) as XmlElement; if (digestValueElement == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Reference/DigestValue"); } m_digestValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(digestValueElement.InnerText)); // cache the Xml m_cachedXml = value; }
internal byte[] CalculateHashValue(XmlDocument document, CanonicalXmlNodeList refList) { // refList is a list of elements that might be targets of references // Now's the time to create our hashing algorithm m_hashAlgorithm = GostCryptoConfig.CreateFromName(m_digestMethod) as HashAlgorithm; if (m_hashAlgorithm == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed")); } // Let's go get the target. string baseUri = (document == null ? System.Environment.CurrentDirectory + "\\" : document.BaseURI); Stream hashInputStream = null; WebRequest request = null; WebResponse response = null; Stream inputStream = null; XmlResolver resolver = null; byte[] hashval = null; try { switch (m_refTargetType) { case ReferenceTargetType.Stream: // This is the easiest case. We already have a stream, so just pump it through the TransformChain resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream((Stream)m_refTarget, resolver, baseUri); break; case ReferenceTargetType.UriReference: // Second-easiest case -- dereference the URI & pump through the TransformChain // handle the special cases where the URI is null (meaning whole doc) // or the URI is just a fragment (meaning a reference to an embedded Object) if (m_uri == null) { // We need to create a DocumentNavigator out of the XmlElement resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); // In the case of a Uri-less reference, we will simply pass null to the transform chain. // The first transform in the chain is expected to know how to retrieve the data to hash. hashInputStream = this.TransformChain.TransformToOctetStream((Stream)null, resolver, baseUri); } else if (m_uri.Length == 0) { // This is the self-referential case. First, check that we have a document context. // The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process if (document == null) { throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri)); } // Normalize the containing document resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); XmlDocument docWithNoComments = Utils.DiscardComments(Utils.PreProcessDocumentInput(document, resolver, baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else if (m_uri[0] == '#') { // If we get here, then we are constructing a Reference to an embedded DataObject // referenced by an Id = attribute. Go find the relevant object bool discardComments = true; string idref = Utils.GetIdFromLocalUri(m_uri, out discardComments); if (idref == "xpointer(/)") { // This is a self referencial case if (document == null) { throw new CryptographicException(String.Format(CultureInfo.CurrentCulture, SecurityResources.GetResourceString("Cryptography_Xml_SelfReferenceRequiresContext"), m_uri)); } // We should not discard comments here!!! resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessDocumentInput(document, resolver, baseUri), resolver, baseUri); break; } XmlElement elem = this.SignedXml.GetIdElement(document, idref); if (elem != null) { m_namespaces = Utils.GetPropagatedAttributes(elem.ParentNode as XmlElement); } if (elem == null) { // Go throw the referenced items passed in if (refList != null) { foreach (XmlNode node in refList) { XmlElement tempElem = node as XmlElement; if ((tempElem != null) && (Utils.HasAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl)) && (Utils.GetAttribute(tempElem, "Id", SignedXml.XmlDsigNamespaceUrl).Equals(idref))) { elem = tempElem; if (this.m_signedXml.m_context != null) { m_namespaces = Utils.GetPropagatedAttributes(this.m_signedXml.m_context); } break; } } } } if (elem == null) { throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidReference")); } XmlDocument normDocument = Utils.PreProcessElementInput(elem, resolver, baseUri); // Add the propagated attributes Utils.AddNamespaces(normDocument.DocumentElement, m_namespaces); resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); if (discardComments) { // We should discard comments before going into the transform chain XmlDocument docWithNoComments = Utils.DiscardComments(normDocument); hashInputStream = this.TransformChain.TransformToOctetStream(docWithNoComments, resolver, baseUri); } else { // This is an XPointer reference, do not discard comments!!! hashInputStream = this.TransformChain.TransformToOctetStream(normDocument, resolver, baseUri); } } else { // WebRequest always expects an Absolute Uri, so try to resolve if we were passed a relative Uri. System.Uri uri = new System.Uri(m_uri, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { uri = new Uri(new Uri(baseUri), uri); } request = WebRequest.Create(uri); if (request == null) { goto default; } response = request.GetResponse(); if (response == null) { goto default; } inputStream = response.GetResponseStream(); if (inputStream == null) { goto default; } resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(inputStream, resolver, m_uri); } break; case ReferenceTargetType.XmlElement: // We need to create a DocumentNavigator out of the XmlElement resolver = (this.SignedXml.ResolverSet ? this.SignedXml.m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri)); hashInputStream = this.TransformChain.TransformToOctetStream(Utils.PreProcessElementInput((XmlElement)m_refTarget, resolver, baseUri), resolver, baseUri); break; default: throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_UriNotResolved"), m_uri); } // Compute the new hash value //hashInputStream = SignedXmlDebugLog.LogReferenceData(this, hashInputStream); hashval = m_hashAlgorithm.ComputeHash(hashInputStream); } finally { if (hashInputStream != null) { hashInputStream.Close(); } if (response != null) { response.Close(); } if (inputStream != null) { inputStream.Close(); } } return(hashval); }
static GostEncryptedXml() { GostCryptoConfig.Initialize(); }