/**
         * Return an appropriate TimeStampResponse.
         * <p>
         * If genTime is null a timeNotAvailable error response will be returned.
         *
         * @param request the request this response is for.
         * @param serialNumber serial number for the response token.
         * @param genTime generation time for the response token.
         * @param provider provider to use for signature calculation.
         * @return
         * @throws NoSuchAlgorithmException
         * @throws NoSuchProviderException
         * @throws TSPException
         * </p>
         */
        public TimeStampResponse Generate(
            TimeStampRequest request,
            BigInteger serialNumber,
            DateTimeObject genTime)
        {
            TimeStampResp resp;

            try
            {
                if (genTime == null)
                {
                    throw new TspValidationException("The time source is not available.",
                                                     PkiFailureInfo.TimeNotAvailable);
                }

                request.Validate(acceptedAlgorithms, acceptedPolicies, acceptedExtensions);

                this.status = PkiStatus.Granted;
                this.AddStatusString("Operation Okay");

                PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();

                ContentInfo tstTokenContentInfo;
                try
                {
                    TimeStampToken token   = tokenGenerator.Generate(request, serialNumber, genTime.Value);
                    byte[]         encoded = token.ToCmsSignedData().GetEncoded();

                    tstTokenContentInfo = ContentInfo.GetInstance(Asn1Object.FromByteArray(encoded));
                }
                catch (IOException e)
                {
                    throw new TspException("Timestamp token received cannot be converted to ContentInfo", e);
                }

                resp = new TimeStampResp(pkiStatusInfo, tstTokenContentInfo);
            }
            catch (TspValidationException e)
            {
                status = PkiStatus.Rejection;

                this.SetFailInfoField(e.FailureCode);
                this.AddStatusString(e.Message);

                PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();

                resp = new TimeStampResp(pkiStatusInfo, null);
            }

            try
            {
                return(new TimeStampResponse(resp));
            }
            catch (IOException e)
            {
                throw new TspException("created badly formatted response!", e);
            }
        }
Beispiel #2
0
 private X509AttrCertStoreSelector(
     X509AttrCertStoreSelector o)
 {
     this.attributeCert             = o.attributeCert;
     this.attributeCertificateValid = o.attributeCertificateValid;
     this.holder       = o.holder;
     this.issuer       = o.issuer;
     this.serialNumber = o.serialNumber;
 }
Beispiel #3
0
 /**
  * Verifies a certificate against a single OCSP response
  * @param ocspResp	the OCSP response
  * @param issuerCert
  * @param signDate
  * @return
  * @throws GeneralSecurityException
  * @throws IOException
  */
 virtual public bool Verify(BasicOcspResp ocspResp, X509Certificate signCert, X509Certificate issuerCert, DateTime signDate)
 {
     if (ocspResp == null)
     {
         return(false);
     }
     // Getting the responses
     SingleResp[] resp = ocspResp.Responses;
     for (int i = 0; i < resp.Length; ++i)
     {
         // check if the serial number corresponds
         if (!signCert.SerialNumber.Equals(resp[i].GetCertID().SerialNumber))
         {
             continue;
         }
         // check if the issuer matches
         try {
             if (issuerCert == null)
             {
                 issuerCert = signCert;
             }
             if (!resp[i].GetCertID().MatchesIssuer(issuerCert))
             {
                 LOGGER.Info("OCSP: Issuers doesn't match.");
                 continue;
             }
         } catch (OcspException) {
             continue;
         }
         // check if the OCSP response was valid at the time of signing
         DateTimeObject nextUpdate = resp[i].NextUpdate;
         DateTime       nextUpdateDate;
         if (nextUpdate == null)
         {
             nextUpdateDate = resp[i].ThisUpdate.AddSeconds(180);
             LOGGER.Info("No 'next update' for OCSP Response; assuming " + nextUpdateDate);
         }
         else
         {
             nextUpdateDate = nextUpdate.Value;
         }
         if (signDate > nextUpdateDate)
         {
             LOGGER.Info(String.Format("OCSP no longer valid: {0} after {1}", signDate, nextUpdateDate));
             continue;
         }
         // check the status of the certificate
         Object status = resp[i].GetCertStatus();
         if (status == CertificateStatus.Good)
         {
             // check if the OCSP response was genuine
             IsValidResponse(ocspResp, issuerCert);
             return(true);
         }
     }
     return(false);
 }
