/// <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); } }
internal SignerInformation(Org.BouncyCastle.Asn1.Cms.SignerInfo info, DerObjectIdentifier contentType, CmsProcessable content, IDigestCalculator digestCalculator) { this.info = info; sid = new SignerID(); this.contentType = contentType; isCounterSignature = (contentType == null); try { SignerIdentifier signerID = info.SignerID; if (signerID.IsTagged) { Asn1OctetString instance = Asn1OctetString.GetInstance(signerID.ID); sid.SubjectKeyIdentifier = instance.GetEncoded(); } else { Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber instance2 = Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber.GetInstance(signerID.ID); sid.Issuer = instance2.Name; sid.SerialNumber = instance2.SerialNumber.Value; } } catch (IOException) { throw new ArgumentException("invalid sid in SignerInfo"); } digestAlgorithm = info.DigestAlgorithm; signedAttributeSet = info.AuthenticatedAttributes; unsignedAttributeSet = info.UnauthenticatedAttributes; encryptionAlgorithm = info.DigestEncryptionAlgorithm; signature = info.EncryptedDigest.GetOctets(); this.content = content; this.digestCalculator = digestCalculator; }
public SignerInformationStore(SignerInformation signerInfo) { all = Platform.CreateArrayList(1); all.Add(signerInfo); SignerID signerID = signerInfo.SignerID; table[signerID] = all; }
public CAdESOCSPSource(CmsSignedData cms) { var signers = cms.GetSignerInfos().GetSigners().GetEnumerator(); signers.MoveNext(); cmsSignedData = cms; signerId = ((SignerInformation)signers.Current).SignerID; }
/// <summary>The default constructor for CAdESCRLSource.</summary> /// <remarks>The default constructor for CAdESCRLSource.</remarks> /// <param name="cms"></param> /// <exception cref="Org.Bouncycastle.Cms.CmsException">Org.Bouncycastle.Cms.CmsException /// </exception> public CAdESCRLSource(CmsSignedData cms) { IEnumerator signers = cms.GetSignerInfos().GetSigners().GetEnumerator(); signers.MoveNext(); this.cmsSignedData = cms; this.signerId = ((SignerInformation)signers.Current).SignerID; }
public SignerInformation GetFirstSigner(SignerID selector) { IList list = (IList)table[selector]; if (list != null) { return((SignerInformation)list[0]); } return(null); }
public ICollection GetSigners(SignerID selector) { IList list = (IList)table[selector]; if (list != null) { return(Platform.CreateArrayList(list)); } return(Platform.CreateArrayList()); }
/// <summary>The default constructor for CAdESCertificateSource.</summary> /// <remarks>The default constructor for CAdESCertificateSource.</remarks> /// <param name="encodedCMS"></param> /// <exception cref="Org.Bouncycastle.Cms.CmsException">Org.Bouncycastle.Cms.CmsException /// </exception> public CAdESCertificateSource(CmsSignedData cms) { IEnumerator signers = cms.GetSignerInfos().GetSigners().GetEnumerator(); signers.MoveNext(); this.cmsSignedData = cms; this.signerId = ((SignerInformation)signers.Current).SignerID; this.onlyExtended = false; }
internal TsaId(SignerID signerID, X509Certificate2 cert) { this.TsaCertSerialNumber = signerID.SerialNumber.ToByteArray(); this.TsaCertSubjectKeyIdentifier = signerID.SubjectKeyIdentifier; this.TsaCertIssuerName = new X500DistinguishedName(signerID.Issuer.GetEncoded()); if (null != cert) { TsaCert = cert; } }
X509Certificate GetCertificate(IX509Store store, SignerID signer) { var matches = store.GetMatches(signer); foreach (X509Certificate certificate in matches) { return(certificate); } return(GetCertificate(signer)); }
public static bool ValidateCertificateChain(IX509Store certificateStore, SignerID signerID) { List <X509Certificate> certificateChain = GetCertificateChain(certificateStore, signerID); List <byte[]> certificateChainBytes = new List <byte[]>(); foreach (X509Certificate certficate in certificateChain) { certificateChainBytes.Add(certficate.GetEncoded()); } return(CertificateValidationHelper.VerifyCertificateChain(certificateChainBytes)); }
public SignerInformationStore(ICollection signerInfos) { foreach (SignerInformation signerInfo in signerInfos) { SignerID signerID = signerInfo.SignerID; IList list = (IList)table[signerID]; if (list == null) { list = (IList)(table[signerID] = Platform.CreateArrayList(1)); } list.Add(signerInfo); } all = Platform.CreateArrayList(signerInfos); }
public CAdESCertificateSource(CmsSignedData cms) { if (cms is null) { throw new ArgumentNullException(nameof(cms)); } var signers = cms.GetSignerInfos().GetSigners().GetEnumerator(); signers.MoveNext(); cmsSignedData = cms; signerId = ((SignerInformation)signers.Current).SignerID; onlyExtended = false; }
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()); }
/// <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."); }
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); }
public override bool Equals(object obj) { if (obj == this) { return(false); } SignerID signerID = obj as SignerID; if (signerID == null) { return(false); } if (Arrays.AreEqual(base.SubjectKeyIdentifier, signerID.SubjectKeyIdentifier) && object.Equals(base.SerialNumber, signerID.SerialNumber)) { return(X509CertStoreSelector.IssuersMatch(base.Issuer, signerID.Issuer)); } return(false); }
/// <exception cref="System.IO.IOException"></exception> public virtual Document ExtendSignature(object signatureId, Document document, Document originalData, SignatureParameters parameters) { SignerID toExtendId = (SignerID)signatureId; try { CmsSignedData signedData = new CmsSignedData(document.OpenStream()); SignerInformationStore signerStore = signedData.GetSignerInfos(); List <SignerInformation> siArray = new List <SignerInformation>(); //Iterator<object> infos = signerStore.GetSigners().Iterator(); IEnumerator infos = signerStore.GetSigners().GetEnumerator(); while (infos.MoveNext()) { SignerInformation si = (SignerInformation)infos.Current; if (si.SignerID.Equals(toExtendId)) { try { siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData)); } catch (IOException) { //LOG.Error("Exception when extending signature"); siArray.Add(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"); } }
public static SignerInformation GetSigner(CmsSignedDataParser cms, SignerID id) => GetSignerInfoByEnumeration(cms.GetSignerInfos(), id) ?? GetSignerInfoByGetFirst(cms.GetSignerInfos(), id);
public CAdESOCSPSource(CmsSignedData cms, SignerID id) { cmsSignedData = cms; signerId = id; }
public CAdESSignature(CmsSignedData cms, SignerID id) { _cmsSignedData = cms; this.signerInformation = BCStaticHelpers.GetSigner(cms, id); }
public static SignerInformation GetSignerInfoByEnumeration(SignerInformationStore signerInformationStore, SignerID id) { SignerInformation si = null; foreach (SignerInformation s in signerInformationStore.GetSigners()) { if (s.SignerID == id) { si = s; break; } } return(si); }
/// <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, SignerID id) { this.cmsSignedData = cms; this.signerId = id; }
/// <summary>The default constructor for CAdESSignature.</summary> /// <remarks>The default constructor for CAdESSignature.</remarks> /// <param name="data"></param> /// <exception cref="Org.Bouncycastle.Cms.CmsException">Org.Bouncycastle.Cms.CmsException /// </exception> public CAdESSignature(CmsSignedData cms, SignerID id) : this(cms, cms.GetSignerInfos().GetFirstSigner(id)) { }
public static SignerInformation GetSignerInfoByGetFirst(SignerInformationStore signerInformationStore, SignerID id) { return(signerInformationStore.GetFirstSigner(id)); }
public static byte[] ExtractSignerId(this SignerID selector) { //In case of SignerID it seems to be the encoded Octet String (bug?) return(Asn1OctetString.GetInstance(DerOctetString.FromByteArray(selector.SubjectKeyIdentifier)).GetOctets()); }
public CAdESCertificateSource(CmsSignedData cms, SignerID id, bool onlyExtended) { cmsSignedData = cms; signerId = id; this.onlyExtended = onlyExtended; }
/// <summary> /// Extracts and validates the certificate from token. /// </summary> /// <param name="token">The token.</param> /// <param name="timestamp">The timestamp.</param> /// <param name="validityPeriod">Required certificate validity</param> /// <returns><see cref="X509Certificate2" /></returns> /// <exception cref="TspValidationException">Invalid response, more than one certificate found</exception> /// <exception cref="System.Security.Cryptography.CryptographicException">Certificate chain validation failed.</exception> public static X509Certificate2 ValidateCertificate(TimeStampToken token, TimestampObject timestamp, int validityPeriod) { X509Certificate2 tsaCertificate = null; SignerID signer = token.SignerID; ICollection certificates = token.GetCertificates("Collection").GetMatches(signer); if (certificates.Count > 1) { throw new TspValidationException("Invalid response, more than one certificate found"); } foreach (Org.BouncyCastle.X509.X509Certificate cert in certificates) { /* * Validate the time stamp token. * <p> * To be valid the token must be signed by the passed in certificate and * the certificate must be the one referred to by the SigningCertificate * attribute included in the hashed attributes of the token. The * certificate must also have the ExtendedKeyUsageExtension with only * KeyPurposeID.IdKPTimeStamping and have been valid at the time the * timestamp was created. * </p> * <p> * A successful call to validate means all the above are true. * </p> */ token.Validate(cert); /// <summary> /// Return true if the nominated time is within the start and end times nominated on the certificate. /// </summary> /// <param name="time">The time to test validity against.</param> /// <returns>True if certificate is valid for nominated time.</returns> if (!cert.IsValid(token.TimeStampInfo.GenTime)) { throw new TspValidationException("Certificate is not valid at the time of timestamp creation."); } /* Set warning if signing certificate is expired or is about to expire */ if (!cert.IsValidNow) { timestamp.Warning = "Signing certificate expired."; } else if (validityPeriod > 0) { int expireDays = (cert.NotAfter - DateTime.Now).Days; if (expireDays <= validityPeriod) { timestamp.Warning = string.Format("Signing certificate is going to expire in {0} days on {1}.", expireDays, cert.NotAfter); } } /* * verify that the given certificate successfully handles and confirms * the signature associated with this signer and, if a signingTime * attribute is available, that the certificate was valid at the time the * signature was generated. */ token.ToCmsSignedData().GetSignerInfos().GetFirstSigner(signer).Verify(cert); tsaCertificate = new X509Certificate2(cert.GetEncoded()); /* Microsoft validation */ X509Chain chain = new X509Chain(); chain.ChainPolicy.VerificationTime = token.TimeStampInfo.GenTime; if (!chain.Build(tsaCertificate)) { /* Search for revoked certificate */ bool allRevokedCertificatesAreValid = true; foreach (X509ChainElement element in chain.ChainElements) { if (IsRevoked(element) && !IsValidAfterRevocation(element.Certificate, token.TimeStampInfo.GenTime)) { allRevokedCertificatesAreValid = false; break; } } string failReason = ""; foreach (X509ChainStatus status in chain.ChainStatus) { if (status.Status != X509ChainStatusFlags.Revoked || !allRevokedCertificatesAreValid) { failReason += status.Status + ": " + status.StatusInformation; } } if (failReason != "") { throw new CryptographicException("Certificate chain validation failed.\n" + failReason); } } } timestamp.Time = token.TimeStampInfo.GenTime; timestamp.TsaIssuer = token.SignerID.Issuer.ToString(); timestamp.TsaCertificate = tsaCertificate; timestamp.MessageImprint = BitConverter.ToString(token.TimeStampInfo.TstInfo.MessageImprint.GetHashedMessage()); return(tsaCertificate); }