public AddSigner ( |
||
privateKey | ||
cert | ||
digestOID | string | |
return | void |
/// <summary> /// Signiert die Daten mit dem angegebenen Absender-Zertifikat /// </summary> /// <param name="data">Die zu signierenden Daten</param> /// <param name="privateKey">Der private Schlüssel mit dem signiert werden soll (passend zum Zeritifikat <paramref name="cert"/>)</param> /// <param name="cert">Das Absender-Zertifikat</param> /// <param name="certs">Die Zertifikate, die zusätzlich im Ergebnis gespeichert werden sollen (z.B. für eine Zertifkatskette)</param> /// <returns>Die signierten Daten</returns> public static byte[] SignData(byte[] data, AsymmetricKeyParameter privateKey, X509Certificate cert, IEnumerable<X509Certificate> certs = null) { var gen = new CmsSignedDataGenerator(); var allCerts = new List<X509Certificate>(); if (certs != null) allCerts.AddRange(certs); var storeParams = new X509CollectionStoreParameters(allCerts); var certStore = X509StoreFactory.Create("Certificate/Collection", storeParams); gen.AddCertificates(certStore); gen.AddSigner(privateKey, cert, NistObjectIdentifiers.IdSha256.Id); var message = new CmsProcessableByteArray(data); var signedData = gen.Generate(message, true); return signedData.GetEncoded(); }
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; }
public void TestSignerStoreReplacement() { 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.AddCertificates(x509Certs); CmsSignedData original = gen.Generate(msg, true); // // create new Signer // gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha224); gen.AddCertificates(x509Certs); CmsSignedData newSD = gen.Generate(msg, true); // // replace signer // CmsSignedData sd = CmsSignedData.ReplaceSigners(original, newSD.GetSignerInfos()); IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator(); signerEnum.MoveNext(); SignerInformation signer = (SignerInformation) signerEnum.Current; Assert.AreEqual(CmsSignedDataGenerator.DigestSha224, signer.DigestAlgOid); // we use a parser here as it requires the digests to be correct in the digest set, if it // isn't we'll get a NullPointerException CmsSignedDataParser sp = new CmsSignedDataParser(sd.GetEncoded()); sp.GetSignedContent().Drain(); VerifySignatures(sp); }
private void SignManigestFile(PassGeneratorRequest request, string manifestFileAndPath) { byte[] dataToSign = File.ReadAllBytes(manifestFileAndPath); X509Certificate2 card = GetCertificate(request); Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card); Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private; X509Certificate2 appleCA = GetAppleCertificate(); Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA); ArrayList intermediateCerts = new ArrayList(); intermediateCerts.Add(appleCert); intermediateCerts.Add(cert); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1); generator.AddCertificates(st1); CmsProcessable content = new CmsProcessableByteArray(dataToSign); CmsSignedData signedData = generator.Generate(content, false); string outputDirectory = Path.GetDirectoryName(manifestFileAndPath); string signatureFileAndPath = Path.Combine(outputDirectory, "signature"); File.WriteAllBytes(signatureFileAndPath, signedData.GetEncoded()); }
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); }
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 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); }
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 rsaPssTest( string digestName, string digestOID) { byte[] msgBytes = Encoding.ASCII.GetBytes("Hello World!"); CmsProcessable msg = new CmsProcessableByteArray(msgBytes); IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.EncryptionRsaPss, digestOID); gen.AddCertificates(x509Certs); CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, msg, false); // compute expected content digest byte[] expectedDigest = DigestUtilities.CalculateDigest(digestName, msgBytes); VerifySignatures(s, expectedDigest); }
public void TestSha1WithRsaAndAttributeTable() { byte[] testBytes = Encoding.ASCII.GetBytes("Hello world!"); CmsProcessable msg = new CmsProcessableByteArray(testBytes); IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); byte[] hash = DigestUtilities.CalculateDigest("SHA1", testBytes); Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest, new DerSet(new DerOctetString(hash))); Asn1EncodableVector v = new Asn1EncodableVector(attr); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(SignKP.Private, SignCert, 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); }
public void TestDetachedVerification() { byte[] data = Encoding.ASCII.GetBytes("Hello World!"); CmsProcessable msg = new CmsProcessableByteArray(data); IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); 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, DigestUtilities.CalculateDigest("SHA1", data)); hashes.Add(CmsSignedDataGenerator.DigestMD5, DigestUtilities.CalculateDigest("MD5", data)); s = new CmsSignedData(hashes, s.GetEncoded()); VerifySignatures(s, null); }
public void TestCertOrdering2() { CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); IX509Store x509Certs = CmsTestUtil.MakeCertStore(SignCert, SignDsaCert, OrigCert); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddCertificates(x509Certs); CmsSignedData sd = gen.Generate(msg, true); x509Certs = sd.GetCertificates("Collection"); ArrayList a = new ArrayList(x509Certs.GetMatches(null)); Assert.AreEqual(3, a.Count); Assert.AreEqual(SignCert, a[0]); Assert.AreEqual(SignDsaCert, a[1]); Assert.AreEqual(OrigCert, a[2]); }
public void TestEncapsulatedCertStoreReplacement() { CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); IX509Store x509Certs = CmsTestUtil.MakeCertStore(SignDsaCert); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddCertificates(x509Certs); CmsSignedData sd = gen.Generate(msg, true); // // create new certstore // x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); // // replace certs // sd = CmsSignedData.ReplaceCertificatesAndCrls(sd, x509Certs, null, null); VerifySignatures(sd); }
public void TestNullContentWithSigner() { IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); 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); }
/// <exception cref="System.IO.IOException"></exception> //private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ContentSigner contentSigner // , DigestCalculatorProvider digestCalculatorProvider, SignatureParameters parameters // , CAdESProfileBES cadesProfile, bool includeUnsignedAttributes, CmsSignedData originalSignedData // ) private CmsSignedDataGenerator CreateCMSSignedDataGenerator(ISigner signer , SignatureParameters parameters, CAdESProfileBES cadesProfile , bool includeUnsignedAttributes, CmsSignedData originalSignedData ) { try { CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); X509Certificate signerCertificate = parameters.SigningCertificate; //X509CertificateHolder certHolder = new X509CertificateHolder(signerCertificate.GetEncoded()); ArrayList certList = new ArrayList(); certList.Add(signerCertificate); IX509Store certHolder = X509StoreFactory.Create("CERTIFICATE/COLLECTION", new X509CollectionStoreParameters(certList)); //jbonilla - El provider siempre es BC C# //SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder // (digestCalculatorProvider); CmsAttributeTableGenerator signedAttrGen = new DefaultSignedAttributeTableGenerator (new AttributeTable(cadesProfile.GetSignedAttributes(parameters))); CmsAttributeTableGenerator unsignedAttrGen = new SimpleAttributeTableGenerator ((includeUnsignedAttributes) ? new AttributeTable(cadesProfile.GetUnsignedAttributes (parameters)) : null); //jbonilla - No existe ContentSigner en BC C# //SignerInfoGenerator sigInfoGen = sigInfoGeneratorBuilder.Build(contentSigner, certHolder); //generator.AddSignerInfoGenerator(sigInfoGen); generator.SignerProvider = signer; generator.AddSigner(new NullPrivateKey(), signerCertificate, parameters.SignatureAlgorithm.GetOid() , parameters.DigestAlgorithm.GetOid(), signedAttrGen, unsignedAttrGen); if (originalSignedData != null) { generator.AddSigners(originalSignedData.GetSignerInfos()); } //ICollection<X509Certificate> certs = new AList<X509Certificate>(); IList certs = new ArrayList(); //certs.AddItem(parameters.SigningCertificate); certs.Add(parameters.SigningCertificate); if (parameters.CertificateChain != null) { foreach (X509Certificate c in parameters.CertificateChain) { if (!c.SubjectDN.Equals(parameters.SigningCertificate.SubjectDN)) { //certs.AddItem(c); certs.Add(c); } } } //JcaCertStore certStore = new JcaCertStore(certs); IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); generator.AddCertificates(certStore); if (originalSignedData != null) { generator.AddCertificates(originalSignedData.GetCertificates("Collection")); } return generator; } catch (CmsException e) { throw new IOException("CmsException", e); } catch (CertificateEncodingException e) { throw new IOException("CertificateEncodingException", e); } /*catch (OperatorCreationException e) { throw new IOException(e); }*/ }
public void TestWithAttributeCertificate() { IList certList = new ArrayList(); CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); certList.Add(SignDsaCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddCertificates(x509Certs); IX509AttributeCertificate attrCert = CmsTestUtil.GetAttributeCertificate(); ArrayList attrCerts = new ArrayList(); attrCerts.Add(attrCert); IX509Store store = X509StoreFactory.Create( "AttributeCertificate/Collection", new X509CollectionStoreParameters(attrCerts)); gen.AddAttributeCertificates(store); CmsSignedData sd = gen.Generate(msg); Assert.AreEqual(4, sd.Version); store = sd.GetAttributeCertificates("Collection"); ArrayList coll = new ArrayList(store.GetMatches(null)); Assert.AreEqual(1, coll.Count); Assert.IsTrue(coll.Contains(attrCert)); // // create new certstore // certList = new ArrayList(); certList.Add(OrigCert); certList.Add(SignCert); x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // // replace certs // sd = CmsSignedData.ReplaceCertificatesAndCrls(sd, x509Certs, null, null); VerifySignatures(sd); }
private void rsaPssTest( string digestName, string digestOID) { IList certList = new ArrayList(); byte[] msgBytes = Encoding.ASCII.GetBytes("Hello World!"); CmsProcessable msg = new CmsProcessableByteArray(msgBytes); 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.EncryptionRsaPss, digestOID); gen.AddCertificates(x509Certs); CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, msg, false); // // compute expected content digest // IDigest md = DigestUtilities.GetDigest(digestName); md.BlockUpdate(msgBytes, 0, msgBytes.Length); byte[] expectedDigest = DigestUtilities.DoFinal(md); VerifySignatures(s, expectedDigest); }
private void EncapsulatedTest( AsymmetricCipherKeyPair signaturePair, X509Certificate signatureCert, string digestAlgorithm) { CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); IX509Store x509Certs = CmsTestUtil.MakeCertStore(signatureCert, OrigCert); IX509Store x509Crls = CmsTestUtil.MakeCrlStore(SignCrl); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(signaturePair.Private, signatureCert, digestAlgorithm); gen.AddCertificates(x509Certs); gen.AddCrls(x509Crls); CmsSignedData s = gen.Generate(msg, true); s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded()))); x509Certs = s.GetCertificates("Collection"); x509Crls = s.GetCrls("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.AreEqual(digestAlgorithm, signer.DigestAlgOid); 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); s = new CmsSignedData(ContentInfo.GetInstance(Asn1Object.FromByteArray(s.GetEncoded()))); x509Certs = s.GetCertificates("Collection"); x509Crls = s.GetCrls("Collection"); signers = s.GetSignerInfos(); 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)); } CheckSignerStoreReplacement(s, signers); }
public void TestCertOrdering2() { IList certList = new ArrayList(); CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); certList.Add(SignCert); certList.Add(SignDsaCert); certList.Add(OrigCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddCertificates(x509Certs); CmsSignedData sd = gen.Generate(msg, true); x509Certs = sd.GetCertificates("Collection"); ArrayList a = new ArrayList(x509Certs.GetMatches(null)); Assert.AreEqual(3, a.Count); Assert.AreEqual(SignCert, a[0]); Assert.AreEqual(SignDsaCert, a[1]); Assert.AreEqual(OrigCert, a[2]); }
private void SignManigestFile(PassGeneratorRequest request) { Trace.TraceInformation("Signing the manifest file..."); X509Certificate2 card = GetCertificate(request); if (card == null) { throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct."); } try { Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card); Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private; Trace.TraceInformation("Fetching Apple Certificate for signing.."); X509Certificate2 appleCA = GetAppleCertificate(request); Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA); Trace.TraceInformation("Constructing the certificate chain.."); ArrayList intermediateCerts = new ArrayList(); intermediateCerts.Add(appleCert); intermediateCerts.Add(cert); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1); generator.AddCertificates(st1); Trace.TraceInformation("Processing the signature.."); CmsProcessable content = new CmsProcessableByteArray(manifestFile); CmsSignedData signedData = generator.Generate(content, false); signatureFile = signedData.GetEncoded(); Trace.TraceInformation("The file has been successfully signed!"); } catch (Exception exp) { Trace.TraceError("Failed to sign the manifest file: [{0}]", exp.Message); throw new ManifestSigningException("Failed to sign manifest", exp); } }
public void TestEncapsulatedCertStoreReplacement() { IList certList = new ArrayList(); CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); certList.Add(SignDsaCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataGenerator gen = new CmsSignedDataGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1); gen.AddCertificates(x509Certs); CmsSignedData sd = gen.Generate(msg, true); // // create new certstore // certList = new ArrayList(); certList.Add(OrigCert); certList.Add(SignCert); x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); // // replace certs // sd = CmsSignedData.ReplaceCertificatesAndCrls(sd, x509Certs, null, null); VerifySignatures(sd); }
//------------------------------------------------------------------------------ public TimeStampToken Generate( TimeStampRequest request, BigInteger serialNumber, DateTime genTime) { DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid); AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance); MessageImprint messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest()); Accuracy accuracy = null; if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0) { DerInteger seconds = null; if (accuracySeconds > 0) { seconds = new DerInteger(accuracySeconds); } DerInteger millis = null; if (accuracyMillis > 0) { millis = new DerInteger(accuracyMillis); } DerInteger micros = null; if (accuracyMicros > 0) { micros = new DerInteger(accuracyMicros); } accuracy = new Accuracy(seconds, millis, micros); } DerBoolean derOrdering = null; if (ordering) { derOrdering = DerBoolean.GetInstance(ordering); } DerInteger nonce = null; if (request.Nonce != null) { nonce = new DerInteger(request.Nonce); } DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID); if (request.ReqPolicy != null) { tsaPolicy = new DerObjectIdentifier(request.ReqPolicy); } TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint, new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy, derOrdering, nonce, tsa, request.Extensions); try { CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator(); byte[] derEncodedTstInfo = tstInfo.GetDerEncoded(); if (request.CertReq) { signedDataGenerator.AddCertificates(x509Certs); } signedDataGenerator.AddCrls(x509Crls); signedDataGenerator.AddSigner(key, cert, digestOID, signedAttr, unsignedAttr); CmsSignedData signedData = signedDataGenerator.Generate( PkcsObjectIdentifiers.IdCTTstInfo.Id, new CmsProcessableByteArray(derEncodedTstInfo), true); return new TimeStampToken(signedData); } catch (CmsException cmsEx) { throw new TspException("Error generating time-stamp token", cmsEx); } catch (IOException e) { throw new TspException("Exception encoding info", e); } catch (X509StoreException e) { throw new TspException("Exception handling CertStore", e); } // catch (InvalidAlgorithmParameterException e) // { // throw new TspException("Exception handling CertStore CRLs", e); // } }
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); }
private void SignManigestFile(PassGeneratorRequest request) { X509Certificate2 card = GetCertificate(request); if (card == null) { throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct."); } Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(card); Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = DotNetUtilities.GetKeyPair(card.PrivateKey).Private; X509Certificate2 appleCA = GetAppleCertificate(request); Org.BouncyCastle.X509.X509Certificate appleCert = DotNetUtilities.FromX509Certificate(appleCA); ArrayList intermediateCerts = new ArrayList(); intermediateCerts.Add(appleCert); intermediateCerts.Add(cert); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(intermediateCerts); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); CmsSignedDataGenerator generator = new CmsSignedDataGenerator(); generator.AddSigner(privateKey, cert, CmsSignedDataGenerator.DigestSha1); generator.AddCertificates(st1); CmsProcessable content = new CmsProcessableByteArray(manifestFile); CmsSignedData signedData = generator.Generate(content, false); signatureFile = signedData.GetEncoded(); }
public void TestSha1WithRsaCounterSignature() { IList certList = new ArrayList(); IList crlList = new ArrayList(); CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!")); certList.Add(SignCert); 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(SignKP.Private, SignCert, CmsSignedDataGenerator.DigestSha1); gen.AddCertificates(x509Certs); gen.AddCrls(x509Crls); CmsSignedData s = gen.Generate(msg, true); SignerInformation origSigner = (SignerInformation) new ArrayList(s.GetSignerInfos().GetSigners())[0]; SignerInformationStore counterSigners1 = gen.GenerateCounterSigners(origSigner); SignerInformationStore counterSigners2 = gen.GenerateCounterSigners(origSigner); SignerInformation signer1 = SignerInformation.AddCounterSigners(origSigner, counterSigners1); SignerInformation signer2 = SignerInformation.AddCounterSigners(signer1, counterSigners2); SignerInformationStore cs = signer2.GetCounterSignatures(); ICollection csSigners = cs.GetSigners(); Assert.AreEqual(2, csSigners.Count); foreach (SignerInformation cSigner in csSigners) { ICollection certCollection = x509Certs.GetMatches(cSigner.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate) certEnum.Current; Assert.IsNull(cSigner.SignedAttributes[Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtContentType]); Assert.IsTrue(cSigner.Verify(cert)); } }
private static byte[] SignData(byte[] data, Pkcs12Store signCertificate, DateTime? requestTimestamp = null) { var signCertAlias = signCertificate.Aliases.Cast<string>().First(signCertificate.IsKeyEntry); var signCertEntry = signCertificate.GetCertificate(signCertAlias); var signCert = signCertEntry.Certificate; var signPkEntry = signCertificate.GetKey(signCertAlias); var signPk = signPkEntry.Key; string digestName; if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id) { digestName = "SHA1"; } else if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id) { digestName = "SHA256"; } else { throw new ExtraException($"Unsupported digest algorithm {signCert.SigAlgName}"); } var digestOid = DigestUtilities.GetObjectIdentifier(digestName).Id; var digest = DigestUtilities.CalculateDigest(digestName, data); var signedAttrs = new Dictionary<object, object>() { { CmsAttributeTableParameter.Digest, digest } }; if (requestTimestamp.HasValue) { var signTimestamp = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(requestTimestamp.Value.ToUniversalTime()))); signedAttrs.Add(signTimestamp.AttrType, signTimestamp); } var signedAttrGen = new DefaultSignedAttributeTableGenerator(); var signedAttrTable = signedAttrGen.GetAttributes(signedAttrs); var generator = new CmsSignedDataGenerator(); generator.AddSigner(signPk, signCert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttrTable), null); var signedData = generator.Generate(new CmsProcessableByteArray(data), true); return signedData.GetEncoded(); }