Beispiel #4
0
 private X509AttrCertStoreSelector(X509AttrCertStoreSelector o)
 {
     attributeCert             = o.attributeCert;
     attributeCertificateValid = o.attributeCertificateValid;
     holder       = o.holder;
     issuer       = o.issuer;
     serialNumber = o.serialNumber;
     targetGroups = new HashSet(o.targetGroups);
     targetNames  = new HashSet(o.targetNames);
 }
Beispiel #5
0
        internal static DateTime GetValidDate(PkixParameters paramsPKIX)
        {
            DateTimeObject date = paramsPKIX.Date;

            if (date == null)
            {
                return(DateTime.UtcNow);
            }
            return(date.Value);
        }
 public X509CrlStoreSelector(X509CrlStoreSelector o)
 {
     certificateChecking             = o.CertificateChecking;
     dateAndTime                     = o.DateAndTime;
     issuers                         = o.Issuers;
     maxCrlNumber                    = o.MaxCrlNumber;
     minCrlNumber                    = o.MinCrlNumber;
     deltaCrlIndicatorEnabled        = o.DeltaCrlIndicatorEnabled;
     completeCrlEnabled              = o.CompleteCrlEnabled;
     maxBaseCrlNumber                = o.MaxBaseCrlNumber;
     attrCertChecking                = o.AttrCertChecking;
     issuingDistributionPointEnabled = o.IssuingDistributionPointEnabled;
     issuingDistributionPoint        = o.IssuingDistributionPoint;
 }
Beispiel #7
0
 public X509CrlStoreSelector(X509CrlStoreSelector o)
 {
     this.certificateChecking             = o.CertificateChecking;
     this.dateAndTime                     = o.DateAndTime;
     this.issuers                         = o.Issuers;
     this.maxCrlNumber                    = o.MaxCrlNumber;
     this.minCrlNumber                    = o.MinCrlNumber;
     this.deltaCrlIndicatorEnabled        = o.DeltaCrlIndicatorEnabled;
     this.completeCrlEnabled              = o.CompleteCrlEnabled;
     this.maxBaseCrlNumber                = o.MaxBaseCrlNumber;
     this.attrCertChecking                = o.AttrCertChecking;
     this.issuingDistributionPointEnabled = o.IssuingDistributionPointEnabled;
     this.issuingDistributionPoint        = o.IssuingDistributionPoint;
 }
Beispiel #8
0
        static async Task Main(string[] args)
        {
            const string serverUrl = "http://localhost:5000";

            IDateTimeApi api = new DateTimeApi(serverUrl);

            try {
                DateTimeObject response = await api.GetUtcDateTimeAsync();

                Console.WriteLine($"Server date-time: {response.DateTime}");
            }
            catch (ApiException ex) {
                Console.Error.WriteLine($"Unexpected error occurred: {ex.Message}");
            }
        }
Beispiel #9
0
        public void Invoke(string func)
        {
            var result = string.Empty;

            if (func == "ShowDate")
            {
                result = DateTimeObject.GetDate();
            }

            if (func == "ShowTime")
            {
                result = DateTimeObject.GetTime();
            }

            Callback(result);
        }
