Exemple #1
0
        static DateTime GetSigningTime(Asn1Encodable encodable)
        {
            // Special attention to the conversion from Der*Time to .Net's DateTime
            // (May lost timezone information)

            // Try to parse as UTC time
            try
            {
                DerUtcTime timeUtc = (DerUtcTime)DerUtcTime.GetInstance(encodable);
                return(timeUtc.ToAdjustedDateTime());
            }
            catch (Exception e)
            {
            }

            // Try to parse as GeneralizedTime
            try
            {
                DerGeneralizedTime timeGenTime = (DerGeneralizedTime)DerGeneralizedTime.GetInstance(encodable);
                return(timeGenTime.ToDateTime());
            }
            catch (Exception e)
            {
            }

            return(DateTime.Now);
        }
Exemple #2
0
        /// <summary>
        /// 对待签名数据签名
        /// </summary>
        /// <param name="inData">在操作过程中请勿对流进行关闭</param>
        /// <param name="propertyInfo">签章属性信息</param>
        /// <returns></returns>
        public override byte[] Sign(Stream inData, string propertyInfo)
        {
            //原文杂凑值计算
            GeneralDigest digest = GetDigest();

            byte[] block = inData.ToArray();
            digest.BlockUpdate(block, 0, block.Length);
            byte[] outBytes = new byte[32];
            digest.DoFinal(outBytes, 0);

            //计算杂凑值
            DerUtcTime signTime = new DerUtcTime(DateTime.Now);
            TbsSign    tbsSign  = new TbsSign
            {
                Version            = new DerInteger(1),
                EsSeal             = _seal,
                TimeInfo           = new DerBitString(signTime),
                DataHash           = new DerBitString(outBytes),
                PropertyInfo       = new DerIA5String(propertyInfo),
                Cert               = new DerOctetString(_certificate.GetEncoded()),
                SignatureAlgorithm = GetSignAlgOId()
            };
            ISigner signer = SignerUtilities.GetSigner(GMObjectIdentifiers.sm2sign_with_sm3);

            signer.Init(true, _privateKey);
            byte[] signBytes = tbsSign.GetDerEncoded();
            signer.BlockUpdate(signBytes, 0, signBytes.Length);
            byte[]       sign         = signer.GenerateSignature();
            SesSignature sesSignature = new SesSignature(tbsSign, new DerBitString(sign));

            return(sesSignature.GetDerEncoded());
        }
 public void SetNextUpdate(
     DerUtcTime nextUpdate)
 {
     this.nextUpdate = (nextUpdate != null)
                         ?       new Time(nextUpdate)
                         :       null;
 }
Exemple #4
0
        public override void PerformTest()
        {
//			SimpleDateFormat yyyyF = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
//			SimpleDateFormat yyF = new SimpleDateFormat("yyyyMMddHHmmss'Z'");

//			yyyyF.setTimeZone(new SimpleTimeZone(0,"Z"));
//			yyF.setTimeZone(new SimpleTimeZone(0,"Z"));

            for (int i = 0; i != input.Length; i++)
            {
                DerUtcTime t = new DerUtcTime(input[i]);

                if (!t.AdjustedTimeString.Equals(output[i]))
                {
                    Fail("failed conversion test " + i);
                }

//				if (!yyyyF.format(t.getAdjustedDate()).Equals(zOutput1[i]))
                if (!t.ToAdjustedDateTime().ToString(@"yyyyMMddHHmmss\Z").Equals(zOutput1[i]))
                {
                    Fail("failed date conversion test " + i);
                }

//				if (!yyF.format(t.getDate()).Equals(zOutput2[i]))
                if (!t.ToDateTime().ToString(@"yyyyMMddHHmmss\Z").Equals(zOutput2[i]))
                {
                    Fail("failed date shortened conversion test " + i);
                }
            }
        }
		public void SetNextUpdate(
            DerUtcTime nextUpdate)
        {
            this.nextUpdate = (nextUpdate != null)
				?	new Time(nextUpdate)
				:	null;
        }
 static DateTime ToAdjustedDateTime(DerUtcTime time)
 {
     //try {
     //	return time.ToAdjustedDateTime ();
     //} catch {
     return(DateUtils.Parse(time.AdjustedTimeString, "yyyyMMddHHmmsszzz"));
     //}
 }
