public static void Main(string[] args) { try { string fileName = null; string tsa = null; string hash = null; string policy = null; string nonce = null; bool cert = false; string outFile = null; string sslClientCertFile = null; string sslClientCertPass = null; string httpAuthLogin = null; string httpAuthPass = null; bool isAsics = false; if (args == null) { return; } int i = 0; if (0 >= args.Length) { ExitWithHelp(string.Empty); } while (i < args.Length) { switch (args[i]) { case "--file": fileName = args[++i]; break; case "--tsa": tsa = args[++i]; break; case "--out": outFile = args[++i]; break; case "--hash": hash = args[++i]; break; case "--policy": policy = args[++i]; break; case "--nonce": nonce = args[++i]; break; case "--cert-req": cert = true; break; case "--ssl-client-cert-file": sslClientCertFile = args[++i]; break; case "--ssl-client-cert-pass": sslClientCertPass = args[++i]; break; case "--http-auth-login": httpAuthLogin = args[++i]; break; case "--http-auth-pass": httpAuthPass = args[++i]; break; case "--asics": isAsics = true; break; default: ExitWithHelp("Invalid argument: " + args[i]); break; } i++; } X509Certificate2 sslCert = null; if (!string.IsNullOrEmpty(sslClientCertFile)) { sslCert = new X509Certificate2(sslClientCertFile, sslClientCertPass); } NetworkCredential networkCredential = null; if (!string.IsNullOrEmpty(httpAuthLogin) && !string.IsNullOrEmpty(httpAuthPass)) { networkCredential = new NetworkCredential(httpAuthLogin, httpAuthPass); } UserCredentials credentials = null; if (networkCredential != null || sslCert != null) { credentials = new UserCredentials(sslCert, networkCredential); } TimeStampToken token = SharedUtils.RequestTimeStamp(tsa, fileName, hash, policy, nonce, cert, credentials, new LogDelegate(LogMessage), true); if (isAsics) { SharedUtils.SaveToAsicSimple(fileName, token, outFile); } else { SharedUtils.SaveResponse(outFile, token); } } catch (Exception e) { Console.WriteLine(e.Message); ExitWithHelp(null); } Console.WriteLine("Success"); }
public void TestResponseValidation() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2"); tsTokenGen.SetCertificates(certs); 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); try { request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(101)); tsResp.Validate(request); Assert.Fail("response validation failed on invalid nonce."); } catch (TspValidationException) { // ignore } try { request = reqGen.Generate(TspAlgorithms.Sha1, new byte[22], BigInteger.ValueOf(100)); tsResp.Validate(request); Assert.Fail("response validation failed on wrong digest."); } catch (TspValidationException) { // ignore } try { request = reqGen.Generate(TspAlgorithms.MD5, new byte[20], BigInteger.ValueOf(100)); tsResp.Validate(request); Assert.Fail("response validation failed on wrong digest."); } catch (TspValidationException) { // ignore } }
protected void Complete(Level?level, Stream embedded, Stream signed, Stream content, X509Certificate2 providedSigner, out TimemarkKey timemarkKey) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Information, 0, "Completing the message with of {0} bytes to level {1}", signed.Length, level); #else logger.LogInformation("Completing the message with of {0} bytes to level {1}", signed.Length, level); #endif //Create the objects we need var gen = new CmsSignedDataStreamGenerator(); var parser = new CmsSignedDataParser(signed); timemarkKey = new TimemarkKey(); //preset the digests so we can add the signers afterwards gen.AddDigests(parser.DigestOids); //Copy the content to the output Stream contentOut = gen.Open(embedded, parser.SignedContentType.Id, true); if (content != null) { content.CopyTo(contentOut); } else { parser.GetSignedContent().ContentStream.CopyTo(contentOut); } //Extract the various data from outer layer SignerInformation signerInfo = ExtractSignerInfo(parser); IX509Store embeddedCerts = parser.GetCertificates("Collection"); //Extract the various data from signer info timemarkKey.SignatureValue = signerInfo.GetSignature(); timemarkKey.SigningTime = ExtractSigningTime(signerInfo); timemarkKey.Signer = ExtractSignerCert(embeddedCerts, signerInfo, providedSigner); if (timemarkKey.Signer != null) { timemarkKey.SignerId = DotNetUtilities.FromX509Certificate(timemarkKey.Signer).GetSubjectKeyIdentifier(); } else { timemarkKey.SignerId = signerInfo.SignerID.ExtractSignerId(); } //Extract the various data from unsiged attributes of signer info IDictionary unsignedAttributes = signerInfo.UnsignedAttributes != null?signerInfo.UnsignedAttributes.ToDictionary() : new Hashtable(); TimeStampToken tst = ExtractTimestamp(unsignedAttributes); RevocationValues revocationInfo = ExtractRevocationInfo(unsignedAttributes); //quick check for an expected error and extrapolate some info if (timemarkKey.SignerId == null) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Error, 0, "We could not find any signer information"); #else logger.LogError("We could not find any signer information"); #endif throw new InvalidMessageException("The message does not contain any valid signer info"); } if (timemarkKey.SigningTime == default && tst != null) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Information, 0, "Implicit signing time is replaced with time-stamp time {1}", tst.TimeStampInfo.GenTime); #else logger.LogInformation("Implicit signing time is replaced with time-stamp time {1}", tst.TimeStampInfo.GenTime); #endif timemarkKey.SigningTime = tst.TimeStampInfo.GenTime; } //Are we missing embedded certs and should we add them? if ((embeddedCerts == null || embeddedCerts.GetMatches(null).Count <= 1) && timemarkKey.Signer != null && level != null) { embeddedCerts = GetEmbeddedCerts(timemarkKey); } if (embeddedCerts != null) { gen.AddCertificates(embeddedCerts); //add the existing or new embedded certs to the output. } //Are we missing timestamp and should we add them (not that time-mark authorities do not require a timestamp provider) if (tst == null && (level & Level.T_Level) == Level.T_Level && timestampProvider != null) { tst = GetTimestamp(timemarkKey); AddTimestamp(unsignedAttributes, tst); } //should be make sure we have the proper revocation info (it is hard to tell if we have everything, just go for it) if ((level & Level.L_Level) == Level.L_Level) { if (embeddedCerts != null && embeddedCerts.GetMatches(null).Count > 0) { //extend the revocation info with info about the embedded certs revocationInfo = GetRevocationValues(timemarkKey, embeddedCerts, revocationInfo); } if (tst != null) { //extend the revocation info with info about the TST revocationInfo = GetRevocationValues(tst, revocationInfo); } //update the unsigned attributes AddRevocationValues(unsignedAttributes, revocationInfo); } //Update the unsigned attributes of the signer info signerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, new BC::Asn1.Cms.AttributeTable(unsignedAttributes)); //Copy the signer gen.AddSigners(new SignerInformationStore(new SignerInformation[] { signerInfo })); contentOut.Close(); }
internal static DateTime GetTimeStampDate(TimeStampToken timeStampToken) { return(timeStampToken.TimeStampInfo.GenTime); }
public void TestAccuracyWithCertsAndOrdering() { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.MD5, "1.2.3"); tsTokenGen.SetCertificates(certs); tsTokenGen.SetAccuracySeconds(3); tsTokenGen.SetAccuracyMillis(1); tsTokenGen.SetAccuracyMicros(2); tsTokenGen.SetOrdering(true); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); reqGen.SetCertReq(true); TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20], BigInteger.ValueOf(100)); Assert.IsTrue(request.CertReq); 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(3, accuracy.Seconds); Assert.AreEqual(1, accuracy.Millis); Assert.AreEqual(2, accuracy.Micros); Assert.AreEqual(BigInteger.ValueOf(23), tstInfo.SerialNumber); Assert.AreEqual("1.2.3", tstInfo.Policy); Assert.AreEqual(true, tstInfo.IsOrdered); Assert.AreEqual(tstInfo.Nonce, BigInteger.ValueOf(100)); // // test certReq // IX509Store store = tsToken.GetCertificates("Collection"); ICollection certificates = store.GetMatches(null); Assert.AreEqual(2, certificates.Count); }
/// <summary> /// Validates the time-stamp token trusting the time of the token itself /// </summary> /// <param name="tst">The timestamp to validate</param> /// <returns>The validation chain of the signing certificate</returns> public static async Task <Timestamp> ValidateAsync(this TimeStampToken tst) { return(await tst.ValidateAsync(new List <CertificateList>(), new List <BasicOcspResponse>())); }
/// <summary>Constructor with an indication of the time-stamp type The default constructor for TimestampToken. /// </summary> /// <remarks>Constructor with an indication of the time-stamp type The default constructor for TimestampToken. /// </remarks> public TimestampToken(TimeStampToken timeStamp, TimestampToken.TimestampType type ) { this.timeStamp = timeStamp; this.timeStampType = type; }
private void extensionTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( privateKey, cert, TspAlgorithms.Sha1, "1.2"); tsTokenGen.SetCertificates(certs); TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator(); // --- These are test case only values reqGen.SetReqPolicy("2.5.29.56"); reqGen.AddExtension(new DerObjectIdentifier("1.3.6.1.5.5.7.1.2"), true, new DerOctetString(new byte[20])); // --- not for any real world purpose. TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha1, new byte[20]); try { request.Validate(new ArrayList(), new ArrayList(), new ArrayList()); Assert.Fail("expected exception"); } catch (Exception ex) { Assert.True("request contains unknown algorithm" == ex.Message); } ArrayList algorithms = new ArrayList(); algorithms.Add(TspAlgorithms.Sha1); try { request.Validate(algorithms, new ArrayList(), new ArrayList()); Assert.Fail("no exception"); } catch (Exception e) { Assert.IsTrue(e.Message == "request contains unknown policy"); } ArrayList policies = new ArrayList(); // Testing only do not use in real world. policies.Add("2.5.29.56"); try { request.Validate(algorithms, policies, new ArrayList()); Assert.Fail("no exception"); } catch (Exception e) { Assert.IsTrue(e.Message == "request contains unknown extension"); } ArrayList extensions = new ArrayList(); // Testing only do not use in real world/ extensions.Add("1.3.6.1.5.5.7.1.2"); // should validate with full set request.Validate(algorithms, policies, extensions); // should validate with null policy request.Validate(algorithms, null, extensions); TimeStampResponseGenerator tsRespGen = new TimeStampResponseGenerator(tsTokenGen, TspAlgorithms.Allowed); TimeStampResponse tsResp = tsRespGen.Generate(request, new BigInteger("23"), DateTime.UtcNow); tsResp = new TimeStampResponse(tsResp.GetEncoded()); TimeStampToken tsToken = tsResp.TimeStampToken; tsToken.Validate(cert); Asn1.Cms.AttributeTable table = tsToken.SignedAttributes; Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found"); }
private void overrideAttrsTest(AsymmetricKeyParameter privateKey, X509Certificate cert, IX509Store certs) { SignerInfoGeneratorBuilder signerInfoGenBuilder = new SignerInfoGeneratorBuilder(); IssuerSerial issuerSerial = new IssuerSerial( new GeneralNames( new GeneralName( X509CertificateStructure.GetInstance(cert.GetEncoded()).Issuer)), new DerInteger(cert.SerialNumber)); byte[] certHash256; byte[] certHash; { Asn1DigestFactory digCalc = Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1); IStreamCalculator calc = digCalc.CreateCalculator(); using (Stream s = calc.Stream) { byte[] crt = cert.GetEncoded(); s.Write(crt, 0, crt.Length); } certHash = ((SimpleBlockResult)calc.GetResult()).Collect(); } { Asn1DigestFactory digCalc = Asn1DigestFactory.Get(NistObjectIdentifiers.IdSha256); IStreamCalculator calc = digCalc.CreateCalculator(); using (Stream s = calc.Stream) { byte[] crt = cert.GetEncoded(); s.Write(crt, 0, crt.Length); } certHash256 = ((SimpleBlockResult)calc.GetResult()).Collect(); } EssCertID essCertid = new EssCertID(certHash, issuerSerial); EssCertIDv2 essCertidV2 = new EssCertIDv2(certHash256, issuerSerial); signerInfoGenBuilder.WithSignedAttributeGenerator(new TestAttrGen() { EssCertID = essCertid, EssCertIDv2 = essCertidV2 }); Asn1SignatureFactory sigfact = new Asn1SignatureFactory("SHA1WithRSA", privateKey); SignerInfoGenerator signerInfoGenerator = signerInfoGenBuilder.Build(sigfact, cert); TimeStampTokenGenerator tsTokenGen = new TimeStampTokenGenerator( signerInfoGenerator, Asn1DigestFactory.Get(OiwObjectIdentifiers.IdSha1), new DerObjectIdentifier("1.2"), true); tsTokenGen.SetCertificates(certs); 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); Asn1.Cms.AttributeTable table = tsToken.SignedAttributes; Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificate], "no signingCertificate attribute found"); Assert.NotNull(table[PkcsObjectIdentifiers.IdAASigningCertificateV2], "no signingCertificateV2 attribute found"); SigningCertificate sigCert = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificate].AttrValues[0]); Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCert.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name)); Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCert.GetCerts()[0].IssuerSerial.Serial.Value)); Assert.IsTrue(Arrays.AreEqual(certHash, sigCert.GetCerts()[0].GetCertHash())); SigningCertificate sigCertV2 = SigningCertificate.GetInstance(table[PkcsObjectIdentifiers.IdAASigningCertificateV2].AttrValues[0]); Assert.IsTrue(cert.CertificateStructure.Issuer.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Issuer.GetNames()[0].Name)); Assert.IsTrue(cert.CertificateStructure.SerialNumber.Value.Equals(sigCertV2.GetCerts()[0].IssuerSerial.Serial.Value)); Assert.IsTrue(Arrays.AreEqual(certHash256, sigCertV2.GetCerts()[0].GetCertHash())); }
/// <summary> /// Validates the time-stamp token in case of arbitration or with a specified trusted time. /// </summary> /// <param name="tst">The timestamp to validate</param> /// <param name="crls">Known Crl's, new retrieved crl's will be added here</param> /// <param name="ocsps">Known Ocsp's, new retrieved ocsp's will be added here</param> /// <param name="trustedTime">The trusted time, <c>null</c> for the timestamp time</param> /// <returns>The validation chain of the signing certificate</returns> public static async Task <Timestamp> ValidateAsync(this TimeStampToken tst, IList <CertificateList> crls, IList <BasicOcspResponse> ocsps, DateTime?trustedTime) { return(await tst.ValidateAsync(null, crls, ocsps, trustedTime)); }
private static MessageReport.Signature InspectSignature(AcroFields fields, String name, SignaturePermissions perms) { MessageReport.Signature sigInfo = new MessageReport.Signature(); IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name); if (fps != null && fps.Count > 0) { AcroFields.FieldPosition fp = fps[0]; Rectangle pos = fp.position; if (pos.Width == 0 || pos.Height == 0) { sigInfo.visible = false; } else { sigInfo.visible = true; } } PdfPKCS7 pkcs7 = VerifySignature(fields, name, ref sigInfo); sigInfo.digestAlgorithm = pkcs7.GetHashAlgorithm(); sigInfo.encryptionAlgorithm = pkcs7.GetEncryptionAlgorithm(); sigInfo.isRevocationValid = pkcs7.IsRevocationValid(); X509Certificate cert = pkcs7.SigningCertificate; sigInfo.signerName = CertificateInfo.GetSubjectFields(cert).GetField("CN"); if (pkcs7.SignName != null) { sigInfo.signerName = pkcs7.SignName; } sigInfo.signDate = pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff"); if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue)) { sigInfo.isTimestampped = true; sigInfo.timestampDate = pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff"); TimeStampToken ts = pkcs7.TimeStampToken; sigInfo.timestampName = ts.TimeStampInfo.Tsa.ToString(); } sigInfo.signLocation = pkcs7.Location; sigInfo.signReason = pkcs7.Reason; PdfDictionary sigDict = fields.GetSignatureDictionary(name); PdfString contact = sigDict.GetAsString(PdfName.CONTACTINFO); if (contact != null) { Console.WriteLine("Contact info: " + contact); } perms = new SignaturePermissions(sigDict, perms); sigInfo.signatureType = (perms.Certification ? "certification" : "approval"); return(sigInfo); }
/// <summary> /// Validates the time-stamp token with a specified trusted time. /// </summary> /// <param name="tst">The timestamp to validate</param> /// <param name="crls">Known Crl's, new retrieved crl's will be added here</param> /// <param name="ocsps">Known Ocsp's, new retrieved ocsp's will be added here</param> /// <param name="trustedTime">The trusted time, <c>null</c> for the timestamp time</param> /// <returns>The validation chain of the signing certificate</returns> public static Timestamp Validate(this TimeStampToken tst, IList <CertificateList> crls, IList <BasicOcspResponse> ocsps, DateTime?trustedTime) { return(tst.Validate(null, crls, ocsps, trustedTime)); }
/// <summary> /// Validates the time-stamp token trusting the time of the token itself /// </summary> /// <param name="tst">The timestamp to validate</param> /// <param name="extraCerts">Extra intermediate certificates</param> /// <param name="crls">Known Crl's, new retrieved crl's will be added here</param> /// <param name="ocsps">Known Ocsp's, new retrieved ocsp's will be added here</param> /// <returns>The validation chain of the signing certificate</returns> public static async Task <Timestamp> ValidateAsync(this TimeStampToken tst, X509Certificate2Collection extraCerts, IList <CertificateList> crls, IList <BasicOcspResponse> ocsps) { return(await tst.ValidateAsync(extraCerts, crls, ocsps, null)); }
/// <summary> /// Validates the time-stamp token trusting the time of the token itself /// </summary> /// <param name="tst">The timestamp to validate</param> /// <param name="extraCerts">Extra intermediate certificates</param> /// <param name="crls">Known Crl's, new retrieved crl's will be added here</param> /// <param name="ocsps">Known Ocsp's, new retrieved ocsp's will be added here</param> /// <returns>The validation chain of the signing certificate</returns> public static Timestamp Validate(this TimeStampToken tst, X509Certificate2Collection extraCerts, IList <CertificateList> crls, IList <BasicOcspResponse> ocsps) { return(tst.Validate(extraCerts, crls, ocsps, null)); }
public ValidationResult Validate(SignatureDocument sigDocument) { /* Los elementos que se validan son: * * 1. Las huellas de las referencias de la firma. * 2. Se comprueba la huella del elemento SignedInfo y se verifica la firma con la clave pública del certificado. * 3. Si la firma contiene un sello de tiempo se comprueba que la huella de la firma coincide con la del sello de tiempo. * * La validación de perfiles -C, -X, -XL y -A esta fuera del ámbito de este proyecto. */ ValidationResult result = new ValidationResult(); try { // Verifica las huellas de las referencias y la firma sigDocument.XadesSignature.CheckXmldsigSignature(); } catch (Exception ex) { result.IsValid = false; result.Message = "La verificación de la firma no ha sido satisfactoria"; return(result); } if (sigDocument.XadesSignature.UnsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count > 0) { // Se comprueba el sello de tiempo TimeStamp timeStamp = sigDocument.XadesSignature.UnsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection[0]; TimeStampToken token = new TimeStampToken(new CmsSignedData(timeStamp.EncapsulatedTimeStamp.PkiData)); byte[] tsHashValue = token.TimeStampInfo.GetMessageImprintDigest(); Crypto.DigestMethod tsDigestMethod = Crypto.DigestMethod.GetByOid(token.TimeStampInfo.HashAlgorithm.ObjectID.Id); System.Security.Cryptography.Xml.Transform transform = null; if (timeStamp.CanonicalizationMethod != null) { transform = CryptoConfig.CreateFromName(timeStamp.CanonicalizationMethod.Algorithm) as System.Security.Cryptography.Xml.Transform; } else { transform = new XmlDsigC14NTransform(); } ArrayList signatureValueElementXpaths = new ArrayList(); signatureValueElementXpaths.Add("ds:SignatureValue"); byte[] signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(sigDocument.XadesSignature, signatureValueElementXpaths, transform), tsDigestMethod); if (!Arrays.AreEqual(tsHashValue, signatureValueHash)) { result.IsValid = false; result.Message = "La huella del sello de tiempo no se corresponde con la calculada"; return(result); } } result.IsValid = true; result.Message = "Verificación de la firma satisfactoria"; return(result); }
/* * private void verifyTimestamp(TimeStampToken token, X509CRL crl) throws SignVerificationException, XPathExpressionException { * // Read timestamp signature certificate * X509CertificateHolder signCert = getTimestampSignatureCertificate(token); * if (signCert == null) { * throw new SignVerificationException("Cannot retrieve timestamp signature certificate (Rule 26)."); * } * * // Rule 26 - Validity * // Check current certificate validity * if (!signCert.isValidOn(new Date())) { * throw new SignVerificationException("Timestamp signature certificate is not valid now (Rule 26)."); * } * * // Check against CRL * X509CRLEntry entry = crl.getRevokedCertificate(signCert.getSerialNumber()); * if (entry != null) { * throw new SignVerificationException("Timestamp signature certificate is revoked (Rule 26)."); * } * * // Rule 27 - Message imprint * byte[] timestampDigest = token.getTimeStampInfo().getMessageImprintDigest(); * String hashAlgorithm = token.getTimeStampInfo().getHashAlgorithm().getAlgorithm().getId(); * * Element signature = querySelector("//ds:Signature/ds:SignatureValue", "Cannot find element 'ds:SignatureValue' (Rule 27)."); * byte[] signatureValue = Base64.decode(signature.getTextContent().getBytes()); * * MessageDigest messageDigest = null; * try { * messageDigest = MessageDigest.getInstance(hashAlgorithm, "BC"); * } catch (NoSuchAlgorithmException | NoSuchProviderException e) { * throw new SignVerificationException("Unsupported digest type (Rule 27)."); * } * * byte[] signatureDigest = messageDigest.digest(signatureValue); * if (!Arrays.equals(timestampDigest, signatureDigest)) { * throw new SignVerificationException("Timestamp MessageImprint check failure (Rule 27)."); * } * }*/ private bool validateTimestamp() { TimeStampToken token = null; X509Crl ss = null; XmlNamespaceManager mn = new XmlNamespaceManager(doc.NameTable); X509CrlParser xx = new X509CrlParser(); mn.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#"); string crlUrl = "http://test.ditec.sk/DTCCACrl/DTCCACrl.crl"; Org.BouncyCastle.X509.X509Certificate signerCert = null; try { var timestamp = this.doc.SelectSingleNode($"//xades:EncapsulatedTimeStamp", mn); var webClient = new WebClient(); byte[] crlBytes = webClient.DownloadData(crlUrl); token = new TimeStampToken(new CmsSignedData(Convert.FromBase64String(timestamp.InnerText))); ss = xx.ReadCrl(crlBytes); if (timestamp == null || crlBytes == null || token == null || ss == null) { generalException(new Exception()); return(false); } var store = token.GetCertificates("Collection"); var certs = new ArrayList(store.GetMatches(null)); foreach (Org.BouncyCastle.X509.X509Certificate cert in certs) { string cerIssuer = cert.IssuerDN.ToString(true, new Hashtable()); string signIssuer = token.SignerID.Issuer.ToString(true, new Hashtable()); if (cerIssuer == signIssuer && cert.SerialNumber.Equals(token.SignerID.SerialNumber)) { signerCert = cert; if (signerCert == null) { generalException(new Exception()); return(false); } break; } } if (!signerCert.IsValidNow) { return(false); } X509CrlEntry revokeCheck = ss.GetRevokedCertificate(signerCert.SerialNumber); if (revokeCheck == null) { generalException(new Exception()); return(false); } } catch (Exception e) { generalException(e); } return(false); }
/// <summary> /// Validates the time-stamp token trusting the time of the token itself /// </summary> /// <param name="tst">The timestamp to validate</param> /// <returns>The validation chain of the signing certificate</returns> public static Timestamp Validate(this TimeStampToken tst) { return(tst.Validate(new List <CertificateList>(), new List <BasicOcspResponse>())); }
internal static void IsSignatureValid(TimeStampToken validator, X509Certificate certStoreX509) { validator.Validate(certStoreX509); }
/// <summary> /// Validates the time-stamp token trusting the time of the token itself /// </summary> /// <param name="tst">The timestamp to validate</param> /// <param name="crls">Known Crl's, new retrieved crl's will be added here</param> /// <param name="ocsps">Known Ocsp's, new retrieved ocsp's will be added here</param> /// <returns>The validation chain of the signing certificate</returns> public static Timestamp Validate(this TimeStampToken tst, IList <CertificateList> crls, IList <BasicOcspResponse> ocsps) { return(tst.Validate(crls, ocsps, null)); }
/// <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); }