Exemplo n.º 1
0
        public TimeStampTokenGenerator(AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;
            TspUtil.ValidateCertificate(cert);
            IDictionary dictionary;

            if (signedAttr != null)
            {
                dictionary = signedAttr.ToDictionary();
            }
            else
            {
                dictionary = Platform.CreateHashtable();
            }
            try
            {
                byte[]    hash      = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());
                EssCertID essCertID = new EssCertID(hash);
                Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertID)));
                dictionary[attribute.AttrType] = attribute;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e2)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e2);
            }
            this.signedAttr = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
        }
Exemplo n.º 2
0
        /**
         * Validate the timestamp request, checking the digest to see if it is of an
         * accepted type and whether it is of the correct length for the algorithm specified.
         *
         * @param algorithms a set of string OIDS giving accepted algorithms.
         * @param policies if non-null a set of policies we are willing to sign under.
         * @param extensions if non-null a set of extensions we are willing to accept.
         * @throws TspException if the request is invalid, or processing fails.
         */
        public void Validate(
            IList algorithms,
            IList policies,
            IList extensions)
        {
            if (!algorithms.Contains(this.MessageImprintAlgOid))
            {
                throw new TspValidationException("request contains unknown algorithm.", PkiFailureInfo.BadAlg);
            }

            if (policies != null && this.ReqPolicy != null && !policies.Contains(this.ReqPolicy))
            {
                throw new TspValidationException("request contains unknown policy.", PkiFailureInfo.UnacceptedPolicy);
            }

            if (this.Extensions != null && extensions != null)
            {
                foreach (DerObjectIdentifier oid in this.Extensions.ExtensionOids)
                {
                    if (!extensions.Contains(oid.Id))
                    {
                        throw new TspValidationException("request contains unknown extension.",
                                                         PkiFailureInfo.UnacceptedExtension);
                    }
                }
            }

            int digestLength = TspUtil.GetDigestLength(this.MessageImprintAlgOid);

            if (digestLength != this.GetMessageImprintDigest().Length)
            {
                throw new TspValidationException("imprint digest the wrong length.",
                                                 PkiFailureInfo.BadDataFormat);
            }
        }
Exemplo n.º 3
0
        public void Validate(IList algorithms, IList policies, IList extensions)
        {
            if (!algorithms.Contains(this.MessageImprintAlgOid))
            {
                throw new TspValidationException("request contains unknown algorithm.", 128);
            }
            if (policies != null && this.ReqPolicy != null && !policies.Contains(this.ReqPolicy))
            {
                throw new TspValidationException("request contains unknown policy.", 256);
            }
            if (this.Extensions != null && extensions != null)
            {
                foreach (DerObjectIdentifier derObjectIdentifier in this.Extensions.ExtensionOids)
                {
                    if (!extensions.Contains(derObjectIdentifier.Id))
                    {
                        throw new TspValidationException("request contains unknown extension.", 8388608);
                    }
                }
            }
            int digestLength = TspUtil.GetDigestLength(this.MessageImprintAlgOid);

            if (digestLength != this.GetMessageImprintDigest().Length)
            {
                throw new TspValidationException("imprint digest the wrong length.", 4);
            }
        }