Exemple #7
0
 public EsPropertyInfo(DerInteger type, DerUtf8String name, Asn1Sequence certList, DerUtcTime createDate, DerUtcTime validStart, DerUtcTime validEnd)
 {
     Type       = type;
     Name       = name;
     CertList   = certList;
     CreateDate = createDate;
     ValidStart = validStart;
     ValidEnd   = validEnd;
 }
    protected override bool Asn1Equals(Asn1Object asn1Object)
    {
        DerUtcTime derUtcTime = asn1Object as DerUtcTime;

        if (derUtcTime == null)
        {
            return(false);
        }
        return(time.Equals(derUtcTime.time));
    }
Exemple #9
0
        public EsPropertyInfo(Asn1Sequence seq)
        {
            IEnumerator e = seq.GetEnumerator();

            Type       = DerInteger.GetInstance(e.Next());
            Name       = DerUtf8String.GetInstance(e.Next());
            CertList   = Asn1Sequence.GetInstance(e.Next());
            CreateDate = DerUtcTime.GetInstance(e.Next());
            ValidStart = DerUtcTime.GetInstance(e.Next());
            ValidEnd   = DerUtcTime.GetInstance(e.Next());
        }
 public CrlIdentifier(X509Name crlIssuer, DateTime crlIssuedTime, BigInteger crlNumber)
 {
     if (crlIssuer == null)
     {
         throw new ArgumentNullException("crlIssuer");
     }
     this.crlIssuer     = crlIssuer;
     this.crlIssuedTime = new DerUtcTime(crlIssuedTime);
     if (crlNumber != null)
     {
         this.crlNumber = new DerInteger(crlNumber);
     }
 }
Exemple #11
0
 public CrlIdentifier(X509Name crlIssuer, global::System.DateTime crlIssuedTime, BigInteger crlNumber)
 {
     //IL_000e: Unknown result type (might be due to invalid IL or missing references)
     if (crlIssuer == null)
     {
         throw new ArgumentNullException("crlIssuer");
     }
     this.crlIssuer     = crlIssuer;
     this.crlIssuedTime = new DerUtcTime(crlIssuedTime);
     if (crlNumber != null)
     {
         this.crlNumber = new DerInteger(crlNumber);
     }
 }
        private CrlIdentifier(
			Asn1Sequence seq)
        {
            if (seq == null)
                throw new ArgumentNullException("seq");
            if (seq.Count < 2 || seq.Count > 3)
                throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");

            this.crlIssuer = X509Name.GetInstance(seq[0]);
            this.crlIssuedTime = DerUtcTime.GetInstance(seq[1]);

            if (seq.Count > 2)
            {
                this.crlNumber = DerInteger.GetInstance(seq[2]);
            }
        }
        public CrlIdentifier(
			X509Name	crlIssuer,
			DateTime	crlIssuedTime,
			BigInteger	crlNumber)
        {
            if (crlIssuer == null)
                throw new ArgumentNullException("crlIssuer");

            this.crlIssuer = crlIssuer;
            this.crlIssuedTime = new DerUtcTime(crlIssuedTime);

            if (crlNumber != null)
            {
                this.crlNumber = new DerInteger(crlNumber);
            }
        }
 private CrlIdentifier(Asn1Sequence seq)
 {
     if (seq == null)
     {
         throw new ArgumentNullException("seq");
     }
     if (seq.Count < 2 || seq.Count > 3)
     {
         throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
     }
     this.crlIssuer     = X509Name.GetInstance(seq[0]);
     this.crlIssuedTime = DerUtcTime.GetInstance(seq[1]);
     if (seq.Count > 2)
     {
         this.crlNumber = DerInteger.GetInstance(seq[2]);
     }
 }
Exemple #15
0
 private CrlIdentifier(Asn1Sequence seq)
 {
     //IL_000e: Unknown result type (might be due to invalid IL or missing references)
     //IL_0040: Unknown result type (might be due to invalid IL or missing references)
     if (seq == null)
     {
         throw new ArgumentNullException("seq");
     }
     if (seq.Count < 2 || seq.Count > 3)
     {
         throw new ArgumentException(string.Concat((object)"Bad sequence size: ", (object)seq.Count), "seq");
     }
     crlIssuer     = X509Name.GetInstance(seq[0]);
     crlIssuedTime = DerUtcTime.GetInstance(seq[1]);
     if (seq.Count > 2)
     {
         crlNumber = DerInteger.GetInstance(seq[2]);
     }
 }
 public void SetStartDate(
     DerUtcTime startDate)
 {
     this.startDate = new Time(startDate);
 }