Beispiel #10
0
        public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
        {
            var func   = message.Body.ToString();
            var result = string.Empty;

            if (func == "ShowDate")
            {
                result = DateTimeObject.GetDate();
            }

            if (func == "ShowTime")
            {
                result = DateTimeObject.GetTime();
            }

            Callback(result);
        }
 public X509CertStoreSelector(X509CertStoreSelector o)
 {
     this.authorityKeyIdentifier = o.AuthorityKeyIdentifier;
     this.basicConstraints       = o.BasicConstraints;
     this.certificate            = o.Certificate;
     this.certificateValid       = o.CertificateValid;
     this.extendedKeyUsage       = o.ExtendedKeyUsage;
     this.issuer                = o.Issuer;
     this.keyUsage              = o.KeyUsage;
     this.policy                = o.Policy;
     this.privateKeyValid       = o.PrivateKeyValid;
     this.serialNumber          = o.SerialNumber;
     this.subject               = o.Subject;
     this.subjectKeyIdentifier  = o.SubjectKeyIdentifier;
     this.subjectPublicKey      = o.SubjectPublicKey;
     this.subjectPublicKeyAlgID = o.SubjectPublicKeyAlgID;
 }
Beispiel #12
0
 public X509CertStoreSelector(X509CertStoreSelector o)
 {
     authorityKeyIdentifier = o.AuthorityKeyIdentifier;
     basicConstraints       = o.BasicConstraints;
     certificate            = o.Certificate;
     certificateValid       = o.CertificateValid;
     extendedKeyUsage       = o.ExtendedKeyUsage;
     issuer                = o.Issuer;
     keyUsage              = o.KeyUsage;
     policy                = o.Policy;
     privateKeyValid       = o.PrivateKeyValid;
     serialNumber          = o.SerialNumber;
     subject               = o.Subject;
     subjectKeyIdentifier  = o.SubjectKeyIdentifier;
     subjectPublicKey      = o.SubjectPublicKey;
     subjectPublicKeyAlgID = o.SubjectPublicKeyAlgID;
 }
