static CmsSignedData ReadPem(String filename) { StreamReader sR = new StreamReader(filename); PemReader pR = new PemReader(sR); Org.BouncyCastle.Asn1.Cms.ContentInfo cI = (Org.BouncyCastle.Asn1.Cms.ContentInfo) pR.ReadObject(); sR.Close(); CmsSignedData cms = new CmsSignedData(cI); return cms; }
/// <summary>The default constructor for CAdESOCSPSource.</summary> /// <remarks>The default constructor for CAdESOCSPSource.</remarks> /// <param name="encodedCMS"></param> /// <exception cref="Org.Bouncycastle.Cms.CmsException">Org.Bouncycastle.Cms.CmsException /// </exception> public CAdESOCSPSource(CmsSignedData cms) { IEnumerator signers = cms.GetSignerInfos().GetSigners().GetEnumerator(); signers.MoveNext(); this.cmsSignedData = cms; this.signerId = ((SignerInformation)signers.Current).SignerID; }
public TimeStampToken( CmsSignedData signedData) { this.tsToken = signedData; if (!this.tsToken.SignedContentTypeOid.Equals(PkcsObjectIdentifiers.IdCTTstInfo.Id)) { throw new TspValidationException("ContentInfo object not for a time stamp."); } ICollection signers = tsToken.GetSignerInfos().GetSigners(); if (signers.Count != 1) { throw new ArgumentException("Time-stamp token signed by " + signers.Count + " signers, but it must contain just the TSA signature."); } IEnumerator signerEnum = signers.GetEnumerator(); signerEnum.MoveNext(); tsaSignerInfo = (SignerInformation) signerEnum.Current; try { CmsProcessable content = tsToken.SignedContent; MemoryStream bOut = new MemoryStream(); content.Write(bOut); this.tstInfo = new TimeStampTokenInfo( TstInfo.GetInstance( Asn1Object.FromByteArray(bOut.ToArray()))); Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[ PkcsObjectIdentifiers.IdAASigningCertificate]; if (attr == null) { throw new TspValidationException( "no signing certificate attribute found, time stamp invalid."); } SigningCertificate signCert = SigningCertificate.GetInstance( attr.AttrValues[0]); this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]); } catch (CmsException e) { throw new TspException(e.Message, e.InnerException); } }
static void Main(string[] args) { //if (args.Length > 0) //string fullFileName = Path.GetFullPath(args[0]); foreach (string fileName in Directory.GetFiles("p7m")) { FileStream file = new FileStream(fileName, FileMode.Open); bool isValid = true; Console.WriteLine("File to decrypt: " + fileName); try { CmsSignedData signedFile = new CmsSignedData(file); IX509Store certStore = signedFile.GetCertificates("Collection"); ICollection certs = certStore.GetMatches(new X509CertStoreSelector()); SignerInformationStore signerStore = signedFile.GetSignerInfos(); ICollection signers = signerStore.GetSigners(); foreach (object tempCertification in certs) { X509Certificate certification = tempCertification as X509Certificate; foreach (object tempSigner in signers) { SignerInformation signer = tempSigner as SignerInformation; if (!signer.Verify(certification.GetPublicKey())) { isValid = false; break; } } } string newFileName = Path.Combine(Directory.CreateDirectory("p7m-extracted").Name, Path.GetFileNameWithoutExtension(fileName)); using (var fileStream = new FileStream(newFileName, FileMode.Create, FileAccess.Write)) { signedFile.SignedContent.Write(fileStream); Console.WriteLine("File decrypted: " + newFileName); } } catch (Exception ex) { isValid = false; } Console.WriteLine("File valid: " + isValid); ; } Console.ReadLine(); }
/// <exception cref="System.IO.IOException"></exception> public virtual Document ExtendSignatures(Document document, Document originalData , SignatureParameters parameters) { try { CmsSignedData signedData = new CmsSignedData(document.OpenStream()); SignerInformationStore signerStore = signedData.GetSignerInfos(); AList<SignerInformation> siArray = new AList<SignerInformation>(); foreach (SignerInformation si in signerStore.GetSigners()) { try { //jbonilla - Hack para evitar errores cuando una firma ya ha sido extendida. //Se asume que sólo se extiende las firmas desde BES. //TODO jbonilla - Se debería validar hasta qué punto se extendió (BES, T, C, X, XL). if(si.UnsignedAttributes.Count == 0) { siArray.AddItem(ExtendCMSSignature(signedData, si, parameters, originalData)); } else { LOG.Error("Already extended?"); siArray.AddItem(si); } } catch (IOException) { LOG.Error("Exception when extending signature"); siArray.AddItem(si); } } SignerInformationStore newSignerStore = new SignerInformationStore(siArray); CmsSignedData extended = CmsSignedData.ReplaceSigners(signedData, newSignerStore); return new InMemoryDocument(extended.GetEncoded()); } catch (CmsException) { throw new IOException("Cannot parse CMS data"); } }
/// <inheritdoc /> public byte[] Decrypt(byte[] data) { foreach (var pkcsStore in _allSenderCertificates) { var certAlias = pkcsStore.Aliases.Cast<string>().First(x => pkcsStore.IsKeyEntry(x)); var certEntry = pkcsStore.GetCertificate(certAlias); var cert = certEntry.Certificate; var envelopedData = new CmsEnvelopedData(data); var recepientInfos = envelopedData.GetRecipientInfos(); var recepientId = new RecipientID() { Issuer = cert.IssuerDN, SerialNumber = cert.SerialNumber }; var recepient = recepientInfos[recepientId]; if (recepient == null) continue; var privKeyEntry = pkcsStore.GetKey(certAlias); var privKey = privKeyEntry.Key; var decryptedData = recepient.GetContent(privKey); var sig = new CmsSignedData(decryptedData); var sigInfos = sig.GetSignerInfos(); var signerId = new SignerID() { Issuer = _receiverCertificate.IssuerDN, SerialNumber = _receiverCertificate.SerialNumber }; var signer = sigInfos.GetFirstSigner(signerId); if (!signer.Verify(_receiverCertificate)) throw new ExtraEncryptionException("Failed to verify the signature."); var verifiedData = new MemoryStream(); sig.SignedContent.Write(verifiedData); return verifiedData.ToArray(); } throw new ExtraEncryptionException("No certificate for decryption found."); }
private void SubjectKeyIDTest( IAsymmetricCipherKeyPair signaturePair, X509Certificate signatureCert, string digestAlgorithm) { IList certList = new ArrayList(); IList crlList = new ArrayList(); CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); certList.Add(signatureCert); certList.Add(OrigCert); crlList.Add(SignCrl); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); IX509Store x509Crls = X509StoreFactory.Create( "CRL/Collection", new X509CollectionStoreParameters(crlList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(signaturePair.Private, CmsTestUtil.CreateSubjectKeyId(signatureCert.GetPublicKey()).GetKeyIdentifier(), digestAlgorithm); gen.AddCertificates(x509Certs); gen.AddCrls(x509Crls); CmsSignedData s = gen.Generate(msg, true); Assert.AreEqual(3, s.Version); MemoryStream bIn = new MemoryStream(s.GetEncoded(), false); Asn1InputStream aIn = new Asn1InputStream(bIn); s = new CmsSignedData(ContentInfo.GetInstance(aIn.ReadObject())); x509Certs = s.GetCertificates("Collection"); x509Crls = s.GetCrls("Collection"); SignerInformationStore signers = s.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; Assert.IsTrue(signer.Verify(cert)); } // // check for CRLs // ArrayList crls = new ArrayList(x509Crls.GetMatches(null)); Assert.AreEqual(1, crls.Count); Assert.IsTrue(crls.Contains(SignCrl)); // // try using existing signer // gen = new CmsSignedDataGenerator(); gen.AddSigners(s.GetSignerInfos()); gen.AddCertificates(s.GetCertificates("Collection")); gen.AddCrls(s.GetCrls("Collection")); s = gen.Generate(msg, true); bIn = new MemoryStream(s.GetEncoded(), false); aIn = new Asn1InputStream(bIn); s = new CmsSignedData(ContentInfo.GetInstance(aIn.ReadObject())); x509Certs = s.GetCertificates("Collection"); x509Crls = s.GetCrls("Collection"); signers = s.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; Assert.IsTrue(signer.Verify(cert)); } CheckSignerStoreReplacement(s, signers); }
private void VerifySignatures( CmsSignedData s, byte[] contentDigest) { IX509Store x509Certs = s.GetCertificates("Collection"); SignerInformationStore signers = s.GetSignerInfos(); ICollection c = signers.GetSigners(); foreach (SignerInformation signer in c) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; Assert.IsTrue(signer.Verify(cert)); if (contentDigest != null) { Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest())); } } }
public void TestForMultipleCounterSignatures() { CmsSignedData sd = new CmsSignedData(xtraCounterSig); foreach (SignerInformation sigI in sd.GetSignerInfos().GetSigners()) { SignerInformationStore counter = sigI.GetCounterSignatures(); IList sigs = new ArrayList(counter.GetSigners()); Assert.AreEqual(2, sigs.Count); } }
public void TestCounterSig() { CmsSignedData sig = new CmsSignedData(GetInput("counterSig.p7m")); SignerInformationStore ss = sig.GetSignerInfos(); ArrayList signers = new ArrayList(ss.GetSigners()); SignerInformationStore cs = ((SignerInformation)signers[0]).GetCounterSignatures(); ArrayList csSigners = new ArrayList(cs.GetSigners()); Assert.AreEqual(1, csSigners.Count); foreach (SignerInformation cSigner in csSigners) { ArrayList certCollection = new ArrayList( sig.GetCertificates("Collection").GetMatches(cSigner.SignerID)); X509Certificate cert = (X509Certificate)certCollection[0]; Assert.IsNull(cSigner.SignedAttributes[Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtContentType]); Assert.IsTrue(cSigner.Verify(cert)); } VerifySignatures(sig); }
// Sign the message with the private key of the signer. public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached) { // Place message in a ContentInfo object. // This is required to build a SignedCms object. ContentInfo contentInfo = new ContentInfo(msg); // Instantiate SignedCms object with the ContentInfo above. // Has default SubjectIdentifierType IssuerAndSerialNumber. SignedCms signedCms = new SignedCms(contentInfo, detached); // Formulate a CmsSigner object for the signer. CmsSigner cmsSigner = new CmsSigner(signerCert); // Include the following line if the top certificate in the // smartcard is not in the trusted list. cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly; // Sign the CMS/PKCS #7 message. The second argument is // needed to ask for the pin. signedCms.ComputeSignature(cmsSigner, false); // TODO: Here the user can fail the password or cancel...what to do? // Encode the CMS/PKCS #7 message. byte[] bb = signedCms.Encode(); //return bb here if no timestamp is to be applied if (!Config.Stamp) return bb; CmsSignedData sd = new CmsSignedData(bb); SignerInformationStore signers = sd.GetSignerInfos(); byte[] signature = null; SignerInformation signer = null; foreach (SignerInformation signer_ in signers.GetSigners()) { signer = signer_; break; } signature = signer.GetSignature(); Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature)); signer = SignerInformation.ReplaceUnsignedAttributes(signer, at); IList signerInfos = new ArrayList(); signerInfos.Add(signer); sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos)); bb = sd.GetEncoded(); return bb; }
public void TestEncapsulatedSignerStoreReplacement() { MemoryStream bOut = new MemoryStream(); IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1); gen.AddCertificates(x509Certs); byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage); Stream sigOut = gen.Open(bOut, true); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); // // create new Signer // MemoryStream original = new MemoryStream(bOut.ToArray(), false); bOut.SetLength(0); gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha224); gen.AddCertificates(x509Certs); sigOut = gen.Open(bOut, true); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CmsSignedData sd = new CmsSignedData(bOut.ToArray()); // // replace signer // MemoryStream newOut = new MemoryStream(); CmsSignedDataParser.ReplaceSigners(original, sd.GetSignerInfos(), newOut); sd = new CmsSignedData(newOut.ToArray()); IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator(); signerEnum.MoveNext(); SignerInformation signer = (SignerInformation) signerEnum.Current; Assert.AreEqual(signer.DigestAlgOid, CmsSignedDataStreamGenerator.DigestSha224); CmsSignedDataParser sp = new CmsSignedDataParser(newOut.ToArray()); sp.GetSignedContent().Drain(); VerifySignatures(sp); }
public void TestUnsortedAttributes() { CmsSignedData s = new CmsSignedData(new CmsProcessableByteArray(disorderedMessage), disorderedSet); IX509Store x509Certs = s.GetCertificates("Collection"); SignerInformationStore signers = s.GetSignerInfos(); ICollection c = signers.GetSigners(); foreach (SignerInformation signer in c) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; Assert.IsTrue(signer.Verify(cert)); } }
public void TestSha1WithRsaEncapsulatedSubjectKeyID() { MemoryStream bOut = new MemoryStream(); IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, CmsTestUtil.CreateSubjectKeyId(OrigCert.GetPublicKey()).GetKeyIdentifier(), CmsSignedDataStreamGenerator.DigestSha1); gen.AddCertificates(x509Certs); byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage); Stream sigOut = gen.Open(bOut, true); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray()); sp.GetSignedContent().Drain(); VerifySignatures(sp); byte[] contentDigest = (byte[])gen.GetGeneratedDigests()[CmsSignedGenerator.DigestSha1]; ArrayList signers = new ArrayList(sp.GetSignerInfos().GetSigners()); AttributeTable table = ((SignerInformation) signers[0]).SignedAttributes; Asn1.Cms.Attribute hash = table[CmsAttributes.MessageDigest]; Assert.IsTrue(Arrays.AreEqual(contentDigest, ((Asn1OctetString)hash.AttrValues[0]).GetOctets())); // // try using existing signer // gen = new CmsSignedDataStreamGenerator(); gen.AddSigners(sp.GetSignerInfos()); // gen.AddCertificatesAndCRLs(sp.GetCertificatesAndCrls("Collection", "BC")); gen.AddCertificates(sp.GetCertificates("Collection")); bOut.SetLength(0); sigOut = gen.Open(bOut, true); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CmsSignedData sd = new CmsSignedData(new CmsProcessableByteArray(testBytes), bOut.ToArray()); Assert.AreEqual(1, sd.GetSignerInfos().GetSigners().Count); VerifyEncodedData(bOut); }
private CmsSignedData(CmsSignedData c) { this.signedData = c.signedData; this.contentInfo = c.contentInfo; this.signedContent = c.signedContent; this.signerInfoStore = c.signerInfoStore; }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData , SignerInformation si, SignatureParameters parameters, Document originalData) { if (this.signatureTsa == null) { throw new ConfigurationException(ConfigurationException.MSG.CONFIGURE_TSP_SERVER); } LOG.Info("Extend signature with id " + si.SignerID); BcCms.AttributeTable unsigned = si.UnsignedAttributes; //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = null; IDictionary unsignedAttrHash = null; if (unsigned == null) { unsignedAttrHash = new Dictionary<DerObjectIdentifier, Attribute>(); } else { unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); } //TODO jbonilla - ¿Qué ocurre si ya es CAdES-T? No se debería volver a extender. Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken , this.signatureTsa, digestAlgorithm, si.GetSignature()); //unsignedAttrHash.Put(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp); unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable (unsignedAttrHash)); return newsi; }
private CmsSignedData(CmsSignedData c) { signedData = c.signedData; contentInfo = c.contentInfo; signedContent = c.signedContent; signerInfoStore = c.signerInfoStore; }
private CmsSignedData( CmsSignedData c) { this.signedData = c.signedData; this.contentInfo = c.contentInfo; this.signedContent = c.signedContent; this.signerInfoStore = c.signerInfoStore; }
/** * Replace the signerinformation store associated with this * CmsSignedData object with the new one passed in. You would * probably only want to do this if you wanted to change the unsigned * attributes associated with a signer, or perhaps delete one. * * @param signedData the signed data object to be used as a base. * @param signerInformationStore the new signer information store to use. * @return a new signed data object. */ public static CmsSignedData ReplaceSigners( CmsSignedData signedData, SignerInformationStore signerInformationStore) { // // copy // CmsSignedData cms = new CmsSignedData(signedData); // // replace the store // cms.signerInfoStore = signerInformationStore; // // replace the signers in the SignedData object // Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector vec = new Asn1EncodableVector(); foreach (SignerInformation signer in signerInformationStore.GetSigners()) { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); vec.Add(signer.ToSignerInfo()); } Asn1Set digests = new DerSet(digestAlgs); Asn1Set signers = new DerSet(vec); Asn1Sequence sD = (Asn1Sequence)signedData.signedData.ToAsn1Object(); // // signers are the last item in the sequence. // vec = new Asn1EncodableVector( sD[0], // version digests); for (int i = 2; i != sD.Count - 1; i++) { vec.Add(sD[i]); } vec.Add(signers); cms.signedData = SignedData.GetInstance(new BerSequence(vec)); // // replace the contentInfo with the new one // cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData); return(cms); }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData cmsSignedData , SignerInformation si, SignatureParameters parameters, Document originalDocument ) { si = base.ExtendCMSSignature(cmsSignedData, si, parameters, originalDocument); CAdESSignature signature = new CAdESSignature(cmsSignedData, si); //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); Attribute archiveTimeStamp = GetTimeStampAttribute(CAdESProfileA.id_aa_ets_archiveTimestampV2 , GetSignatureTsa(), digestAlgorithm, signature.GetArchiveTimestampData(0, originalDocument )); //unsignedAttrHash.Put(CAdESProfileA.id_aa_ets_archiveTimestampV2, archiveTimeStamp); unsignedAttrHash.Add(CAdESProfileA.id_aa_ets_archiveTimestampV2, archiveTimeStamp); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new AttributeTable (unsignedAttrHash)); return newsi; }
public static CmsSignedData ReplaceSigners(CmsSignedData signedData, SignerInformationStore signerInformationStore) { CmsSignedData cmsSignedData = new CmsSignedData(signedData); cmsSignedData.signerInfoStore = signerInformationStore; Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]); Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(new Asn1Encodable[0]); foreach (SignerInformation signerInformation in signerInformationStore.GetSigners()) { asn1EncodableVector.Add(new Asn1Encodable[] { CmsSignedData.Helper.FixAlgID(signerInformation.DigestAlgorithmID) }); asn1EncodableVector2.Add(new Asn1Encodable[] { signerInformation.ToSignerInfo() }); } Asn1Set asn1Set = new DerSet(asn1EncodableVector); Asn1Set asn1Set2 = new DerSet(asn1EncodableVector2); Asn1Sequence asn1Sequence = (Asn1Sequence)signedData.signedData.ToAsn1Object(); asn1EncodableVector2 = new Asn1EncodableVector(new Asn1Encodable[] { asn1Sequence[0], asn1Set }); for (int num = 2; num != asn1Sequence.Count - 1; num++) { asn1EncodableVector2.Add(new Asn1Encodable[] { asn1Sequence[num] }); } asn1EncodableVector2.Add(new Asn1Encodable[] { asn1Set2 }); cmsSignedData.signedData = SignedData.GetInstance(new BerSequence(asn1EncodableVector2)); cmsSignedData.contentInfo = new ContentInfo(cmsSignedData.contentInfo.ContentType, cmsSignedData.signedData); return(cmsSignedData); }
public static CmsSignedData ReplaceCertificatesAndCrls(CmsSignedData signedData, IX509Store x509Certs, IX509Store x509Crls, IX509Store x509AttrCerts) { if (x509AttrCerts != null) { throw Platform.CreateNotImplementedException("Currently can't replace attribute certificates"); } CmsSignedData cmsSignedData = new CmsSignedData(signedData); Asn1Set certificates = null; try { Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList(CmsUtilities.GetCertificatesFromStore(x509Certs)); if (asn1Set.Count != 0) { certificates = asn1Set; } } catch (X509StoreException e) { throw new CmsException("error getting certificates from store", e); } Asn1Set crls = null; try { Asn1Set asn1Set2 = CmsUtilities.CreateBerSetFromList(CmsUtilities.GetCrlsFromStore(x509Crls)); if (asn1Set2.Count != 0) { crls = asn1Set2; } } catch (X509StoreException e2) { throw new CmsException("error getting CRLs from store", e2); } SignedData signedData2 = signedData.signedData; cmsSignedData.signedData = new SignedData(signedData2.DigestAlgorithms, signedData2.EncapContentInfo, certificates, crls, signedData2.SignerInfos); cmsSignedData.contentInfo = new ContentInfo(cmsSignedData.contentInfo.ContentType, cmsSignedData.signedData); return(cmsSignedData); }
public static CmsSignedData ReplaceSigners(CmsSignedData signedData, SignerInformationStore signerInformationStore) { CmsSignedData cmsSignedData = new CmsSignedData(signedData); cmsSignedData.signerInfoStore = signerInformationStore; Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(); global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)signerInformationStore.GetSigners()).GetEnumerator(); try { while (enumerator.MoveNext()) { SignerInformation signerInformation = (SignerInformation)enumerator.get_Current(); asn1EncodableVector.Add(Helper.FixAlgID(signerInformation.DigestAlgorithmID)); asn1EncodableVector2.Add(signerInformation.ToSignerInfo()); } } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } Asn1Set asn1Set = new DerSet(asn1EncodableVector); Asn1Set asn1Set2 = new DerSet(asn1EncodableVector2); Asn1Sequence asn1Sequence = (Asn1Sequence)signedData.signedData.ToAsn1Object(); asn1EncodableVector2 = new Asn1EncodableVector(asn1Sequence[0], asn1Set); for (int i = 2; i != asn1Sequence.Count - 1; i++) { asn1EncodableVector2.Add(asn1Sequence[i]); } asn1EncodableVector2.Add(asn1Set2); cmsSignedData.signedData = SignedData.GetInstance(new BerSequence(asn1EncodableVector2)); cmsSignedData.contentInfo = new ContentInfo(cmsSignedData.contentInfo.ContentType, cmsSignedData.signedData); return(cmsSignedData); }
public byte[] Sign(byte[] cmsData) { IList certs = new List<X509Certificate>(); byte[] signBytes = File.ReadAllBytes(GetFile()); X509Certificate2 signCert = new X509Certificate2(signBytes, Key, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable); certs.Add(DotNetUtilities.FromX509Certificate(signCert)); IX509Store x509Certs = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); AsymmetricCipherKeyPair pair = DotNetUtilities.GetKeyPair(signCert.PrivateKey); X509Certificate bX509Certificate = DotNetUtilities.FromX509Certificate(signCert); gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha1); gen.AddSigner(pair.Private, bX509Certificate, CmsSignedGenerator.DigestSha256); CmsSignedData unsignedData = new CmsSignedData(cmsData); gen.AddCertificates(x509Certs); CmsProcessable msg = new CmsProcessableByteArray(unsignedData.GetEncoded()); CmsSignedData cmsSignedData = gen.Generate(CmsSignedGenerator.Data, msg, true); byte[] p7MData = cmsSignedData.GetEncoded(); return p7MData; }
/** * Replace the certificate and CRL information associated with this * CmsSignedData object with the new one passed in. * * @param signedData the signed data object to be used as a base. * @param x509Certs the new certificates to be used. * @param x509Crls the new CRLs to be used. * @return a new signed data object. * @exception CmsException if there is an error processing the stores */ public static CmsSignedData ReplaceCertificatesAndCrls( CmsSignedData signedData, IX509Store x509Certs, IX509Store x509Crls, IX509Store x509AttrCerts) { if (x509AttrCerts != null) throw Platform.CreateNotImplementedException("Currently can't replace attribute certificates"); // // copy // CmsSignedData cms = new CmsSignedData(signedData); // // replace the certs and crls in the SignedData object // Asn1Set certs = null; try { Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( CmsUtilities.GetCertificatesFromStore(x509Certs)); if (asn1Set.Count != 0) { certs = asn1Set; } } catch (X509StoreException e) { throw new CmsException("error getting certificates from store", e); } Asn1Set crls = null; try { Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( CmsUtilities.GetCrlsFromStore(x509Crls)); if (asn1Set.Count != 0) { crls = asn1Set; } } catch (X509StoreException e) { throw new CmsException("error getting CRLs from store", e); } // // replace the CMS structure. // SignedData old = signedData.signedData; cms.signedData = new SignedData( old.DigestAlgorithms, old.EncapContentInfo, certs, crls, old.SignerInfos); // // replace the contentInfo with the new one // cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData); return cms; }
private void VerifySignatures( CmsSignedData s) { VerifySignatures(s, null); }
private void doTestSample( string messageName, string sigName) { CmsSignedData sig = new CmsSignedData( new CmsProcessableByteArray(GetInput(messageName)), GetInput(sigName)); VerifySignatures(sig); }
public static void foo() { byte[] sigBlock = null; Org.BouncyCastle.Cms.CmsSignedData c = new Org.BouncyCastle.Cms.CmsSignedData(sigBlock); }
private void doTestSample( string sigName) { CmsSignedData sig = new CmsSignedData(GetInput(sigName)); VerifySignatures(sig); }
// // signerInformation store replacement test. // private void CheckSignerStoreReplacement( CmsSignedData orig, SignerInformationStore signers) { CmsSignedData s = CmsSignedData.ReplaceSigners(orig, signers); IX509Store x509Certs = s.GetCertificates("Collection"); signers = s.GetSignerInfos(); ICollection c = signers.GetSigners(); foreach (SignerInformation signer in c) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; Assert.IsTrue(signer.Verify(cert)); } }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData , SignerInformation si, SignatureParameters parameters, Document originalData) { si = base.ExtendCMSSignature(signedData, si, parameters, originalData); //IDictionary<DerObjectIdentifier, Asn1Encodable> unsignedAttrs = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrs = si.UnsignedAttributes.ToDictionary(); CAdESSignature signature = new CAdESSignature(signedData, si.SignerID); DateTime signingTime = signature.GetSigningTime().Value; if (signingTime == null) { signingTime = parameters.SigningDate; } if (signingTime == null) { signingTime = DateTime.Now; } unsignedAttrs = ExtendUnsignedAttributes(unsignedAttrs, signature.GetSigningCertificate (), signingTime, signature.GetCertificateSource()); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable (unsignedAttrs)); return newsi; }
/** * Replace the signerinformation store associated with this * CmsSignedData object with the new one passed in. You would * probably only want to do this if you wanted to change the unsigned * attributes associated with a signer, or perhaps delete one. * * @param signedData the signed data object to be used as a base. * @param signerInformationStore the new signer information store to use. * @return a new signed data object. */ public static CmsSignedData ReplaceSigners( CmsSignedData signedData, SignerInformationStore signerInformationStore) { // // copy // CmsSignedData cms = new CmsSignedData(signedData); // // replace the store // cms.signerInfoStore = signerInformationStore; // // replace the signers in the SignedData object // Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); Asn1EncodableVector vec = new Asn1EncodableVector(); foreach (SignerInformation signer in signerInformationStore.GetSigners()) { digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); vec.Add(signer.ToSignerInfo()); } Asn1Set digests = new DerSet(digestAlgs); Asn1Set signers = new DerSet(vec); Asn1Sequence sD = (Asn1Sequence)signedData.signedData.ToAsn1Object(); // // signers are the last item in the sequence. // vec = new Asn1EncodableVector( sD[0], // version digests); for (int i = 2; i != sD.Count - 1; i++) { vec.Add(sD[i]); } vec.Add(signers); cms.signedData = SignedData.GetInstance(new BerSequence(vec)); // // replace the contentInfo with the new one // cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData); return cms; }
public void TestDetachedVerification() { byte[] data = Encoding.ASCII.GetBytes("Hello World!"); CmsProcessable msg = new CmsProcessableByteArray(data); IList certList = new ArrayList(); certList.Add(OrigCert); certList.Add(SignCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestMD5); gen.AddCertificates(x509Certs); CmsSignedData s = gen.Generate(msg); IDictionary hashes = new Hashtable(); hashes.Add(CmsSignedDataGenerator.DigestSha1, CalculateHash("SHA1", data)); hashes.Add(CmsSignedDataGenerator.DigestMD5, CalculateHash("MD5", data)); s = new CmsSignedData(hashes, s.GetEncoded()); VerifySignatures(s, null); }
public void TestSha1WithRsaAndAttributeTable() { byte[] testBytes = Encoding.ASCII.GetBytes("Hello world!"); IList certList = new ArrayList(); CmsProcessable msg = new CmsProcessableByteArray(testBytes); certList.Add(OrigCert); certList.Add(SignCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); IDigest md = DigestUtilities.GetDigest("SHA1"); md.BlockUpdate(testBytes, 0, testBytes.Length); byte[] hash = DigestUtilities.DoFinal(md); Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest, new DerSet(new DerOctetString(hash))); Asn1EncodableVector v = new Asn1EncodableVector(attr); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1, new AttributeTable(v), null); gen.AddCertificates(x509Certs); CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, null, false); // // the signature is detached, so need to add msg before passing on // s = new CmsSignedData(msg, s.GetEncoded()); // // compute expected content digest // VerifySignatures(s, hash); }
/** * Replace the certificate and CRL information associated with this * CmsSignedData object with the new one passed in. * * @param signedData the signed data object to be used as a base. * @param x509Certs the new certificates to be used. * @param x509Crls the new CRLs to be used. * @return a new signed data object. * @exception CmsException if there is an error processing the stores */ public static CmsSignedData ReplaceCertificatesAndCrls( CmsSignedData signedData, IX509Store x509Certs, IX509Store x509Crls, IX509Store x509AttrCerts) { if (x509AttrCerts != null) { throw Platform.CreateNotImplementedException("Currently can't replace attribute certificates"); } // // copy // CmsSignedData cms = new CmsSignedData(signedData); // // replace the certs and crls in the SignedData object // Asn1Set certs = null; try { Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( CmsUtilities.GetCertificatesFromStore(x509Certs)); if (asn1Set.Count != 0) { certs = asn1Set; } } catch (X509StoreException e) { throw new CmsException("error getting certificates from store", e); } Asn1Set crls = null; try { Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList( CmsUtilities.GetCrlsFromStore(x509Crls)); if (asn1Set.Count != 0) { crls = asn1Set; } } catch (X509StoreException e) { throw new CmsException("error getting CRLs from store", e); } // // replace the CMS structure. // SignedData old = signedData.signedData; cms.signedData = new SignedData( old.DigestAlgorithms, old.EncapContentInfo, certs, crls, old.SignerInfos); // // replace the contentInfo with the new one // cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData); return(cms); }
public void TestNullContentWithSigner() { IList certList = new ArrayList(); certList.Add(OrigCert); certList.Add(SignCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddCertificates(x509Certs); CmsSignedData s = gen.Generate(null, false); s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded()))); VerifySignatures(s); }
public void TestSha1AndMD5WithRsaEncapsulatedRepeated() { IList certList = new ArrayList(); CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); certList.Add(OrigCert); certList.Add(SignCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestMD5); gen.AddCertificates(x509Certs); CmsSignedData s = gen.Generate(msg, true); s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded()))); x509Certs = s.GetCertificates("Collection"); SignerInformationStore signers = s.GetSignerInfos(); Assert.AreEqual(2, signers.Count); SignerID sid = null; ICollection c = signers.GetSigners(); foreach (SignerInformation signer in c) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; sid = signer.SignerID; Assert.IsTrue(signer.Verify(cert)); // // check content digest // byte[] contentDigest = (byte[])gen.GetGeneratedDigests()[signer.DigestAlgOid]; AttributeTable table = signer.SignedAttributes; Asn1.Cms.Attribute hash = table[CmsAttributes.MessageDigest]; Assert.IsTrue(Arrays.AreEqual(contentDigest, ((Asn1OctetString)hash.AttrValues[0]).GetOctets())); } c = signers.GetSigners(sid); Assert.AreEqual(2, c.Count); // // try using existing signer // gen = new CmsSignedDataGenerator(); gen.AddSigners(s.GetSignerInfos()); gen.AddCertificates(s.GetCertificates("Collection")); gen.AddCrls(s.GetCrls("Collection")); s = gen.Generate(msg, true); s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded()))); x509Certs = s.GetCertificates("Collection"); signers = s.GetSignerInfos(); c = signers.GetSigners(); Assert.AreEqual(2, c.Count); foreach (SignerInformation signer in c) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; Assert.AreEqual(true, signer.Verify(cert)); } CheckSignerStoreReplacement(s, signers); }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData , SignerInformation si, SignatureParameters parameters, Document originalData) { si = base.ExtendCMSSignature(signedData, si, parameters, originalData); DerObjectIdentifier attributeId = null; ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); switch (GetExtendedValidationType()) { case 1: { attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp; toTimestamp.Write(si.GetSignature()); // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5, // NOTE 2) toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] .AttrValues.GetDerEncoded()); break; } case 2: { attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp; break; } default: { throw new InvalidOperationException("CAdES-X Profile: Extended validation is set but no valid type (1 or 2)" ); } } toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs] .AttrValues.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs] .AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs] .AttrValues.GetDerEncoded()); //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, GetSignatureTsa( ), digestAlgorithm, toTimestamp.ToByteArray()); //unsignedAttrHash.Put(attributeId, extendedTimeStamp); unsignedAttrHash.Add(attributeId, extendedTimeStamp); return SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash )); }