Exemple #17
0
        private void AddAsn1Object(string name, DataKey root, Asn1Object obj, int level, Logger logger)
        {
            Asn1Sequence     seq      = obj as Asn1Sequence;
            Asn1Set          set      = obj as Asn1Set;
            Asn1TaggedObject tag      = obj as Asn1TaggedObject;
            string           currName = name ?? obj.GetType().Name;

            System.Diagnostics.Trace.WriteLine(String.Format("{0} {1}", currName, obj.GetType()));

            if (seq != null)
            {
                if (!Config.IgnoreSequences)
                {
                    DataKey key = new Asn1SequenceKey(currName, Config.NoVerify);

                    foreach (Asn1Object o in seq)
                    {
                        AddAsn1Object(null, key, o, level + 1, logger);
                    }

                    root.AddSubNode(key);
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else if (set != null)
            {
                if (!Config.IgnoreSets)
                {
                    DataKey key = new Asn1SetKey(currName, Config.NoVerify);

                    foreach (Asn1Object o in set)
                    {
                        AddAsn1Object(null, key, o, level + 1, logger);
                    }

                    root.AddSubNode(key);
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else if (tag != null)
            {
                if (!Config.IgnoreTaggedObjects)
                {
                    DataKey key = new Asn1TaggedObjectKey(currName, tag.TagNo, Config.NoVerify);

                    root.AddSubNode(key);

                    Asn1Object     o   = tag.GetObject();
                    DerOctetString oct = o as DerOctetString;

                    AddAsn1Object("Object", key, tag.GetObject(), level + 1, logger);

                    //if (oct != null)
                    //{
                    //    Asn1InputStream input = new Asn1InputStream(oct.GetOctetStream());

                    //    try
                    //    {
                    //        Asn1Object next = input.ReadObject();
                    //        if (next == null)
                    //        {
                    //            AddAsn1Object("Object", key, o, logger);
                    //        }
                    //        else
                    //        {
                    //            Asn1OctetStringObject newRoot = new Asn1OctetStringObject("Object");

                    //            while (next != null)
                    //            {
                    //                AddAsn1Object(next.GetType().Name, newRoot, next, logger);

                    //                next = input.ReadObject();
                    //            }

                    //            key.AddSubNode(newRoot);
                    //        }
                    //    }
                    //    catch (IOException)
                    //    {
                    //        AddAsn1Object("Object", key, o, logger);
                    //    }
                    //}
                    //else
                    //{
                    //    AddAsn1Object("Object", key, tag.GetObject(), logger);
                    //}
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
            else
            {
                if (!Config.NoDecode)
                {
                    DerStringBase          str  = obj as DerStringBase;
                    DerObjectIdentifier    oid  = obj as DerObjectIdentifier;
                    DerInteger             i    = obj as DerInteger;
                    DerOctetString         oct  = obj as DerOctetString;
                    DerBitString           bits = obj as DerBitString;
                    DerBoolean             boo  = obj as DerBoolean;
                    DerNull                n    = obj as DerNull;
                    DerUtcTime             time = obj as DerUtcTime;
                    DerGeneralizedTime     gt   = obj as DerGeneralizedTime;
                    DerApplicationSpecific app  = obj as DerApplicationSpecific;

                    if (oct != null)
                    {
                        root.AddValue(new Asn1OctetStringValue(currName, oct.GetOctets()));
                    }
                    else if (bits != null)
                    {
                        root.AddSubNode(new Asn1BitStringKey(currName, bits.PadBits, bits.GetBytes()));
                    }
                    else if (str != null)
                    {
                        Type stringType = typeof(Asn1StringValue <>).MakeGenericType(str.GetType());

                        root.AddValue((DataValue)Activator.CreateInstance(stringType, currName, str.GetString()));
                    }
                    else if (oid != null)
                    {
                        root.AddValue(new Asn1ObjectIdentifierValue(currName, oid.Id));
                    }
                    else if (i != null)
                    {
                        root.AddValue(new Asn1IntegerValue(currName, i.Value.ToByteArray()));
                    }
                    else if (boo != null)
                    {
                        root.AddValue(new Asn1BooleanValue(currName, boo.IsTrue));
                    }
                    else if (n != null)
                    {
                        root.AddValue(new Asn1NullValue(currName));
                    }
                    else if (time != null)
                    {
                        root.AddValue(new Asn1DateTimeValue(currName, time.ToDateTime()));
                    }
                    else if (gt != null)
                    {
                        root.AddValue(new Asn1GeneralizedTimeValue(currName, gt.ToDateTime()));
                    }
                    else if (app != null)
                    {
                        root.AddSubNode(new Asn1ApplicationSpecificValue(currName, app.ApplicationTag, app.GetContents()));
                    }
                    else
                    {
                        logger.LogError("Cannot convert type {0} to a class", obj.GetType().Name);
                        root.AddValue(currName, obj.GetDerEncoded());
                    }
                }
                else
                {
                    root.AddValue(currName, obj.GetDerEncoded());
                }
            }
        }
Exemple #18
0
            public override byte[] ToArray()
            {
                DerUtcTime t = new DerUtcTime(_time);

                return(t.GetDerEncoded());
            }
        public override void PerformTest()
        {
            for (int i = 0; i != input.Length; i++)
            {
                string ii = input[i], oi = output[i];

                DerGeneralizedTime t = new DerGeneralizedTime(ii);
                DateTime dt = t.ToDateTime();
                string st = t.GetTime();

                if (oi.IndexOf('G') > 0)   // don't check local time the same way
                {
                    if (!st.Equals(oi))
                    {
                        Fail("failed conversion test");
                    }

                    string dts = dt.ToString(@"yyyyMMddHHmmss\Z");
                    string zi = zOutput[i];
                    if (!dts.Equals(zi))
                    {
                        Fail("failed date conversion test");
                    }
                }
                else
                {
                    string offset = CalculateGmtOffset(dt);
                    if (!st.Equals(oi + offset))
                    {
                        Fail("failed conversion test");
                    }
                }
            }

            for (int i = 0; i != input.Length; i++)
            {
                DerGeneralizedTime t = new DerGeneralizedTime(input[i]);

                if (!t.ToDateTime().ToString(@"yyyyMMddHHmmss.fff\Z").Equals(mzOutput[i]))
                {
                    Console.WriteLine("{0} != {1}", t.ToDateTime().ToString(@"yyyyMMddHHmmss.SSS\Z"), mzOutput[i]);

                    Fail("failed long date conversion test");
                }
            }

            /*
             * [BMA-87]
             */
            {
                DateTime t1 = new DerUtcTime("110616114855Z").ToDateTime();
                DateTime t2 = new DerGeneralizedTime("20110616114855Z").ToDateTime();

                if (t1 != t2)
                {
                    Fail("failed UTC equivalence test");
                }

                DateTime u1 = t1.ToUniversalTime();
                DateTime u2 = t2.ToUniversalTime();

                if (u1 != u2)
                {
                    Fail("failed UTC conversion test");
                }
            }
        }
		public void SetStartDate(
            DerUtcTime startDate)
        {
            this.startDate = new Time(startDate);
        }
 public void AddCrlEntry(DerInteger userCertificate, DerUtcTime revocationDate, int reason)
 {
     AddCrlEntry(userCertificate, new Time(revocationDate), reason);
 }
 public void SetThisUpdate(
     DerUtcTime thisUpdate)
 {
     this.thisUpdate = new Time(thisUpdate);
 }
Exemple #23
0
		public override void PerformTest()
		{
//			SimpleDateFormat yyyyF = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
//			SimpleDateFormat yyF = new SimpleDateFormat("yyyyMMddHHmmss'Z'");

//			yyyyF.setTimeZone(new SimpleTimeZone(0,"Z"));
//			yyF.setTimeZone(new SimpleTimeZone(0,"Z"));

			for (int i = 0; i != input.Length; i++)
			{
				DerUtcTime t = new DerUtcTime(input[i]);

				if (!t.AdjustedTimeString.Equals(output[i]))
				{
					Fail("failed conversion test " + i);
				}

//				if (!yyyyF.format(t.getAdjustedDate()).Equals(zOutput1[i]))
				if (!t.ToAdjustedDateTime().ToString(@"yyyyMMddHHmmss\Z").Equals(zOutput1[i]))
				{
					Fail("failed date conversion test " + i);
				}

//				if (!yyF.format(t.getDate()).Equals(zOutput2[i]))
				if (!t.ToDateTime().ToString(@"yyyyMMddHHmmss\Z").Equals(zOutput2[i]))
				{
					Fail("failed date shortened conversion test " + i);
				}
			}
		}
 public void SetEndDate(
     DerUtcTime endDate)
 {
     this.endDate = new Time(endDate);
 }
		public void SetEndDate(
            DerUtcTime endDate)
        {
            this.endDate = new Time(endDate);
        }
 public void SetThisUpdate(
     DerUtcTime thisUpdate)
 {
     this.thisUpdate = new Time(thisUpdate);
 }
Exemple #27
0
        private void ReadInformation()
        {
            if (_signerInformation.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime] != null)
            {
                _signingDate = DerUtcTime.GetInstance(_signerInformation.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime].AttrValues[0]).ToDateTime().ToLocalTime();
            }

            if (_signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAAEtsSignerAttr] != null)
            {
                var signerAttr = SignerAttribute.GetInstance(_signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAAEtsSignerAttr].AttrValues[0]);

                List <string> claimedRoles = new List <string>();

                foreach (BcCms.Attribute claimedAttr in signerAttr.ClaimedAttributes)
                {
                    foreach (var value in claimedAttr.AttrValues)
                    {
                        claimedRoles.Add(DerUtf8String.GetInstance(value).GetString());
                    }
                }

                _signerRoles = claimedRoles;
            }

            if (_signerInformation.UnsignedAttributes != null &&
                _signerInformation.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken] != null)
            {
                _timeStamp = new TimeStampToken(new CmsSignedData(_signerInformation.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrValues[0].GetEncoded()));
            }

            // Se leen las contrafirmas
            var signers = _signerInformation.GetCounterSignatures().GetSigners();

            _counterSignatures = new List <SignerInfoNode>();

            foreach (var signer in signers)
            {
                SignerInfoNode node = new SignerInfoNode((SignerInformation)signer, _sigDocument);

                _counterSignatures.Add(node);
            }

            // Se intenta identificar el certificado empleado para la firma, esto quizás se pueda mejorar
            byte[]       certHash     = null;
            IssuerSerial issuerSerial = null;

            if (_signerInformation.DigestAlgOid == DigestMethod.SHA1.Oid)
            {
                BcCms.Attribute    attr = _signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificate];
                SigningCertificate sc   = SigningCertificate.GetInstance(attr.AttrValues[0]);
                EssCertID          ecid = sc.GetCerts()[0];
                issuerSerial = ecid.IssuerSerial;
                certHash     = ecid.GetCertHash();
            }
            else
            {
                BcCms.Attribute      attr = _signerInformation.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];
                SigningCertificateV2 sc2  = SigningCertificateV2.GetInstance(attr.AttrValues[0]);
                EssCertIDv2          ecid = sc2.GetCerts()[0];
                issuerSerial = ecid.IssuerSerial;
                certHash     = ecid.GetCertHash();
            }

            DigestMethod digestMethod = DigestMethod.GetByOid(_signerInformation.DigestAlgOid);

            foreach (X509CertificateStructure cs in _sigDocument.Certificates)
            {
                if (issuerSerial == null || cs.TbsCertificate.SerialNumber.Equals(issuerSerial.Serial))
                {
                    byte[] currentCertHash = digestMethod.CalculateDigest(cs.GetEncoded());

                    if (certHash.SequenceEqual(currentCertHash))
                    {
                        _certificate = new X509Certificate(cs);
                        break;
                    }
                }
            }
        }
 public void AddCrlEntry(DerInteger userCertificate, DerUtcTime revocationDate, int reason)
 {
     AddCrlEntry(userCertificate, new Time(revocationDate), reason);
 }
        public override void PerformTest()
        {
            for (int i = 0; i != input.Length; i++)
            {
                string ii = input[i], oi = output[i];

                DerGeneralizedTime t  = new DerGeneralizedTime(ii);
                DateTime           dt = t.ToDateTime();
                string             st = t.GetTime();

                if (oi.IndexOf('G') > 0)   // don't check local time the same way
                {
                    if (!st.Equals(oi))
                    {
                        Fail("failed conversion test");
                    }

                    string dts = dt.ToString(@"yyyyMMddHHmmss\Z");
                    string zi  = zOutput[i];
                    if (!dts.Equals(zi))
                    {
                        Fail("failed date conversion test");
                    }
                }
                else
                {
                    string offset = CalculateGmtOffset(dt);
                    if (!st.Equals(oi + offset))
                    {
                        Fail("failed conversion test");
                    }
                }
            }

            for (int i = 0; i != input.Length; i++)
            {
                DerGeneralizedTime t = new DerGeneralizedTime(input[i]);

                if (!t.ToDateTime().ToString(@"yyyyMMddHHmmss.fff\Z").Equals(mzOutput[i]))
                {
                    Console.WriteLine("{0} != {1}", t.ToDateTime().ToString(@"yyyyMMddHHmmss.SSS\Z"), mzOutput[i]);

                    Fail("failed long date conversion test");
                }
            }

            /*
             * [BMA-87]
             */
            {
                DateTime t1 = new DerUtcTime("110616114855Z").ToDateTime();
                DateTime t2 = new DerGeneralizedTime("20110616114855Z").ToDateTime();

                if (t1 != t2)
                {
                    Fail("failed UTC equivalence test");
                }

                DateTime u1 = t1.ToUniversalTime();
                DateTime u2 = t2.ToUniversalTime();

                if (u1 != u2)
                {
                    Fail("failed UTC conversion test");
                }
            }
        }