Beispiel #13
0
        private bool CheckTimeValidity(DateTime thisUpate, DateTimeObject nextUpdate, int skew, int maxage)
        {
            DateTime tmp;
            long     t1, t2;
            DateTime now = DateTime.UtcNow;

            t1 = now.Ticks;

            tmp = thisUpate.AddMilliseconds(skew);
            t2  = tmp.Ticks;

            if (t2 < t1)
            {
                return(false);
            }

            tmp = thisUpate.AddMilliseconds(maxage);
            t2  = tmp.Ticks;
            if (t2 < t1)
            {
                return(false);
            }

            if (nextUpdate != null)
            {
                DateTime next = nextUpdate.Value;

                tmp = next.AddMilliseconds(-skew);
                t2  = tmp.Ticks;

                if (t2 < t1)
                {
                    return(false);
                }

                // nextUpdate precedes thisUpdate ?
                if (thisUpate.CompareTo(next) > 0)
                {
                    return(false);
                }
            }

            return(true);
        }
        public DateTimeObject RedactDateTime(DateTimeObject dateObject)
        {
            EnsureArg.IsNotNull(dateObject, nameof(dateObject));

            if (Settings.EnablePartialDatesForRedact)
            {
                if (DateTimeUtility.IndicateAgeOverThreshold(dateObject.DateValue))
                {
                    return(null);
                }

                dateObject.DateValue = new DateTimeOffset(dateObject.DateValue.Year, 1, 1, 0, 0, 0, dateObject.HasTimeZone == null || !(bool)dateObject.HasTimeZone ? new TimeSpan(0, 0, 0) : dateObject.DateValue.Offset);
                return(dateObject);
            }
            else
            {
                return(null);
            }
        }
        public virtual bool Match(
            object obj)
        {
            X509Crl c = obj as X509Crl;

            if (c == null)
            {
                return(false);
            }

            if (dateAndTime != null)
            {
                DateTime       dt = dateAndTime.Value;
                DateTime       tu = c.ThisUpdate;
                DateTimeObject nu = c.NextUpdate;

                if (dt.CompareTo(tu) < 0 || nu == null || dt.CompareTo(nu.Value) >= 0)
                {
                    return(false);
                }
            }

            if (issuers != null)
            {
                X509Name i = c.IssuerDN;

                bool found = false;

                foreach (X509Name issuer in issuers)
                {
                    if (issuer.Equivalent(i, true))
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    return(false);
                }
            }

            if (maxCrlNumber != null || minCrlNumber != null)
            {
                Asn1OctetString extVal = c.GetExtensionValue(X509Extensions.CrlNumber);
                if (extVal == null)
                {
                    return(false);
                }

                BigInteger cn = CrlNumber.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(extVal)).PositiveValue;

                if (maxCrlNumber != null && cn.CompareTo(maxCrlNumber) > 0)
                {
                    return(false);
                }

                if (minCrlNumber != null && cn.CompareTo(minCrlNumber) < 0)
                {
                    return(false);
                }
            }

            DerInteger dci = null;

            try
            {
                Asn1OctetString bytes = c.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
                if (bytes != null)
                {
                    dci = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(bytes));
                }
            }
            catch (Exception)
            {
                return(false);
            }

            if (dci == null)
            {
                if (DeltaCrlIndicatorEnabled)
                {
                    return(false);
                }
            }
            else
            {
                if (CompleteCrlEnabled)
                {
                    return(false);
                }

                if (maxBaseCrlNumber != null && dci.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
                {
                    return(false);
                }
            }

            if (issuingDistributionPointEnabled)
            {
                Asn1OctetString idp = c.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
                if (issuingDistributionPoint == null)
                {
                    if (idp != null)
                    {
                        return(false);
                    }
                }
                else
                {
                    if (!Arrays.AreEqual(idp.GetOctets(), issuingDistributionPoint))
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
        public virtual bool Match(object obj)
        {
            X509Crl x509Crl = obj as X509Crl;

            if (x509Crl == null)
            {
                return(false);
            }
            if (dateAndTime != null)
            {
                global::System.DateTime value      = dateAndTime.Value;
                global::System.DateTime thisUpdate = x509Crl.ThisUpdate;
                DateTimeObject          nextUpdate = x509Crl.NextUpdate;
                if (value.CompareTo((object)thisUpdate) < 0 || nextUpdate == null || value.CompareTo((object)nextUpdate.Value) >= 0)
                {
                    return(false);
                }
            }
            if (issuers != null)
            {
                X509Name issuerDN = x509Crl.IssuerDN;
                bool     flag     = false;
                {
                    global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)issuers).GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            X509Name x509Name = (X509Name)enumerator.get_Current();
                            if (x509Name.Equivalent(issuerDN, inOrder: true))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    finally
                    {
                        global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                if (!flag)
                {
                    return(false);
                }
            }
            if (maxCrlNumber != null || minCrlNumber != null)
            {
                Asn1OctetString extensionValue = x509Crl.GetExtensionValue(X509Extensions.CrlNumber);
                if (extensionValue == null)
                {
                    return(false);
                }
                BigInteger positiveValue = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)).PositiveValue;
                if (maxCrlNumber != null && positiveValue.CompareTo(maxCrlNumber) > 0)
                {
                    return(false);
                }
                if (minCrlNumber != null && positiveValue.CompareTo(minCrlNumber) < 0)
                {
                    return(false);
                }
            }
            DerInteger derInteger = null;

            try
            {
                Asn1OctetString extensionValue2 = x509Crl.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
                if (extensionValue2 != null)
                {
                    derInteger = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
                }
            }
            catch (global::System.Exception)
            {
                return(false);
            }
            if (derInteger == null)
            {
                if (DeltaCrlIndicatorEnabled)
                {
                    return(false);
                }
            }
            else
            {
                if (CompleteCrlEnabled)
                {
                    return(false);
                }
                if (maxBaseCrlNumber != null && derInteger.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
                {
                    return(false);
                }
            }
            if (issuingDistributionPointEnabled)
            {
                Asn1OctetString extensionValue3 = x509Crl.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
                if (issuingDistributionPoint == null)
                {
                    if (extensionValue3 != null)
                    {
                        return(false);
                    }
                }
                else if (!Arrays.AreEqual(extensionValue3.GetOctets(), issuingDistributionPoint))
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #17
0
        private int VerifyOCSPResponse()
        {
            if (ocspResponse.Status != 0)
            {
                this.lastError = Resources.INVALID_OCSP_STATUS + ocspResponse.Status;
                return((int)CertStatus.ERROR);
            }

            BasicOcspResp basicResponse = (BasicOcspResp)ocspResponse.GetResponseObject();

            if (basicResponse != null)
            {
                if (responderCert != null)
                {
                    bool verifyResult = basicResponse.Verify(responderCert.GetPublicKey());

                    if (verifyResult != true)
                    {
                        this.lastError = Resources.OCSP_VERIFY_FAILED;
                        return((int)CertStatus.ERROR);
                    }
                }

                SingleResp[] responses = basicResponse.Responses;

                byte[] reqNonce  = ocspRequest.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce).GetEncoded();
                byte[] respNonce = basicResponse.GetExtensionValue(OcspObjectIdentifiers.PkixOcspNonce).GetEncoded();

                if (reqNonce == null || Arrays.AreEqual(reqNonce, respNonce))
                {
                    // will handle single response only
                    if (responses.Length != 1)
                    {
                        this.lastError = Resources.INVALID_OCSP_RESPONSE_COUNT + responses.Length;
                        return((int)CertStatus.ERROR);
                    }

                    SingleResp resp = responses[0];

                    // Check that response creation time is in valid time slot.
                    DateTime       thisUpdate = resp.ThisUpdate;
                    DateTimeObject nextUpdate = resp.NextUpdate;
                    DateTime       now        = DateTime.UtcNow;

                    // Check whether response creation ramained in valid slot
                    bool valid = CheckTimeValidity(thisUpdate, nextUpdate, 5000, 100000);
                    if (valid == false)
                    {
                        this.lastError = Resources.INVALID_OCSP_TIMESLOT;
                        return((int)CertStatus.ERROR);
                    }

                    Object status = resp.GetCertStatus();

                    if (status == CertificateStatus.Good)
                    {
                        // Ok
                        return((int)CertStatus.GOOD);
                    }
                    else if (status is RevokedStatus)
                    {
                        this.lastError = string.Format(Resources.OCSP_ERROR,
                                                       resp.GetCertID().SerialNumber,
                                                       "revoked");
                        return((int)CertStatus.REVOKED);
                    }
                    else
                    {
                        this.lastError = string.Format(Resources.OCSP_ERROR,
                                                       resp.GetCertID().SerialNumber,
                                                       "unknown");
                        return((int)CertStatus.UNKNOWN);
                    }
                }
            }
            else
            {
                this.lastError = Resources.INVALID_OCSP_RESPONSE;
            }

            // failed
            return((int)CertStatus.ERROR);
        }
    public virtual bool Match(object obj)
    {
        X509Crl x509Crl = obj as X509Crl;

        if (x509Crl == null)
        {
            return(false);
        }
        if (dateAndTime != null)
        {
            DateTime       value      = dateAndTime.Value;
            DateTime       thisUpdate = x509Crl.ThisUpdate;
            DateTimeObject nextUpdate = x509Crl.NextUpdate;
            if (value.CompareTo((object)thisUpdate) < 0 || nextUpdate == null || value.CompareTo((object)nextUpdate.Value) >= 0)
            {
                return(false);
            }
        }
        if (issuers != null)
        {
            X509Name issuerDN = x509Crl.IssuerDN;
            bool     flag     = false;
            foreach (X509Name issuer in issuers)
            {
                if (issuer.Equivalent(issuerDN, inOrder: true))
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                return(false);
            }
        }
        if (maxCrlNumber != null || minCrlNumber != null)
        {
            Asn1OctetString extensionValue = x509Crl.GetExtensionValue(X509Extensions.CrlNumber);
            if (extensionValue == null)
            {
                return(false);
            }
            BigInteger positiveValue = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue)).PositiveValue;
            if (maxCrlNumber != null && positiveValue.CompareTo(maxCrlNumber) > 0)
            {
                return(false);
            }
            if (minCrlNumber != null && positiveValue.CompareTo(minCrlNumber) < 0)
            {
                return(false);
            }
        }
        DerInteger derInteger = null;

        try
        {
            Asn1OctetString extensionValue2 = x509Crl.GetExtensionValue(X509Extensions.DeltaCrlIndicator);
            if (extensionValue2 != null)
            {
                derInteger = DerInteger.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
            }
        }
        catch (Exception)
        {
            return(false);
        }
        if (derInteger == null)
        {
            if (DeltaCrlIndicatorEnabled)
            {
                return(false);
            }
        }
        else
        {
            if (CompleteCrlEnabled)
            {
                return(false);
            }
            if (maxBaseCrlNumber != null && derInteger.PositiveValue.CompareTo(maxBaseCrlNumber) > 0)
            {
                return(false);
            }
        }
        if (issuingDistributionPointEnabled)
        {
            Asn1OctetString extensionValue3 = x509Crl.GetExtensionValue(X509Extensions.IssuingDistributionPoint);
            if (issuingDistributionPoint == null)
            {
                if (extensionValue3 != null)
                {
                    return(false);
                }
            }
            else if (!Arrays.AreEqual(extensionValue3.GetOctets(), issuingDistributionPoint))
            {
                return(false);
            }
        }
        return(true);
    }
 public static bool Before(this DateTime date, DateTimeObject when)
 {
     return(date.CompareTo(when.Value) < 0);
 }
 public static bool After(this DateTime date, DateTimeObject when)
 {
     return(date.CompareTo(when.Value) > 0);
 }
Beispiel #21
0
        public TimeStampResponse Generate(TimeStampRequest request, BigInteger serialNumber, DateTimeObject genTime)
        {
            //IL_0076: Expected O, but got Unknown
            //IL_00cf: Expected O, but got Unknown
            TimeStampResp resp;

            try
            {
                if (genTime == null)
                {
                    throw new TspValidationException("The time source is not available.", 512);
                }
                request.Validate(acceptedAlgorithms, acceptedPolicies, acceptedExtensions);
                status = PkiStatus.Granted;
                AddStatusString("Operation Okay");
                PkiStatusInfo pkiStatusInfo = GetPkiStatusInfo();
                ContentInfo   instance;
                try
                {
                    TimeStampToken timeStampToken = tokenGenerator.Generate(request, serialNumber, genTime.Value);
                    byte[]         encoded        = timeStampToken.ToCmsSignedData().GetEncoded();
                    instance = ContentInfo.GetInstance(Asn1Object.FromByteArray(encoded));
                }
                catch (IOException val)
                {
                    IOException e = val;
                    throw new TspException("Timestamp token received cannot be converted to ContentInfo", (global::System.Exception)(object) e);
                }
                resp = new TimeStampResp(pkiStatusInfo, instance);
            }
            catch (TspValidationException ex)
            {
                status = PkiStatus.Rejection;
                SetFailInfoField(ex.FailureCode);
                AddStatusString(((global::System.Exception)ex).get_Message());
                PkiStatusInfo pkiStatusInfo2 = GetPkiStatusInfo();
                resp = new TimeStampResp(pkiStatusInfo2, null);
            }
            try
            {
                return(new TimeStampResponse(resp));
            }
            catch (IOException val2)
            {
                IOException e2 = val2;
                throw new TspException("created badly formatted response!", (global::System.Exception)(object) e2);
            }
        }