Exemplo n.º 4
0
        internal static SignerInfoGenerator makeInfoGenerator(
            AsymmetricKeyParameter key,
            X509Certificate cert,
            string digestOID,

            Asn1.Cms.AttributeTable signedAttr,
            Asn1.Cms.AttributeTable unsignedAttr)
        {
            TspUtil.ValidateCertificate(cert);

            //
            // Add the ESSCertID attribute
            //
            IDictionary signedAttrs;

            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToDictionary();
            }
            else
            {
                signedAttrs = Platform.CreateHashtable();
            }

            //try
            //{
            //    byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

            //    EssCertID essCertid = new EssCertID(hash);

            //    Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
            //        PkcsObjectIdentifiers.IdAASigningCertificate,
            //        new DerSet(new SigningCertificate(essCertid)));

            //    signedAttrs[attr.AttrType] = attr;
            //}
            //catch (CertificateEncodingException e)
            //{
            //    throw new TspException("Exception processing certificate.", e);
            //}
            //catch (SecurityUtilityException e)
            //{
            //    throw new TspException("Can't find a SHA-1 implementation.", e);
            //}


            string digestName    = CmsSignedHelper.Instance.GetDigestAlgName(digestOID);
            string signatureName = digestName + "with" + CmsSignedHelper.Instance.GetEncryptionAlgName(CmsSignedHelper.Instance.GetEncOid(key, digestOID));

            Asn1SignatureFactory sigfact = new Asn1SignatureFactory(signatureName, key);

            return(new SignerInfoGeneratorBuilder()
                   .WithSignedAttributeGenerator(
                       new DefaultSignedAttributeTableGenerator(
                           new Asn1.Cms.AttributeTable(signedAttrs)))
                   .WithUnsignedAttributeGenerator(
                       new SimpleAttributeTableGenerator(unsignedAttr))
                   .Build(sigfact, cert));
        }
Exemplo n.º 5
0
 public void Validate(X509Certificate cert)
 {
     try
     {
         byte[] b = DigestUtilities.CalculateDigest(certID.GetHashAlgorithmName(), cert.GetEncoded());
         if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), b))
         {
             throw new TspValidationException("certificate hash does not match certID hash.");
         }
         if (certID.IssuerSerial != null)
         {
             if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
             {
                 throw new TspValidationException("certificate serial number does not match certID for signature.");
             }
             GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
             X509Name      issuerX509Principal = PrincipalUtilities.GetIssuerX509Principal(cert);
             bool          flag = false;
             for (int i = 0; i != names.Length; i++)
             {
                 if (names[i].TagNo == 4 && X509Name.GetInstance(names[i].Name).Equivalent(issuerX509Principal))
                 {
                     flag = true;
                     break;
                 }
             }
             if (!flag)
             {
                 throw new TspValidationException("certificate name does not match certID for signature. ");
             }
         }
         TspUtil.ValidateCertificate(cert);
         cert.CheckValidity(tstInfo.GenTime);
         if (!tsaSignerInfo.Verify(cert))
         {
             throw new TspValidationException("signature not created by certificate.");
         }
     }
     catch (CmsException ex)
     {
         if (((global::System.Exception)ex).get_InnerException() != null)
         {
             throw new TspException(((global::System.Exception)ex).get_Message(), ((global::System.Exception)ex).get_InnerException());
         }
         throw new TspException(string.Concat((object)"CMS exception: ", (object)ex), ex);
     }
     catch (CertificateEncodingException ex2)
     {
         throw new TspException(string.Concat((object)"problem processing certificate: ", (object)ex2), ex2);
     }
     catch (SecurityUtilityException ex3)
     {
         throw new TspException("cannot find algorithm: " + ((global::System.Exception)ex3).get_Message(), ex3);
     }
 }
