private void VerifySignatures(CmsSignedData s, byte[] contentDigest) { IX509Store x509Certs = s.GetCertificates("Collection"); IX509Store 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; VerifySigner(signer, cert); if (contentDigest != null) { Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest())); } } ICollection certColl = x509Certs.GetMatches(null); ICollection crlColl = x509Crls.GetMatches(null); Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count); Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count); }
public static bool VerifySignatures(FileInfo contentFile, Stream signedDataStream) { CmsProcessable signedContent = null; CmsSignedData cmsSignedData = null; Org.BouncyCastle.X509.Store.IX509Store store = null; ICollection signers = null; bool verifiedStatus = false; try { //Org.BouncyCastle.Security.addProvider(new BouncyCastleProvider()); signedContent = new CmsProcessableFile(contentFile); cmsSignedData = new CmsSignedData(signedContent, signedDataStream); store = cmsSignedData.GetCertificates("Collection");//.getCertificates(); IX509Store certStore = cmsSignedData.GetCertificates("Collection"); signers = cmsSignedData.GetSignerInfos().GetSigners(); foreach (var item in signers) { SignerInformation signer = (SignerInformation)item; var certCollection = certStore.GetMatches(signer.SignerID); IEnumerator iter = certCollection.GetEnumerator(); iter.MoveNext(); var cert = (Org.BouncyCastle.X509.X509Certificate)iter.Current; verifiedStatus = signer.Verify(cert.GetPublicKey()); } } catch (Exception e) { throw e; } return(verifiedStatus); }
public static void ReadXmlSigned(this Fattura fattura, Stream stream, bool validateSignature = true) { CmsSignedData signedFile = new CmsSignedData(stream); if (validateSignature) { IX509Store certStore = signedFile.GetCertificates("Collection"); ICollection certs = certStore.GetMatches(new X509CertStoreSelector()); SignerInformationStore signerStore = signedFile.GetSignerInfos(); ICollection signers = signerStore.GetSigners(); foreach (object tempCertification in certs) { Org.BouncyCastle.X509.X509Certificate certification = tempCertification as Org.BouncyCastle.X509.X509Certificate; foreach (object tempSigner in signers) { SignerInformation signer = tempSigner as SignerInformation; if (!signer.Verify(certification.GetPublicKey())) { throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.SignatureException); } } } } using (var memoryStream = new MemoryStream()) { signedFile.SignedContent.Write(memoryStream); fattura.ReadXml(memoryStream); } }
public static IList GetCrlsFromStore( IX509Store crlStore) { try { IList crls = Platform.CreateArrayList(); if (crlStore != null) { foreach (X509Crl c in crlStore.GetMatches(null)) { crls.Add( CertificateList.GetInstance( Asn1Object.FromByteArray(c.GetEncoded()))); } } return(crls); } catch (CrlException e) { throw new CmsException("error encoding crls", e); } catch (Exception e) { throw new CmsException("error processing crls", e); } }
public static IList GetCertificatesFromStore( IX509Store certStore) { try { IList certs = new ArrayList(); if (certStore != null) { foreach (X509Certificate c in certStore.GetMatches(null)) { certs.Add( X509CertificateStructure.GetInstance( Asn1Object.FromByteArray(c.GetEncoded()))); } } return certs; } catch (CertificateEncodingException e) { throw new CmsException("error encoding certs", e); } catch (Exception e) { throw new CmsException("error processing certs", e); } }
internal X509Certificate GenerateCertificate(String certificateString) { X509Certificate x509Certificate = null; try { byte[] bytes = Convert.FromBase64CharArray(certificateString.ToCharArray(), 0, certificateString.Length); CmsSignedData cmsSignedData = new CmsSignedData(bytes); IX509Store store = cmsSignedData.GetCertificates("Collection"); ICollection allCertificates = store.GetMatches(null); IEnumerator enumerator = allCertificates.GetEnumerator(); while (enumerator.MoveNext()) { x509Certificate = (X509Certificate)enumerator.Current; Console.WriteLine("Server Generated Certificate: " + x509Certificate.ToString()); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Certificate generation error: " + ex); throw new Exception("Certificate generation error"); } return(x509Certificate); }
/// <returns>The first element in the returned list will be the leaf, and the last will be the root certificate</returns> public static List <X509Certificate> GetCertificateChain(IX509Store certificateStore, SignerID signerID) { X509Certificate parent = null; List <X509Certificate> chain = new List <X509Certificate>(); SignerID nextSignerID = signerID; do { ICollection matches = certificateStore.GetMatches(nextSignerID); foreach (X509Certificate certificate in matches) { parent = certificate; nextSignerID = new SignerID(); nextSignerID.Subject = certificate.IssuerDN; break; } chain.Add(parent); }while (parent != null && !parent.IssuerDN.Equivalent(parent.SubjectDN)); if (parent != null) { return(chain); } else { return(null); } }
public void TestCertOrdering2() { IList certList = new ArrayList(); MemoryStream bOut = new MemoryStream(); certList.Add(SignCert); certList.Add(OrigCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1); gen.AddCertificates(x509Certs); Stream sigOut = gen.Open(bOut, true); byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray()); sp.GetSignedContent().Drain(); x509Certs = sp.GetCertificates("Collection"); ArrayList a = new ArrayList(x509Certs.GetMatches(null)); Assert.AreEqual(2, a.Count); Assert.AreEqual(SignCert, a[0]); Assert.AreEqual(OrigCert, a[1]); }
private static X509Certificate GetCertificate(SignerInformation signer, IX509Store cmsCertificates) { X509Certificate cert = null; // Create a selector with the information necessary to // find the signer certificate X509CertStoreSelector sel = new X509CertStoreSelector(); sel.Issuer = signer.SignerID.Issuer; sel.SerialNumber = signer.SignerID.SerialNumber; // Try find a match IList certificatesFound = new ArrayList( cmsCertificates.GetMatches(sel) ); if (certificatesFound.Count > 0) // Match found { // Load certificate from CMS Console.WriteLine("Loading signer's certificate from CMS..."); cert = (X509Certificate)certificatesFound[0]; } else { // Load certificate from file Console.WriteLine("Loading signer's certificate from file..."); ReadCertificate("..\\..\\example.cer"); } return cert; }
private static BC::X509Certificate GetSigner(this TimeStampToken tst, X509Certificate2Collection extraStore) { //Get the info from the token IEnumerator signers = tst.GetCertificates("Collection").GetMatches(tst.SignerID).GetEnumerator(); //Get the one and only one signer if (signers.MoveNext()) { return((BC::X509Certificate)signers.Current); } //No signer found, lets try the extra store List <BC::X509Certificate> bcExtraList = extraStore.Cast <X509Certificate2>() .Select(c => DotNetUtilities.FromX509Certificate(c)) .ToList(); IX509Store bcExtraStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(bcExtraList)); signers = bcExtraStore.GetMatches(tst.SignerID).GetEnumerator(); if (signers.MoveNext()) { return((BC::X509Certificate)signers.Current); } return(null); }
/// <summary> /// Devuelve una lista con los certificados contenidos en un almacén de certificados /// </summary> /// <param name="certStore"></param> /// <returns></returns> private IList GetCertificatesFromStore(IX509Store certStore) { try { IList certs = new List <object>(); if (certStore != null) { foreach (X509Certificate c in certStore.GetMatches(null)) { certs.Add(c); } } return(certs); } catch (CertificateEncodingException e) { throw new CmsException("error encoding certs", e); } catch (Exception e) { throw new CmsException("error processing certs", e); } }
public static IList GetCertificatesFromStore( IX509Store certStore) { try { IList certs = Platform.CreateArrayList(); if (certStore != null) { foreach (X509Certificate c in certStore.GetMatches(null)) { certs.Add( X509CertificateStructure.GetInstance( Asn1Object.FromByteArray(c.GetEncoded()))); } } return(certs); } catch (CertificateEncodingException e) { throw new CmsException("error encoding certs", e); } catch (Exception e) { throw new CmsException("error processing certs", e); } }
public static IList GetCrlsFromStore(IX509Store crlStore) { IList result; try { IList list = Platform.CreateArrayList(); if (crlStore != null) { foreach (X509Crl x509Crl in crlStore.GetMatches(null)) { list.Add(CertificateList.GetInstance(Asn1Object.FromByteArray(x509Crl.GetEncoded()))); } } result = list; } catch (CrlException e) { throw new CmsException("error encoding crls", e); } catch (Exception e2) { throw new CmsException("error processing crls", e2); } return(result); }
public void TestSha1WithRsa() { MemoryStream bOut = new MemoryStream(); IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert); IX509Store x509Crls = CmsTestUtil.MakeCrlStore(SignCrl, OrigCrl); CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1); gen.AddCertificates(x509Certs); gen.AddCrls(x509Crls); Stream sigOut = gen.Open(bOut); byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CheckSigParseable(bOut.ToArray()); CmsSignedDataParser sp = new CmsSignedDataParser( new CmsTypedStream(new MemoryStream(testBytes, false)), bOut.ToArray()); sp.GetSignedContent().Drain(); // compute expected content digest byte[] hash = DigestUtilities.CalculateDigest("SHA1", testBytes); VerifySignatures(sp, hash); // // try using existing signer // gen = new CmsSignedDataStreamGenerator(); gen.AddSigners(sp.GetSignerInfos()); gen.AddCertificates(sp.GetCertificates("Collection")); gen.AddCrls(sp.GetCrls("Collection")); bOut.SetLength(0); sigOut = gen.Open(bOut, true); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); VerifyEncodedData(bOut); // // look for the CRLs // ArrayList col = new ArrayList(x509Crls.GetMatches(null)); Assert.AreEqual(2, col.Count); Assert.IsTrue(col.Contains(SignCrl)); Assert.IsTrue(col.Contains(OrigCrl)); }
public void TestAccuracyZeroCerts() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2"); tsTokenGen.SetCertificates(certs); tsTokenGen.SetAccuracySeconds(1); tsTokenGen.SetAccuracyMillis(2); tsTokenGen.SetAccuracyMicros(3); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); // // check validation // tsResp.Validate(request); // // check tstInfo // TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; // // check accuracy // GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.AreEqual(1, accuracy.Seconds); Assert.AreEqual(2, accuracy.Millis); Assert.AreEqual(3, accuracy.Micros); Assert.AreEqual(BigInteger.ValueOf(23), tstInfo.SerialNumber); Assert.AreEqual("1.2", tstInfo.Policy); // // test certReq // IX509Store store = tsToken.GetCertificates("Collection"); ICollection certificates = store.GetMatches(null); Assert.AreEqual(0, certificates.Count); }
public void TestNoNonce() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]); Assert.IsFalse(request.CertReq); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(24), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); // // check validation // tsResp.Validate(request); // // check tstInfo // TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; // // check accuracy // GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.IsNull(accuracy); Assert.AreEqual(BigInteger.ValueOf(24), tstInfo.SerialNumber); Assert.AreEqual("1.2.3", tstInfo.Policy); Assert.IsFalse(tstInfo.IsOrdered); Assert.IsNull(tstInfo.Nonce); // // test certReq // IX509Store store = tsToken.GetCertificates("Collection"); ICollection certificates = store.GetMatches(null); Assert.AreEqual(0, certificates.Count); }
private void certPairTest() { X509CertificateParser certParser = new X509CertificateParser(); X509Certificate rootCert = certParser.ReadCertificate(CertPathTest.rootCertBin); X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin); X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin); // Testing CollectionCertStore generation from List X509CertificatePair pair1 = new X509CertificatePair(rootCert, interCert); IList certList = new ArrayList(); certList.Add(pair1); certList.Add(new X509CertificatePair(interCert, finalCert)); IX509Store certStore = X509StoreFactory.Create( "CertificatePair/Collection", new X509CollectionStoreParameters(certList)); X509CertPairStoreSelector selector = new X509CertPairStoreSelector(); X509CertStoreSelector fwSelector = new X509CertStoreSelector(); fwSelector.SerialNumber = rootCert.SerialNumber; fwSelector.Subject = rootCert.IssuerDN; selector.ForwardSelector = fwSelector; IList col = new ArrayList(certStore.GetMatches(selector)); if (col.Count != 1 || !col.Contains(pair1)) { Fail("failed pair1 test"); } col = new ArrayList(certStore.GetMatches(null)); if (col.Count != 2) { Fail("failed null test"); } }
private void testNoNonse(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]); ArrayList algorithms = new ArrayList(); algorithms.Add(TspAlgorithms.Sha1); request.Validate(algorithms, new ArrayList(), new ArrayList()); Assert.False(request.CertReq); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, new BigInteger("24"), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); tsResp.Validate(request); TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.IsNull(accuracy); Assert.IsTrue(new BigInteger("24").Equals(tstInfo.SerialNumber)); Assert.IsTrue("1.2.3" == tstInfo.Policy); Assert.False(tstInfo.IsOrdered); Assert.IsNull(tstInfo.Nonce); // // test certReq // IX509Store store = tsToken.GetCertificates(); ICollection certificates = store.GetMatches(null); Assert.IsTrue(0 == certificates.Count); }
private void v2SigningResponseParse( byte[] encoded) { TimeStampResponse response = new TimeStampResponse(encoded); IX509Store store = response.TimeStampToken.GetCertificates("Collection"); X509Certificate cert = (X509Certificate) new ArrayList(store.GetMatches(response.TimeStampToken.SignerID))[0]; response.TimeStampToken.Validate(cert); }
X509Certificate GetCertificate(IX509Store store, SignerID signer) { var matches = store.GetMatches(signer); foreach (X509Certificate certificate in matches) { return(certificate); } return(GetCertificate(signer)); }
private Org.BouncyCastle.X509.X509Certificate GetCertificate(SignerInformation signer, IX509Store store) { X509CertStoreSelector sel = new X509CertStoreSelector(); sel.SerialNumber = signer.SignerID.SerialNumber; ICollection coll = store.GetMatches(sel); IEnumerator en = coll.GetEnumerator(); en.MoveNext(); return(en.Current as Org.BouncyCastle.X509.X509Certificate); }
private void testAccuracyWithCertsAndOrdering(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); tsTokenGen.SetAccuracySeconds(1); tsTokenGen.SetAccuracyMillis(2); tsTokenGen.SetAccuracyMicros(3); tsTokenGen.SetOrdering(true); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.SetCertReq(true); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); // // This is different to the Java API. // TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsResp.Validate(request); TimeStampTokenInfo tstInfo = tsToken.TimeStampInfo; GenTimeAccuracy accuracy = tstInfo.GenTimeAccuracy; Assert.IsTrue(1 == accuracy.Seconds); Assert.IsTrue(2 == accuracy.Millis); Assert.IsTrue(3 == accuracy.Micros); Assert.IsTrue(new BigInteger("23").Equals(tstInfo.SerialNumber)); Assert.IsTrue("1.2.3" == tstInfo.Policy); IX509Store store = tsToken.GetCertificates(); ICollection certificates = store.GetMatches(null); Assert.IsTrue(2 == certificates.Count); }
public void AddAttributeCertificates(IX509Store store) { try { foreach (IX509AttributeCertificate iX509AttributeCertificate in store.GetMatches(null)) { this._certs.Add(new DerTaggedObject(false, 2, AttributeCertificate.GetInstance(Asn1Object.FromByteArray(iX509AttributeCertificate.GetEncoded())))); } } catch (Exception e) { throw new CmsException("error processing attribute certs", e); } }
public void TestWithAttributeCertificate() { IList certList = new ArrayList(); certList.Add(SignCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); 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); MemoryStream bOut = new MemoryStream(); Stream sigOut = gen.Open(bOut, true); byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray()); sp.GetSignedContent().Drain(); Assert.AreEqual(4, sp.Version); store = sp.GetAttributeCertificates("Collection"); ArrayList coll = new ArrayList(store.GetMatches(null)); Assert.AreEqual(1, coll.Count); Assert.IsTrue(coll.Contains(attrCert)); }
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(); }
private void AddTSACertificates(UnsignedProperties unsignedProperties, IEnumerable <string> ocspServers, IEnumerable <X509Crl> crlList, FirmaXades.Crypto.DigestMethod digestMethod) { TimeStampToken timeStampToken = new TimeStampToken(new CmsSignedData(unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection[0].EncapsulatedTimeStamp.PkiData)); IX509Store certificates = timeStampToken.GetCertificates("Collection"); SignerID signerID = timeStampToken.SignerID; List <X509Certificate2> list = new List <X509Certificate2>(); foreach (object match in certificates.GetMatches(null)) { X509Certificate2 item = new X509Certificate2(((Org.BouncyCastle.X509.X509Certificate)match).GetEncoded()); list.Add(item); } X509Certificate2 cert = DetermineStartCert(list); AddCertificate(cert, unsignedProperties, true, ocspServers, crlList, digestMethod, list.ToArray()); }
/// <summary> /// Comprueba si un certificado ya existe en un almacén dado /// </summary> /// <param name="cert"></param> /// <param name="certStore"></param> /// <returns></returns> private bool CheckCertExists(X509Certificate cert, IX509Store certStore) { X509CertStoreSelector selector = new X509CertStoreSelector(); selector.Certificate = cert; ICollection result = certStore.GetMatches(selector); if (result == null) { return(false); } else { return(result.Count > 0); } }
public void TestCertReq() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); // // request with certReq false // reqGen.SetCertReq(false); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; Assert.IsNull(tsToken.TimeStampInfo.GenTimeAccuracy); // check for abscence of accuracy Assert.AreEqual("1.2", tsToken.TimeStampInfo.Policy); try { tsToken.Validate(cert); } catch (TspValidationException) { Assert.Fail("certReq(false) verification of token failed."); } IX509Store respCerts = tsToken.GetCertificates("Collection"); ICollection certsColl = respCerts.GetMatches(null); if (certsColl.Count != 0) { Assert.Fail("certReq(false) found certificates in response."); } }
public static Org.BouncyCastle.X509.X509Certificate ValidateAndGetDerivedIssuer(this Org.BouncyCastle.X509.X509Certificate cert, IX509Store issuerChains) { Org.BouncyCastle.X509.X509Certificate issuer = null; //does it look like a self signed? if (!cert.IssuerDN.Equivalent(cert.SubjectDN, false)) { return(null); } //is it a self signed? try { cert.Verify(cert.GetPublicKey()); return(null); } catch (InvalidKeyException) { //we have to come here } //It isn't self signed, lets see if we can find a valid issuer. var issuerSelector = new SignerID(); issuerSelector.Subject = cert.IssuerDN; foreach (Org.BouncyCastle.X509.X509Certificate potentialIssuer in issuerChains.GetMatches(issuerSelector)) { try { cert.Verify(potentialIssuer.GetPublicKey()); } catch (InvalidKeyException) { //Not the actual signer, lets try the next one continue; } //Find the most recent issuer that is valid if (potentialIssuer.IsBetter(issuer, cert.NotBefore)) { issuer = potentialIssuer; } } return(issuer); }
private static X509Certificate GenerateCertificate(String certificateString) { byte[] bytes = Convert.FromBase64CharArray(certificateString.ToCharArray(), 0, certificateString.Length); CmsSignedData cmsSignedData = new CmsSignedData(bytes); IX509Store store = cmsSignedData.GetCertificates("Collection"); ICollection allCertificates = store.GetMatches(null); IEnumerator enumerator = allCertificates.GetEnumerator(); while (enumerator.MoveNext()) { X509Certificate x509 = (X509Certificate)enumerator.Current; Console.WriteLine("Server Generated Certificate: " + x509.ToString()); return(x509); } throw new Exception("Certificate generation error"); }
/// <summary> /// Inserta y valida los certificados del servidor de sellado de tiempo. /// </summary> /// <param name="unsignedProperties"></param> private void AddTSACertificates(UnsignedProperties unsignedProperties, IEnumerable <OcspServer> ocspServers, IEnumerable <X509Crl> crlList, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl) { TimeStampToken token = new TimeStampToken(new CmsSignedData(unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection[0].EncapsulatedTimeStamp.PkiData)); IX509Store store = token.GetCertificates("Collection"); Org.BouncyCastle.Cms.SignerID signerId = token.SignerID; List <X509Certificate2> tsaCerts = new List <X509Certificate2>(); foreach (var tsaCert in store.GetMatches(null)) { X509Certificate2 cert = new X509Certificate2(((Org.BouncyCastle.X509.X509Certificate)tsaCert).GetEncoded()); tsaCerts.Add(cert); } X509Certificate2 startCert = DetermineStartCert(tsaCerts.ToArray()); AddCertificate(startCert, unsignedProperties, true, ocspServers, crlList, digestMethod, addCertificateOcspUrl, tsaCerts.ToArray()); }
private void certReqTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.SetCertReq(false); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, BigInteger.ValueOf(23), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; Assert.IsNull(tsToken.TimeStampInfo.GenTimeAccuracy); // check for abscence of accuracy Assert.True("1.2".Equals(tsToken.TimeStampInfo.Policy)); try { tsToken.Validate(cert); } catch (TspValidationException) { Assert.Fail("certReq(false) verification of token failed."); } IX509Store store = tsToken.GetCertificates(); ICollection certsColl = store.GetMatches(null); if (certsColl.Count > 0) { Assert.Fail("certReq(false) found certificates in response."); } }
/** * Add the attribute certificates contained in the passed in store to the * generator. * * @param store a store of Version 2 attribute certificates * @throws CmsException if an error occurse processing the store. */ public void AddAttributeCertificates( IX509Store store) { try { foreach (IX509AttributeCertificate attrCert in store.GetMatches(null)) { _certs.Add(new DerTaggedObject(false, 2, AttributeCertificate.GetInstance(Asn1Object.FromByteArray(attrCert.GetEncoded())))); } } catch (Exception e) { throw new CmsException("error processing attribute certs", e); } }
X509Certificate GetCertificate(IX509Store store, SignerID signer) { var matches = store.GetMatches (signer); foreach (X509Certificate certificate in matches) { return certificate; } return GetCertificate (signer); }
PkixCertPath BuildCertPath(HashSet anchors, IX509Store certificates, IX509Store crls, X509Certificate certificate, DateTime? signingTime) { var intermediate = new X509CertificateStore (); foreach (X509Certificate cert in certificates.GetMatches (null)) intermediate.Add (cert); var selector = new X509CertStoreSelector (); selector.Certificate = certificate; var parameters = new PkixBuilderParameters (anchors, selector); parameters.AddStore (GetIntermediateCertificates ()); parameters.AddStore (intermediate); var localCrls = GetCertificateRevocationLists (); parameters.AddStore (localCrls); parameters.AddStore (crls); // Note: we disable revocation unless we actually have non-empty revocation lists parameters.IsRevocationEnabled = localCrls.GetMatches (null).Count > 0; parameters.ValidityModel = PkixParameters.ChainValidityModel; if (signingTime.HasValue) parameters.Date = new DateTimeObject (signingTime.Value); var result = new PkixCertPathBuilder ().Build (parameters); return result.CertPath; }
private SignatureSecurityInformation Verify(SignerInformationStore signerInfos, IX509Store certs, SignatureSecurityInformation outer) { trace.TraceEvent(TraceEventType.Information, 0, "Verifying the {0} signature information", outer != null ? "outer" : "inner"); SignatureSecurityInformation result = new SignatureSecurityInformation(); //Check if signed (only allow single signatures) SignerInformation signerInfo = null; IEnumerator iterator = signerInfos.GetSigners().GetEnumerator(); if (!iterator.MoveNext()) { result.securityViolations.Add(SecurityViolation.NotSigned); trace.TraceEvent(TraceEventType.Warning, 0, "Although it is a correct CMS file it isn't signed"); return result; } signerInfo = (SignerInformation)iterator.Current; trace.TraceEvent(TraceEventType.Verbose, 0, "Found signature, with signer ID = issuer {0} and serial number {1}", signerInfo.SignerID.Issuer, signerInfo.SignerID.SerialNumber); if (iterator.MoveNext()) { trace.TraceEvent(TraceEventType.Error, 0, "Found more then one signature, this isn't supported (yet)"); throw new InvalidMessageException("An eHealth compliant message can have only one signer"); } //check if signer used correct digest algorithm int i = 0; bool found = false; StringBuilder algos = new StringBuilder(); while (!found && i < EteeActiveConfig.Unseal.SignatureAlgorithms.Count) { Oid algoDigest = EteeActiveConfig.Unseal.SignatureAlgorithms[i].DigestAlgorithm; Oid algoEnc = EteeActiveConfig.Unseal.SignatureAlgorithms[i++].EncryptionAlgorithm; algos.Append(algoDigest.Value + " (" + algoDigest.FriendlyName + ") + " + algoEnc.Value + " (" + algoEnc.FriendlyName + "), "); found = (algoDigest.Value == signerInfo.DigestAlgOid) && (algoEnc.Value == signerInfo.EncryptionAlgOid); } if (!found) { result.securityViolations.Add(SecurityViolation.NotAllowedSignatureDigestAlgorithm); trace.TraceEvent(TraceEventType.Warning, 0, "The signature digest + encryption algorithm {0} + {1} isn't allowed, only {2} are", signerInfo.DigestAlgOid, signerInfo.EncryptionAlgOid, algos); } trace.TraceEvent(TraceEventType.Verbose, 0, "Verified the signature digest and encryption algorithm"); //Find the singing certificate and relevant info Org.BouncyCastle.X509.X509Certificate signerCert = null; if (certs.GetMatches(null).Count > 0) { //We got certificates, so lets find the signer IEnumerator signerCerts = certs.GetMatches(signerInfo.SignerID).GetEnumerator(); if (!signerCerts.MoveNext()) { //found no certificate result.securityViolations.Add(SecurityViolation.NotFoundSigner); trace.TraceEvent(TraceEventType.Warning, 0, "Could not find the signer certificate"); return result; } //Getting the first certificate signerCert = (Org.BouncyCastle.X509.X509Certificate)signerCerts.Current; trace.TraceEvent(TraceEventType.Verbose, 0, "Found the signer certificate: {0}", signerCert.SubjectDN.ToString()); //Check if the outer certificate matches the inner certificate if (outer != null) { Org.BouncyCastle.X509.X509Certificate authCert = DotNetUtilities.FromX509Certificate(outer.Subject.Certificate); trace.TraceEvent(TraceEventType.Verbose, 0, "Comparing The signer certificate {0} ({1}) with the authentication certificate {2} ({3})", signerCert.SubjectDN, signerCert.IssuerDN, authCert.SubjectDN, authCert.IssuerDN); //_safe_ check if the serial numbers of the subject name are equal and they have the same issuer if (!authCert.SubjectDN.GetOidList().Contains(X509Name.SerialNumber) || !signerCert.SubjectDN.GetOidList().Contains(X509Name.SerialNumber) || authCert.SubjectDN.GetValueList(X509Name.SerialNumber).Count != 1 || signerCert.SubjectDN.GetValueList(X509Name.SerialNumber).Count != 1 || !authCert.SubjectDN.GetValueList(X509Name.SerialNumber)[0].Equals(signerCert.SubjectDN.GetValueList(X509Name.SerialNumber)[0]) || !authCert.IssuerDN.Equals(signerCert.IssuerDN)) { result.securityViolations.Add(SecurityViolation.SubjectDoesNotMachEnvelopingSubject); trace.TraceEvent(TraceEventType.Warning, 0, "The signer certificate {0} ({1}) does not match the authentication certificate {2} ({3})", signerCert.SubjectDN, signerCert.IssuerDN, authCert.SubjectDN, authCert.IssuerDN); } } if (signerCerts.MoveNext()) { //found several certificates... trace.TraceEvent(TraceEventType.Error, 0, "Several certificates correspond to the signer"); throw new NotSupportedException("More then one certificate found that corresponds to the sender information in the message, this isn't supported by the library"); } } else { if (outer == null) { trace.TraceEvent(TraceEventType.Error, 0, "The outer signature does not contain any certificates"); throw new InvalidMessageException("The outer signature is missing certifcates"); } //The subject is the same as the outer result.Subject = outer.Subject; signerCert = DotNetUtilities.FromX509Certificate(result.Subject.Certificate); trace.TraceEvent(TraceEventType.Verbose, 0, "An already validated certificates was provided: {0}", signerCert.SubjectDN.ToString()); //Additional check, is the authentication certificate also valid for signatures? if (!DotNetUtilities.FromX509Certificate(result.Subject.Certificate).GetKeyUsage()[1]) { result.Subject.securityViolations.Add(CertSecurityViolation.NotValidForUsage); trace.TraceEvent(TraceEventType.Warning, 0, "The key usage did not have the correct usage flag set"); } } //verify the signature itself result.SignatureValue = signerInfo.GetSignature(); if (!signerInfo.Verify(signerCert.GetPublicKey())) { result.securityViolations.Add(SecurityViolation.NotSignatureValid); trace.TraceEvent(TraceEventType.Warning, 0, "The signature value was invalid"); } trace.TraceEvent(TraceEventType.Verbose, 0, "Signature value verification finished"); //Get the signing time bool hasSigningTime = false; DateTime signingTime = DateTime.UtcNow; if (signerInfo != null && signerInfo.SignedAttributes != null) { Org.BouncyCastle.Asn1.Cms.Attribute time = signerInfo.SignedAttributes[CmsAttributes.SigningTime]; if (time != null && time.AttrValues.Count > 0) { hasSigningTime = true; result.SigningTime = Org.BouncyCastle.Asn1.Cms.Time.GetInstance(time.AttrValues[0]).Date; signingTime = result.SigningTime.Value; trace.TraceEvent(TraceEventType.Verbose, 0, "The CMS message contains a signing time: {0}", result.SigningTime); } } //Validating signature info if (this.level == null && result.Subject == null) { if (outer == null) result.Subject = CertVerifier.VerifyAuth(signerCert, signingTime, certs, null, null, false, false); else result.Subject = CertVerifier.VerifySign(signerCert, signingTime, certs, null, null, false, false); return result; } //Get the embedded CRLs and OCSPs IList<CertificateList> crls = new List<CertificateList>(); IList<BasicOcspResponse> ocsps = new List<BasicOcspResponse>(); if (signerInfo != null && signerInfo.UnsignedAttributes != null) { trace.TraceEvent(TraceEventType.Verbose, 0, "The CMS message contains unsigned attributes"); Org.BouncyCastle.Asn1.Cms.Attribute revocationValuesList = signerInfo.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationValues]; if (revocationValuesList != null && revocationValuesList.AttrValues.Count > 0) { trace.TraceEvent(TraceEventType.Verbose, 0, "The CMS message contains Revocation Values"); RevocationValues revocationValues = RevocationValues.GetInstance(revocationValuesList.AttrValues[0]); if (revocationValues.GetCrlVals() != null) { crls = new List<CertificateList>(revocationValues.GetCrlVals()); trace.TraceEvent(TraceEventType.Verbose, 0, "Found {0} CRL's in the message", crls.Count); } if (revocationValues.GetOcspVals() != null) { ocsps = new List<BasicOcspResponse>(revocationValues.GetOcspVals()); trace.TraceEvent(TraceEventType.Verbose, 0, "Found {0} OCSP's in the message", ocsps.Count); } } } //check for a time-stamp, even if not required DateTime validationTime; TimeStampToken tst = null; bool isSigingTimeValidated; if (signerInfo != null && signerInfo.UnsignedAttributes != null) { trace.TraceEvent(TraceEventType.Verbose, 0, "The CMS message contains unsigned attributes"); Org.BouncyCastle.Asn1.Cms.Attribute tstList = signerInfo.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken]; if (tstList != null && tstList.AttrValues.Count > 0) { trace.TraceEvent(TraceEventType.Verbose, 0, "The CMS message contains the Signature Time Stamp Token: {0}", Convert.ToBase64String(tstList.AttrValues[0].GetEncoded())); tst = tstList.AttrValues[0].GetEncoded().ToTimeStampToken(); } } if (tst == null) { //Retrieve the time-mark if needed by the level only if ((this.level & Level.T_Level) == Level.T_Level) { if (outer == null) { //we are in the outer signature, so we need a time-mark (or time-stamp, but we checked that already) if (timemarkauthority == null) { trace.TraceEvent(TraceEventType.Error, 0, "Not time-mark authority is provided while there is not embedded time-stamp, the level includes T-Level and it isn't an inner signature"); throw new InvalidMessageException("The message does not contain a time-stamp and there is not time-mark authority provided while T-Level is required"); } trace.TraceEvent(TraceEventType.Verbose, 0, "Requesting time-mark for message signed by {0}, signed on {1} and with signature value {2}", signerCert.SubjectDN, signingTime, signerInfo.GetSignature()); validationTime = timemarkauthority.GetTimemark(new X509Certificate2(signerCert.GetEncoded()), signingTime, signerInfo.GetSignature()).ToUniversalTime(); trace.TraceEvent(TraceEventType.Verbose, 0, "The validated time is the return time-mark which is: {0}", validationTime); } else { //we are in the inner signature, we check the signing time against the outer signatures signing time validationTime = outer.SigningTime.Value; trace.TraceEvent(TraceEventType.Verbose, 0, "The validated time is the outer signature singing time which is: {0}", validationTime); } } else { isSigingTimeValidated = false; validationTime = signingTime; trace.TraceEvent(TraceEventType.Verbose, 0, "There is not validated provided, nor is it retrieved because of the level"); } } else { //Check the time-stamp if (!tst.IsMatch(new MemoryStream(signerInfo.GetSignature()))) { trace.TraceEvent(TraceEventType.Warning, 0, "The time-stamp does not match the message"); result.securityViolations.Add(SecurityViolation.InvalidTimestamp); } Timestamp stamp; if ((this.level & Level.A_level) == Level.A_level) { //TODO::follow the chain of A-timestamps until the root (now we assume the signature time-stamp is the root) trace.TraceEvent(TraceEventType.Verbose, 0, "Validating the time-stamp against the current time for arbitration reasons"); stamp = tst.Validate(ref crls, ref ocsps, null); } else { trace.TraceEvent(TraceEventType.Verbose, 0, "Validating the time-stamp against the time-stamp time since no arbitration is needed"); stamp = tst.Validate(ref crls, ref ocsps); } result.TimestampRenewalTime = stamp.RenewalTime; trace.TraceEvent(TraceEventType.Verbose, 0, "The time-stamp must be renewed on {0}", result.TimestampRenewalTime); //we get the time from the time-stamp validationTime = stamp.Time; trace.TraceEvent(TraceEventType.Verbose, 0, "The validated time is the time-stamp time which is on {0}", validationTime); if (!hasSigningTime) { trace.TraceEvent(TraceEventType.Information, 0, "Implicit signing time {0} is replaced with time-stamp time {1}", signingTime, tst.TimeStampInfo.GenTime); signingTime = stamp.Time; } if (stamp.TimestampStatus.Count(x => x.Status != X509ChainStatusFlags.NoError) > 0) { trace.TraceEvent(TraceEventType.Warning, 0, "The time-stamp is invalid with {0} errors, including {1}: {2}", stamp.TimestampStatus.Count, stamp.TimestampStatus[0].Status, stamp.TimestampStatus[0].StatusInformation); isSigingTimeValidated = false; result.securityViolations.Add(SecurityViolation.InvalidTimestamp); } } //lest check if the signing time is in line with the validation time (obtained from time-mark, outer signature or time-stamp) if (validationTime > (signingTime + EteeActiveConfig.ClockSkewness + Settings.Default.TimestampGracePeriod) || validationTime < (signingTime - EteeActiveConfig.ClockSkewness)) { trace.TraceEvent(TraceEventType.Warning, 0, "The validated time {0} is not in line with the signing time {1} with a grace period of {2}", validationTime, signingTime, Settings.Default.TimestampGracePeriod); isSigingTimeValidated = false; result.securityViolations.Add(SecurityViolation.SealingTimeInvalid); } else { trace.TraceEvent(TraceEventType.Verbose, 0, "The validated time {0} is in line with the signing time {1}", validationTime, signingTime); isSigingTimeValidated = true; } //If the subject is already provided, so we don't have to do the next check if (result.Subject != null) return result; //check the status on the available info, for unseal it does not matter if it is B-Level or LT-Level. if (outer == null) result.Subject = CertVerifier.VerifyAuth(signerCert, signingTime, certs, crls, ocsps, true, isSigingTimeValidated); else result.Subject = CertVerifier.VerifySign(signerCert, signingTime, certs, crls, ocsps, true, isSigingTimeValidated); return result; }
public static IList GetCrlsFromStore( IX509Store crlStore) { try { IList crls = Platform.CreateArrayList(); if (crlStore != null) { foreach (X509Crl c in crlStore.GetMatches(null)) { crls.Add( CertificateList.GetInstance( Asn1Object.FromByteArray(c.GetEncoded()))); } } return crls; } catch (CrlException e) { throw new CmsException("error encoding crls", e); } catch (Exception e) { throw new CmsException("error processing crls", e); } }
private static CertificateSecurityInformation Verify(Org.BouncyCastle.X509.X509Certificate cert, DateTime date, IX509Store certs, IList<CertificateList> crls, IList<BasicOcspResponse> ocsps, bool checkRevocation, bool checkTime) { CertificateSecurityInformation result = new CertificateSecurityInformation(); AsymmetricKeyParameter key = cert.GetPublicKey(); //check key type if (!(key is RsaKeyParameters)) { result.securityViolations.Add(CertSecurityViolation.NotValidKeyType); trace.TraceEvent(TraceEventType.Warning, 0, "The key should be RSA but was {0}", key.GetType()); } //check key size if (!VerifyKeySize(key, EteeActiveConfig.Unseal.MinimumSignatureKeySize)) { result.securityViolations.Add(CertSecurityViolation.NotValidKeySize); trace.TraceEvent(TraceEventType.Warning, 0, "The key was smaller then {0}", EteeActiveConfig.Unseal.MinimumSignatureKeySize); } X509Certificate2Collection extraStore = new X509Certificate2Collection(); foreach (Org.BouncyCastle.X509.X509Certificate obj in certs.GetMatches(null)) { extraStore.Add(new X509Certificate2(obj.GetEncoded())); } Chain chain; if (checkRevocation) chain = new X509Certificate2(cert.GetEncoded()).BuildChain(date, extraStore, ref crls, ref ocsps, checkTime ? DateTime.UtcNow : date); else chain = new X509Certificate2(cert.GetEncoded()).BuildBasicChain(date, extraStore); CertificateSecurityInformation dest = null; foreach (ChainElement ce in chain.ChainElements) { if (dest == null) { dest = result; } else { dest.IssuerInfo = new CertificateSecurityInformation(); dest = dest.IssuerInfo; } dest.Certificate = ce.Certificate; foreach (X509ChainStatus status in ce.ChainElementStatus.Where(x => x.Status != X509ChainStatusFlags.NoError)) { dest.securityViolations.Add((CertSecurityViolation)Enum.Parse(typeof(CertSecurityViolation), Enum.GetName(typeof(X509ChainStatusFlags), status.Status))); } } if (chain.ChainStatus.Count(x => x.Status == X509ChainStatusFlags.PartialChain) > 0) { result.securityViolations.Add(CertSecurityViolation.IssuerTrustUnknown); } trace.TraceEvent(TraceEventType.Verbose, 0, "Verified certificate {0} for date {1}", cert.SubjectDN.ToString(), date); return result; }