Exemplo n.º 6
0
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
            AsymmetricKeyParameter key,
            X509Certificate cert,
            string digestOID,
            string tsaPolicyOID,
            Asn1.Cms.AttributeTable signedAttr,
            Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // Add the ESSCertID attribute
            //
            Hashtable signedAttrs;

            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            try
            {
                byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
Exemplo n.º 7
0
        public void Validate(global::System.Collections.IList algorithms, global::System.Collections.IList policies, global::System.Collections.IList extensions)
        {
            if (!algorithms.Contains((object)MessageImprintAlgOid))
            {
                throw new TspValidationException("request contains unknown algorithm.", 128);
            }
            if (policies != null && ReqPolicy != null && !policies.Contains((object)ReqPolicy))
            {
                throw new TspValidationException("request contains unknown policy.", 256);
            }
            if (Extensions != null && extensions != null)
            {
                {
                    global::System.Collections.IEnumerator enumerator = Extensions.ExtensionOids.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current();
                            if (!extensions.Contains((object)derObjectIdentifier.Id))
                            {
                                throw new TspValidationException("request contains unknown extension.", 8388608);
                            }
                        }
                    }
                    finally
                    {
                        global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
            }
            int digestLength = TspUtil.GetDigestLength(MessageImprintAlgOid);

            if (digestLength != GetMessageImprintDigest().Length)
            {
                throw new TspValidationException("imprint digest the wrong length.", 4);
            }
        }
Exemplo n.º 8
0
        /**
         * Validate the timestamp request, checking the digest to see if it is of an
         * accepted type and whether it is of the correct length for the algorithm specified.
         *
         * @param algorithms a set of string OIDS giving accepted algorithms.
         * @param policies if non-null a set of policies we are willing to sign under.
         * @param extensions if non-null a set of extensions we are willing to accept.
         * @param provider the provider to confirm the digest size against.
         * @throws TspException if the request is invalid, or processing fails.
         */
        public void Validate(
            IList algorithms,
            IList policies,
            IList extensions)
        {
            if (!algorithms.Contains(this.MessageImprintAlgOid))
            {
                throw new TspValidationException("request contains unknown algorithm.", PkiFailureInfo.BadAlg);
            }

            if (policies != null && this.ReqPolicy != null && !policies.Contains(this.ReqPolicy))
            {
                throw new TspValidationException("request contains unknown policy.", PkiFailureInfo.UnacceptedPolicy);
            }

            if (this.Extensions != null && extensions != null)
            {
                foreach (DerObjectIdentifier oid in this.Extensions.ExtensionOids)
                {
                    if (!extensions.Contains(oid.Id))
                    {
                        throw new TspValidationException("request contains unknown extension.",
                                                         PkiFailureInfo.UnacceptedExtension);
                    }
                }
            }

            string digestName = TspUtil.GetDigestAlgName(this.MessageImprintAlgOid);

            IDigest digest;

            try
            {
                digest = DigestUtilities.GetDigest(digestName);
            }
            catch (Exception ex)
            {
                throw new TspException("digest algorithm cannot be found.", ex);
            }

            checkImprintLength(digest);
        }
Exemplo n.º 9
0
        public static ICollection GetSignatureTimestamps(SignerInformation signerInfo)
        {
            IList list = Platform.CreateArrayList();

            Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInfo.UnsignedAttributes;
            if (unsignedAttributes != null)
            {
                foreach (Org.BouncyCastle.Asn1.Cms.Attribute attribute in unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken))
                {
                    foreach (Asn1Encodable asn1Encodable in attribute.AttrValues)
                    {
                        try
                        {
                            Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(asn1Encodable.ToAsn1Object());
                            TimeStampToken     timeStampToken = new TimeStampToken(instance);
                            TimeStampTokenInfo timeStampInfo  = timeStampToken.TimeStampInfo;
                            byte[]             a = DigestUtilities.CalculateDigest(TspUtil.GetDigestAlgName(timeStampInfo.MessageImprintAlgOid), signerInfo.GetSignature());
                            if (!Arrays.ConstantTimeAreEqual(a, timeStampInfo.GetMessageImprintDigest()))
                            {
                                throw new TspValidationException("Incorrect digest in message imprint");
                            }
                            list.Add(timeStampToken);
                        }
                        catch (SecurityUtilityException)
                        {
                            throw new TspValidationException("Unknown hash algorithm specified in timestamp");
                        }
                        catch (Exception)
                        {
                            throw new TspValidationException("Timestamp could not be parsed");
                        }
                    }
                }
            }
            return(list);
        }
Exemplo n.º 10
0
        /**
         * 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>
         */
        public void Validate(
            X509Certificate cert)
        {
            try
            {
                byte[] hash = DigestUtilities.CalculateDigest(
                    certID.GetHashAlgorithm(), cert.GetEncoded());

                if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), hash))
                {
                    throw new TspValidationException("certificate hash does not match certID hash.");
                }

                if (certID.IssuerSerial != null)
                {
                    if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
                    {
                        throw new TspValidationException("certificate serial number does not match certID for signature.");
                    }

                    GeneralName[] names     = certID.IssuerSerial.Issuer.GetNames();
                    X509Name      principal = PrincipalUtilities.GetIssuerX509Principal(cert);
                    bool          found     = false;

                    for (int i = 0; i != names.Length; i++)
                    {
                        if (names[i].TagNo == 4 &&
                            X509Name.GetInstance(names[i].Name).Equivalent(principal))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        throw new TspValidationException("certificate name does not match certID for signature. ");
                    }
                }

                TspUtil.ValidateCertificate(cert);

                cert.CheckValidity(tstInfo.GenTime);

                if (!tsaSignerInfo.Verify(cert))
                {
                    throw new TspValidationException("signature not created by certificate.");
                }
            }
            catch (CmsException e)
            {
                if (e.InnerException != null)
                {
                    throw new TspException(e.Message, e.InnerException);
                }

                throw new TspException("CMS exception: " + e, e);
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("problem processing certificate: " + e, e);
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("cannot find algorithm: " + e.Message, e);
            }
        }
Exemplo n.º 11
0
        public TimeStampTokenGenerator(
            SignerInfoGenerator signerInfoGen,
            IDigestFactory digestCalculator,
            DerObjectIdentifier tsaPolicy,
            bool isIssuerSerialIncluded)
        {
            this.signerInfoGenerator = signerInfoGen;
            this.digestCalculator    = digestCalculator;
            this.tsaPolicyOID        = tsaPolicy != null ? tsaPolicy.Id : null;

            if (signerInfoGenerator.certificate == null)
            {
                throw new ArgumentException("SignerInfoGenerator must have an associated certificate");
            }

            X509Certificate assocCert = signerInfoGenerator.certificate;

            TspUtil.ValidateCertificate(assocCert);

            try
            {
                IStreamCalculator calculator = digestCalculator.CreateCalculator();
                Stream            stream     = calculator.Stream;
                byte[]            certEnc    = assocCert.GetEncoded();
                stream.Write(certEnc, 0, certEnc.Length);
                stream.Flush();
                stream.Close();

                if (((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm.Equals(OiwObjectIdentifiers.IdSha1))
                {
                    EssCertID essCertID = new EssCertID(
                        ((IBlockResult)calculator.GetResult()).Collect(),
                        isIssuerSerialIncluded ?
                        new IssuerSerial(
                            new GeneralNames(
                                new GeneralName(assocCert.IssuerDN)),
                            new DerInteger(assocCert.SerialNumber)) : null);

                    this.signerInfoGenerator = signerInfoGen.NewBuilder()
                                               .WithSignedAttributeGenerator(new TableGen(signerInfoGen, essCertID))
                                               .Build(signerInfoGen.contentSigner, signerInfoGen.certificate);
                }
                else
                {
                    AlgorithmIdentifier digestAlgID = new AlgorithmIdentifier(
                        ((AlgorithmIdentifier)digestCalculator.AlgorithmDetails).Algorithm);

                    EssCertIDv2 essCertID = new EssCertIDv2(
                        ((IBlockResult)calculator.GetResult()).Collect(),
                        isIssuerSerialIncluded ?
                        new IssuerSerial(
                            new GeneralNames(
                                new GeneralName(assocCert.IssuerDN)),
                            new DerInteger(assocCert.SerialNumber)) : null);

                    this.signerInfoGenerator = signerInfoGen.NewBuilder()
                                               .WithSignedAttributeGenerator(new TableGen2(signerInfoGen, essCertID))
                                               .Build(signerInfoGen.contentSigner, signerInfoGen.certificate);
                }
            }
            catch (Exception ex)
            {
                throw new TspException("Exception processing certificate", ex);
            }
        }
Exemplo n.º 12
0
 public virtual IList GetExtensionOids()
 {
     return(TspUtil.GetExtensionOids(this.extensions));
 }
Exemplo n.º 13
0
 public virtual global::System.Collections.IList GetExtensionOids()
 {
     return(TspUtil.GetExtensionOids(extensions));
 }
Exemplo n.º 14
0
        internal static IDigest CreateDigestInstance(string digestAlgOID)
        {
            string digestAlgName = TspUtil.GetDigestAlgName(digestAlgOID);

            return(DigestUtilities.GetDigest(digestAlgName));
        }