ReadObject() public method

public ReadObject ( ) : Asn1Object
return Asn1Object
コード例 #1
0
 public virtual bool Check(CertificateAndContext cert)
 {
     //TODO jbonilla - Validar
     //byte[] qcStatement = cert.GetCertificate().GetExtensionValue(X509Extensions.QCStatements);
     Asn1OctetString qcStatement = cert.GetCertificate().GetExtensionValue(X509Extensions.QCStatements);
     if (qcStatement != null)
     {
         try
         {
             //Asn1InputStream input = new Asn1InputStream(qcStatement);                    
             //DerOctetString s = (DerOctetString)input.ReadObject();
             DerOctetString s = (DerOctetString)qcStatement;
             byte[] content = s.GetOctets();
             Asn1InputStream input = new Asn1InputStream(content);
             DerSequence seq = (DerSequence)input.ReadObject();
             for (int i = 0; i < seq.Count; i++)
             {
                 QCStatement statement = QCStatement.GetInstance(seq[i]);
                 if (statement.StatementId.Id.Equals(qcStatementId))
                 {
                     return true;
                 }
             }
             return false;
         }
         catch (IOException e)
         {
             throw new RuntimeException(e);
         }
     }
     return false;
 }
コード例 #2
0
ファイル: EcdsaSignature.cs プロジェクト: kueiwa/ripple-cs
        public static EcdsaSignature DecodeFromDer(byte[] bytes)
        {
            try
            {
                var decoder = new Asn1InputStream(bytes);
                var seq = (Asn1Sequence)decoder.ReadObject();
                DerInteger r, s;
                try
                {
                    r = (DerInteger)seq[0];
                    s = (DerInteger)seq[1];
                }
                catch (InvalidCastException)
                {
                    return null;
                }
                decoder.Close();

                // OpenSSL deviates from the DER spec by interpreting these values as unsigned, though they should not be
                // Thus, we always use the positive versions. See: http://r6.ca/blog/20111119T211504Z.html
                return new EcdsaSignature(r.PositiveValue, s.PositiveValue);
            }
            catch (IOException e)
            {
                throw new ApplicationException("Decoding form DER failed", e);
            }
        }
コード例 #3
0
        bool ValidateDEREncoding(Stream stream)
        {
            try
            {
                var asn1Stream  = new Org.BouncyCastle.Asn1.Asn1InputStream(stream);
                var certificate = asn1Stream.ReadObject();

                var derEncodedStream = new MemoryStream();
                var encoder          = new Org.BouncyCastle.Asn1.DerOutputStream(derEncodedStream);
                encoder.WriteObject(certificate);
                encoder.Flush();

                if (stream.Length != derEncodedStream.Length)
                {
                    return(false);
                }

                stream.Seek(0, SeekOrigin.Begin);
                derEncodedStream.Seek(0, SeekOrigin.Begin);

                for (int i = 0; i < stream.Length; i++)
                {
                    if (stream.ReadByte() != derEncodedStream.ReadByte())
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
コード例 #4
0
ファイル: PolicyIdCondition.cs プロジェクト: Gianluigi/dssnet
 public virtual bool Check(CertificateAndContext cert)
 {
     //TODO jbonilla - validar.
     //byte[] certificatePolicies = cert.GetCertificate().GetExtensionValue(X509Extensions.CertificatePolicies);
     Asn1OctetString certificatePolicies = cert.GetCertificate().GetExtensionValue(X509Extensions.CertificatePolicies);
     if (certificatePolicies != null)
     {
         try
         {
             //Asn1InputStream input = new Asn1InputStream(certificatePolicies);
             //DerOctetString s = (DerOctetString)input.ReadObject();
             DerOctetString s = (DerOctetString)certificatePolicies;
             byte[] content = s.GetOctets();
             Asn1InputStream input = new Asn1InputStream(content);
             DerSequence seq = (DerSequence)input.ReadObject();
             for (int i = 0; i < seq.Count; i++)
             {
                 PolicyInformation policyInfo = PolicyInformation.GetInstance(seq[i]);
                 if (policyInfo.PolicyIdentifier.Id.Equals(policyOid))
                 {
                     return true;
                 }
             }
         }
         catch (IOException e)
         {
             throw new RuntimeException(e);
         }
     }
     return false;
 }
コード例 #5
0
        /**
        * Parse the ServerCertificate message.
        *
        * @param is The stream where to parse from.
        * @return A Certificate object with the certs, the server has sended.
        * @throws IOException If something goes wrong during parsing.
        */
        internal static Certificate Parse(
			Stream inStr)
        {
            X509CertificateStructure[] certs;
            int left = TlsUtilities.ReadUint24(inStr);
            ArrayList tmp = new ArrayList();
            while (left > 0)
            {
                int size = TlsUtilities.ReadUint24(inStr);
                left -= 3 + size;
                byte[] buf = new byte[size];
                TlsUtilities.ReadFully(buf, inStr);
                MemoryStream bis = new MemoryStream(buf, false);
                Asn1InputStream ais = new Asn1InputStream(bis);
                Asn1Object o = ais.ReadObject();
                tmp.Add(X509CertificateStructure.GetInstance(o));
            //				if (bis.available() > 0)
                if (bis.Position < bis.Length)
                {
                    throw new ArgumentException("Sorry, there is garbage data left after the certificate");
                }
            }
            //			certs = new X509CertificateStructure[tmp.size()];
            //			for (int i = 0; i < tmp.size(); i++)
            //			{
            //				certs[i] = (X509CertificateStructure)tmp.elementAt(i);
            //			}
            certs = (X509CertificateStructure[]) tmp.ToArray(typeof(X509CertificateStructure));
            return new Certificate(certs);
        }
コード例 #6
0
        public static string GetAuthorityKeyFromCertificate(X509Certificate2 certificate)
        {
            try
            {
                foreach (var extension in certificate.Extensions.Cast<X509Extension>()
                .Where(extension => extension.Oid.Value.Equals(AuthorityKeyOid)))
                {
                    using (var asnStream = new Asn1InputStream(extension.RawData))
                    {
                        var asnObject = asnStream.ReadObject();
                        var taggedObject = new DerTaggedObject(0, asnObject);

                        var authorityKey = AuthorityKeyIdentifier.GetInstance(taggedObject, true);
                        var octetString = new DerOctetString(authorityKey.GetKeyIdentifier());
                        return NormalizeOctetString(octetString.ToString());
                    }
                }

                return "";
            }
            catch (Exception e)
            {
                Log.WarnFormat("An issue occurred while attempting to extract the authority key from a certificate: {0}", e.Message);
                return "";
            }
        }
コード例 #7
0
ファイル: TimeStampResponse.cs プロジェクト: Gianluigi/dssnet
		private static TimeStampResp readTimeStampResp(
			Asn1InputStream input)
		{
			try
			{
				return TimeStampResp.GetInstance(input.ReadObject());                
			}
			catch (ArgumentException e)
			{
				throw new TspException("malformed timestamp response: " + e, e);
			}
			catch (InvalidCastException e)
			{
				throw new TspException("malformed timestamp response: " + e, e);
			}
            catch (EndOfStreamException e)
            {
                //jbonilla - TSA del BCE por alguna razón devuelve "null\n"
                string resp = "";
                if (input.CanSeek && input.CanRead && input.Length > 0)
                {
                    input.Seek(0, SeekOrigin.Begin);
                    resp = Strings.FromByteArray(
                        Org.BouncyCastle.Utilities.IO.Streams.ReadAll(input));
                }                
                throw new TspException("malformed timestamp response: " 
                    + resp + " " + e.Message, e);
            }
		}
コード例 #8
0
        static CrlDistPoint ExtractCrlDistributionPointsExtension(X509Certificate2 certificate)
        {
            var bouncyCastleCertificate = new X509CertificateParser().ReadCertificate(certificate.RawData);
            var extension = bouncyCastleCertificate.GetExtensionValue(new DerObjectIdentifier(ObjectIdentifiers.CrlDistributionPointsExtension));
            var stream = new Asn1InputStream(extension.GetOctetStream());

            return CrlDistPoint.GetInstance(stream.ReadObject());
        }
コード例 #9
0
ファイル: X509CertPairParser.cs プロジェクト: pusp/o2platform
		private X509CertificatePair ReadDerCrossCertificatePair(
			Stream inStream)
		{
			Asn1InputStream dIn = new Asn1InputStream(inStream);//, ProviderUtil.getReadLimit(in));
			Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject();
			CertificatePair pair = CertificatePair.GetInstance(seq);
			return new X509CertificatePair(pair);
		}
コード例 #10
0
ファイル: SODFile.cs プロジェクト: hernandazevedo/JMRTD
        /// <summary>
        /// Constructs a new EF_SOD file.
        /// </summary>
        /// <param name="data">bytes of the EF_DG1 file</param>
        public SODFile(byte[] data)
        {
            MemoryStream dataStream = new MemoryStream(data);
            BERTLVInputStream tlvStream = new BERTLVInputStream(dataStream);
            int tag = tlvStream.readTag();
            if (tag != IDGFile.EF_SOD_TAG) throw new ArgumentException("Expected EF_SOD_TAG");
            int length = tlvStream.readLength();

            Asn1InputStream sodAsn1 = new Asn1InputStream(dataStream);
            DerSequence seq = (DerSequence)sodAsn1.ReadObject();
            DerObjectIdentifier objectIdentifier = (DerObjectIdentifier)seq[0];

            //DerTaggedObject o = (DerTaggedObject)seq[1];
            DerSequence s2 = (DerSequence)((DerTaggedObject)seq[1]).GetObject();
            IEnumerator e = s2.GetEnumerator();
            e.MoveNext();
            DerInteger version = (DerInteger)e.Current;
            e.MoveNext();
            Asn1Set digestAlgorithms = (Asn1Set)e.Current;
            e.MoveNext();
            ContentInfo contentInfo = ContentInfo.GetInstance(e.Current);

            Asn1Set signerInfos = null;
            bool certsBer = false;
            bool crlsBer = false;
            Asn1Set certificates = null;
            Asn1Set crls = null;

            while (e.MoveNext())
            {
                Object o = e.Current;
                if (o is Asn1TaggedObject)
                {
                    Asn1TaggedObject tagged = (Asn1TaggedObject)o;
                    switch (tagged.TagNo)
                    {
                        case 0:
                            certsBer = tagged is BerTaggedObject;
                            certificates = Asn1Set.GetInstance(tagged, false);
                            break;
                        case 1:
                            crlsBer = tagged is BerTaggedObject;
                            crls = Asn1Set.GetInstance(tagged, false);
                            break;
                        default:
                            throw new ArgumentException("unknown tag value " + tagged.TagNo);
                    }
                }
                else
                {
                    signerInfos = (Asn1Set)o;
                }
            }
            _signedData = new SignedData(digestAlgorithms, contentInfo, certificates, crls, signerInfos);
            byte[] content = ((DerOctetString)contentInfo.Content).GetOctets();
            Asn1InputStream inStream = new Asn1InputStream(content);
            _lds = new LdsSecurityObject((Asn1Sequence)inStream.ReadObject());
        }
コード例 #11
0
		public Boolean verifySignature(Byte[] data, Byte[] sig)
		{
			ECDsaSigner signer = new ECDsaSigner();
			signer.Init(false, new ECPublicKeyParameters(ecParams.Curve.DecodePoint(pubKey), ecParams));
			using (Asn1InputStream asn1stream = new Asn1InputStream(sig))
			{
				Asn1Sequence seq = (Asn1Sequence)asn1stream.ReadObject();
				return signer.VerifySignature(data, ((DerInteger)seq[0]).PositiveValue, ((DerInteger)seq[1]).PositiveValue);
			}
		}
コード例 #12
0
ファイル: Dump.cs プロジェクト: hjgode/iTextSharpCF
        public static void Main(string[] args)
        {
            FileStream fIn = new FileStream(args[0], FileMode.Open);
            Asn1InputStream bIn = new Asn1InputStream(fIn);

            Asn1Object obj;
            while ((obj = bIn.ReadObject()) != null)
            {
                Console.WriteLine(Asn1Dump.DumpAsString(obj));
            }
        }
コード例 #13
0
ファイル: OCSPResp.cs プロジェクト: MBrekhof/pleiobox-clients
		private OcspResp(
			Asn1InputStream aIn)
		{
			try
			{
				this.resp = OcspResponse.GetInstance(aIn.ReadObject());
			}
			catch (Exception e)
			{
				throw new IOException("malformed response: " + e.Message, e);
			}
		}
コード例 #14
0
 public static String GetCertificatePolicyOid(X509Certificate2 certificate)
 {
     var extensions = GetX509Extensions(certificate);
     var e = extensions.GetExtension(X509Extensions.CertificatePolicies);
     var extIn = new Asn1InputStream(e.Value.GetOctetStream());
     var piSeq = (DerSequence)extIn.ReadObject();
     if (piSeq.Count != 1)
     {
         throw new NonOcesCertificateException("Could not find Certificate PolicyOID");
     }
     var pi = PolicyInformation.GetInstance(piSeq[0]);
     return pi.PolicyIdentifier.Id;
 }
コード例 #15
0
ファイル: Dump.cs プロジェクト: roryshko/BouncyCastle.Crypto
        public static void Main(string[] args)
        {
            FileStream fIn = File.OpenRead(args[0]);
            Asn1InputStream bIn = new Asn1InputStream(fIn);

			Asn1Object obj;
			while ((obj = bIn.ReadObject()) != null)
            {
                System.Diagnostics.Debug.WriteLine(Asn1Dump.DumpAsString(obj));
            }

			bIn.Close();
        }
コード例 #16
0
        private Asn1EncodableVector loadVector(byte[] bytes)
        {
            Asn1EncodableVector v   = new Asn1EncodableVector();
            Asn1InputStream     aIn = new Asn1InputStream(bytes);

            Asn1Object obj;

            while ((obj = aIn.ReadObject()) != null)
            {
                v.Add(obj);
            }

            return(v);
        }
コード例 #17
0
ファイル: ECDSASignature.cs プロジェクト: nikropht/NBitcoin
 public static ECDSASignature FromDER(byte[] sig)
 {
     try
     {
         Asn1InputStream decoder = new Asn1InputStream(sig);
         var seq = decoder.ReadObject() as DerSequence;
         if(seq == null || seq.Count != 2)
             throw new FormatException(InvalidDERSignature);
         return new ECDSASignature(((DerInteger)seq[0]).Value, ((DerInteger)seq[1]).Value);
     }
     catch(IOException ex)
     {
         throw new FormatException(InvalidDERSignature, ex);
     }
 }
コード例 #18
0
        public static void Main(string[] args)
        {
            #if !NETFX_CORE
            FileStream fIn = File.OpenRead(args[0]);
            Asn1InputStream bIn = new Asn1InputStream(fIn);

            Asn1Object obj;
            while ((obj = bIn.ReadObject()) != null)
            {
                Console.WriteLine(Asn1Dump.DumpAsString(obj));
            }

            bIn.Dispose();
            #endif
        }
コード例 #19
0
ファイル: CoinapultECC.cs プロジェクト: demenvil/public
		public static string generateSign(byte[] data, ICipherParameters privkey) {
			var dsa = SignerUtilities.GetSigner (ECDSA);
			dsa.Init (true, privkey);
			dsa.BlockUpdate (data, 0, data.Length);
			var sign = dsa.GenerateSignature ();
			BigInteger r, s;

			using (var decoder = new Asn1InputStream (sign)) {
				var seq = (Asn1Sequence)decoder.ReadObject ();
				r = ((DerInteger)seq [0]).Value;
				s = ((DerInteger)seq [1]).Value;
			}
			var signature = packInto32 (r) + packInto32 (s);
			return signature;
		}
コード例 #20
0
		private TimeStampRequest(
			Asn1InputStream str)
		{
			try
			{
				this.req = TimeStampReq.GetInstance(str.ReadObject());
			}
			catch (InvalidCastException e)
			{
				throw new IOException("malformed request: " + e);
			}
			catch (ArgumentException e)
			{
				throw new IOException("malformed request: " + e);
			}
		}
コード例 #21
0
ファイル: OCSPReq.cs プロジェクト: hjgode/iTextSharpCF
        private OcspReq(
			Asn1InputStream aIn)
        {
            try
            {
                this.req = OcspRequest.GetInstance(aIn.ReadObject());
            }
            catch (ArgumentException e)
            {
                throw new IOException("malformed request: " + e.Message);
            }
            catch (InvalidCastException e)
            {
                throw new IOException("malformed request: " + e.Message);
            }
        }
コード例 #22
0
		private static TimeStampResp readTimeStampResp(
			Asn1InputStream input)
		{
			try
			{
				return TimeStampResp.GetInstance(input.ReadObject());
			}
			catch (ArgumentException e)
			{
				throw new TspException("malformed timestamp response: " + e, e);
			}
			catch (InvalidCastException e)
			{
				throw new TspException("malformed timestamp response: " + e, e);
			}
		}
コード例 #23
0
ファイル: Asn1Object.cs プロジェクト: KimikoMuffin/bc-csharp
		/// <summary>Create a base ASN.1 object from a byte array.</summary>
		/// <param name="data">The byte array to parse.</param>
		/// <returns>The base ASN.1 object represented by the byte array.</returns>
		/// <exception cref="IOException">If there is a problem parsing the data.</exception>
		public static Asn1Object FromByteArray(
			byte[] data)
		{
            try
			{
                MemoryStream input = new MemoryStream(data, false);
                Asn1InputStream asn1 = new Asn1InputStream(input, data.Length);
                Asn1Object result = asn1.ReadObject();
                if (input.Position != input.Length)
                    throw new IOException("extra data found after object");
                return result;
			}
			catch (InvalidCastException)
			{
				throw new IOException("cannot recognise object in byte array");
			}
		}
コード例 #24
0
        /**
         * Create a base ASN.1 object from a byte stream.
         *
         * @param data the byte stream to parse.
         * @return the base ASN.1 object represented by the byte stream.
         * @exception IOException if there is a problem parsing the data, or parsing the stream did not exhaust the available data.
         */
        public static ASN1Primitive FromByteArray(byte[] data)
        {
            Asn1InputStream aIn = new Asn1InputStream(data);

            try
            {
                ASN1Primitive o = (ASN1Primitive)aIn.ReadObject();



                return(o);
            }
            catch (ClassCastException)
            {
                throw new IOException("cannot recognise object in stream");
            }
        }
コード例 #25
0
ファイル: Asn1InputStream.cs プロジェクト: todoasap/bc-csharp
        internal virtual Asn1EncodableVector ReadVector(DefiniteLengthInputStream dIn)
        {
            if (dIn.Remaining < 1)
            {
                return(new Asn1EncodableVector(0));
            }

            Asn1InputStream     subStream = new Asn1InputStream(dIn);
            Asn1EncodableVector v         = new Asn1EncodableVector();
            Asn1Object          o;

            while ((o = subStream.ReadObject()) != null)
            {
                v.Add(o);
            }

            return(v);
        }
コード例 #26
0
		private X509Crl ReadDerCrl(
			Asn1InputStream dIn)
		{
			Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject();

			if (seq.Count > 1 && seq[0] is DerObjectIdentifier)
			{
				if (seq[0].Equals(PkcsObjectIdentifiers.SignedData))
				{
					sCrlData = SignedData.GetInstance(
						Asn1Sequence.GetInstance((Asn1TaggedObject) seq[1], true)).Crls;

					return GetCrl();
				}
			}

			return CreateX509Crl(CertificateList.GetInstance(seq));
		}
コード例 #27
0
 /// <summary>Create a base ASN.1 object from a byte array.</summary>
 /// <param name="data">The byte array to parse.</param>
 /// <returns>The base ASN.1 object represented by the byte array.</returns>
 /// <exception cref="IOException">If there is a problem parsing the data.</exception>
 public static Asn1Object FromByteArray(
     byte[] data)
 {
     try
     {
         MemoryStream    input  = new MemoryStream(data, false);
         Asn1InputStream asn1   = new Asn1InputStream(input, data.Length);
         Asn1Object      result = asn1.ReadObject();
         if (input.Position != input.Length)
         {
             throw new IOException("extra data found after object");
         }
         return(result);
     }
     catch (InvalidCastException)
     {
         throw new IOException("cannot recognise object in byte array");
     }
 }
コード例 #28
0
		private IX509AttributeCertificate ReadDerCertificate(
			Asn1InputStream dIn)
		{
			Asn1Sequence seq = (Asn1Sequence)dIn.ReadObject();

			if (seq.Count > 1 && seq[0] is DerObjectIdentifier)
			{
				if (seq[0].Equals(PkcsObjectIdentifiers.SignedData))
				{
					sData = SignedData.GetInstance(
						Asn1Sequence.GetInstance((Asn1TaggedObject) seq[1], true)).Certificates;

					return GetCertificate();
				}
			}

//			return new X509V2AttributeCertificate(seq.getEncoded());
			return new X509V2AttributeCertificate(AttributeCertificate.GetInstance(seq));
		}
コード例 #29
0
ファイル: CMSUtils.cs プロジェクト: MBrekhof/pleiobox-clients
		private static ContentInfo ReadContentInfo(
			Asn1InputStream aIn)
		{
			try
			{
				return ContentInfo.GetInstance(aIn.ReadObject());
			}
			catch (IOException e)
			{
				throw new CmsException("IOException reading content.", e);
			}
			catch (InvalidCastException e)
			{
				throw new CmsException("Malformed content.", e);
			}
			catch (ArgumentException e)
			{
				throw new CmsException("Malformed content.", e);
			}
		}
コード例 #30
0
ファイル: DG15File.cs プロジェクト: hernandazevedo/JMRTD
        /// <summary>
        /// Constructs a new EF_DG15 file.
        /// </summary>
        /// <param name="data">bytes of the EF_DG15 file</param>
        public DG15File(byte[] data)
        {
            dgNumber = 15;
            raw = new byte[data.Length];
            Array.Copy(data, RawBytes, data.Length);
            MemoryStream dg15MemStream = new MemoryStream(data);
            BERTLVInputStream dg15Stream = new BERTLVInputStream(dg15MemStream);
            int tag = dg15Stream.readTag();
            if (tag != IDGFile.EF_DG15_TAG) throw new ArgumentException("Expected EF_DG15_TAG");
            int dg15Length = dg15Stream.readLength();
            byte[] value = dg15Stream.readValue();

            Asn1InputStream aIn = new Asn1InputStream(value);
            /*Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();
            string alg =  ((DerSequence) seq[0])[0].ToString();
            byte[] publicKey = ((DerBitString)seq[1]).GetBytes();*/

            SubjectPublicKeyInfo info = SubjectPublicKeyInfo.GetInstance(aIn.ReadObject());
            PublicKey = RsaPublicKeyStructure.GetInstance(info.GetPublicKey());
        }
コード例 #31
0
ファイル: Asn1Object.cs プロジェクト: smdx24/CPI-Source-Code
 public static Asn1Object FromByteArray(byte[] data)
 {
     //IL_0002: Unknown result type (might be due to invalid IL or missing references)
     //IL_0008: Expected O, but got Unknown
     //IL_002c: Unknown result type (might be due to invalid IL or missing references)
     //IL_003c: Unknown result type (might be due to invalid IL or missing references)
     try
     {
         MemoryStream    val             = new MemoryStream(data, false);
         Asn1InputStream asn1InputStream = new Asn1InputStream((Stream)(object)val, data.Length);
         Asn1Object      result          = asn1InputStream.ReadObject();
         if (((Stream)val).get_Position() != ((Stream)val).get_Length())
         {
             throw new IOException("extra data found after object");
         }
         return(result);
     }
     catch (InvalidCastException)
     {
         throw new IOException("cannot recognise object in byte array");
     }
 }
コード例 #32
0
		internal static void ProcessCertBC(
			PkixCertPath				certPath,
			int							index,
			PkixNameConstraintValidator	nameConstraintValidator)
			//throws CertPathValidatorException
		{
			IList certs = certPath.Certificates;
			X509Certificate cert = (X509Certificate)certs[index];
			int n = certs.Count;
			// i as defined in the algorithm description
			int i = n - index;
			//
			// (b), (c) permitted and excluded subtree checking.
			//
			if (!(PkixCertPathValidatorUtilities.IsSelfIssued(cert) && (i < n)))
			{
				X509Name principal = cert.SubjectDN;
				Asn1InputStream aIn = new Asn1InputStream(principal.GetEncoded());
				Asn1Sequence dns;

				try
				{
					dns = DerSequence.GetInstance(aIn.ReadObject());
				}
				catch (Exception e)
				{
					throw new PkixCertPathValidatorException(
						"Exception extracting subject name when checking subtrees.", e, certPath, index);
				}

				try
				{
					nameConstraintValidator.CheckPermittedDN(dns);
					nameConstraintValidator.CheckExcludedDN(dns);
				}
				catch (PkixNameConstraintValidatorException e)
				{
					throw new PkixCertPathValidatorException(
						"Subtree check for certificate subject failed.", e, certPath, index);
				}

				GeneralNames altName = null;
				try
				{
					altName = GeneralNames.GetInstance(
						PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.SubjectAlternativeName));
				}
				catch (Exception e)
				{
					throw new PkixCertPathValidatorException(
						"Subject alternative name extension could not be decoded.", e, certPath, index);
				}

				IList emails = X509Name.GetInstance(dns).GetValueList(X509Name.EmailAddress);
				foreach (string email in emails)
				{
					GeneralName emailAsGeneralName = new GeneralName(GeneralName.Rfc822Name, email);
					try
					{
						nameConstraintValidator.checkPermitted(emailAsGeneralName);
						nameConstraintValidator.checkExcluded(emailAsGeneralName);
					}
					catch (PkixNameConstraintValidatorException ex)
					{
						throw new PkixCertPathValidatorException(
							"Subtree check for certificate subject alternative email failed.", ex, certPath, index);
					}
				}
				if (altName != null)
				{
					GeneralName[] genNames = null;
					try
					{
						genNames = altName.GetNames();
					}
					catch (Exception e)
					{
						throw new PkixCertPathValidatorException(
							"Subject alternative name contents could not be decoded.", e, certPath, index);
					}
					foreach (GeneralName genName in genNames)
					{
						try
						{
							nameConstraintValidator.checkPermitted(genName);
							nameConstraintValidator.checkExcluded(genName);
						}
						catch (PkixNameConstraintValidatorException e)
						{
							throw new PkixCertPathValidatorException(
								"Subtree check for certificate subject alternative name failed.", e, certPath, index);
						}
					}
				}
			}
		}
コード例 #33
0
 private PdfName GetSignatureHashKey(String signatureName) {
     PdfDictionary dic = acroFields.GetSignatureDictionary(signatureName);
     PdfString contents = dic.GetAsString(PdfName.CONTENTS);
     byte[] bc = contents.GetOriginalBytes();
     byte[] bt = null;
     if (PdfName.ETSI_RFC3161.Equals(dic.GetAsName(PdfName.SUBFILTER))) {
         Asn1InputStream din = new Asn1InputStream(new MemoryStream(bc));
         Asn1Object pkcs = din.ReadObject();
         bc = pkcs.GetEncoded();
     }
     bt = HashBytesSha1(bc);
     return new PdfName(Utilities.ConvertToHex(bt));
 }
コード例 #34
0
ファイル: PdfPKCS7.cs プロジェクト: nicecai/iTextSharp-4.1.6
 /**
 * Get the "subject" from the TBSCertificate bytes that are passed in
 * @param enc A TBSCertificate in a byte array
 * @return a DERObject
 */
 private static Asn1Object GetSubject(byte[] enc) {
     Asn1InputStream inp = new Asn1InputStream(new MemoryStream(enc));
     Asn1Sequence seq = (Asn1Sequence)inp.ReadObject();
     return (Asn1Object)seq[seq[0] is DerTaggedObject ? 5 : 4];
 }
コード例 #35
0
ファイル: PdfPKCS7.cs プロジェクト: nicecai/iTextSharp-4.1.6
 private static Asn1Object GetExtensionValue(X509Certificate cert, String oid) {
     byte[] bytes = cert.GetExtensionValue(new DerObjectIdentifier(oid)).GetDerEncoded();
     if (bytes == null) {
         return null;
     }
     Asn1InputStream aIn = new Asn1InputStream(new MemoryStream(bytes));
     Asn1OctetString octs = (Asn1OctetString) aIn.ReadObject();
     aIn = new Asn1InputStream(new MemoryStream(octs.GetOctets()));
     return aIn.ReadObject();
 }
コード例 #36
0
ファイル: PdfPKCS7.cs プロジェクト: nicecai/iTextSharp-4.1.6
 /**
 * Verifies a signature using the sub-filter adbe.pkcs7.detached or
 * adbe.pkcs7.sha1.
 * @param contentsKey the /Contents key
 * @param provider the provider or <code>null</code> for the default provider
 * @throws SecurityException on error
 * @throws CRLException on error
 * @throws InvalidKeyException on error
 * @throws CertificateException on error
 * @throws NoSuchProviderException on error
 * @throws NoSuchAlgorithmException on error
 */    
 public PdfPKCS7(byte[] contentsKey) {
     Asn1InputStream din = new Asn1InputStream(new MemoryStream(contentsKey));
     
     //
     // Basic checks to make sure it's a PKCS#7 SignedData Object
     //
     Asn1Object pkcs;
     
     try {
         pkcs = din.ReadObject();
     }
     catch  {
         throw new ArgumentException("can't decode PKCS7SignedData object");
     }
     if (!(pkcs is Asn1Sequence)) {
         throw new ArgumentException("Not a valid PKCS#7 object - not a sequence");
     }
     Asn1Sequence signedData = (Asn1Sequence)pkcs;
     DerObjectIdentifier objId = (DerObjectIdentifier)signedData[0];
     if (!objId.Id.Equals(ID_PKCS7_SIGNED_DATA))
         throw new ArgumentException("Not a valid PKCS#7 object - not signed data");
     Asn1Sequence content = (Asn1Sequence)((DerTaggedObject)signedData[1]).GetObject();
     // the positions that we care are:
     //     0 - version
     //     1 - digestAlgorithms
     //     2 - possible ID_PKCS7_DATA
     //     (the certificates and crls are taken out by other means)
     //     last - signerInfos
     
     // the version
     version = ((DerInteger)content[0]).Value.IntValue;
     
     // the digestAlgorithms
     digestalgos = new Hashtable();
     IEnumerator e = ((Asn1Set)content[1]).GetEnumerator();
     while (e.MoveNext())
     {
         Asn1Sequence s = (Asn1Sequence)e.Current;
         DerObjectIdentifier o = (DerObjectIdentifier)s[0];
         digestalgos[o.Id] = null;
     }
     
     // the certificates and crls
     X509CertificateParser cf = new X509CertificateParser();
     certs = new ArrayList();
     foreach (X509Certificate cc in cf.ReadCertificates(contentsKey)) {
         certs.Add(cc);
     }
     crls = new ArrayList();
     
     // the possible ID_PKCS7_DATA
     Asn1Sequence rsaData = (Asn1Sequence)content[2];
     if (rsaData.Count > 1) {
         DerOctetString rsaDataContent = (DerOctetString)((DerTaggedObject)rsaData[1]).GetObject();
         RSAdata = rsaDataContent.GetOctets();
     }
     
     // the signerInfos
     int next = 3;
     while (content[next] is DerTaggedObject)
         ++next;
     Asn1Set signerInfos = (Asn1Set)content[next];
     if (signerInfos.Count != 1)
         throw new ArgumentException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time");
     Asn1Sequence signerInfo = (Asn1Sequence)signerInfos[0];
     // the positions that we care are
     //     0 - version
     //     1 - the signing certificate serial number
     //     2 - the digest algorithm
     //     3 or 4 - digestEncryptionAlgorithm
     //     4 or 5 - encryptedDigest
     signerversion = ((DerInteger)signerInfo[0]).Value.IntValue;
     // Get the signing certificate
     Asn1Sequence issuerAndSerialNumber = (Asn1Sequence)signerInfo[1];
     BigInteger serialNumber = ((DerInteger)issuerAndSerialNumber[1]).Value;
     foreach (X509Certificate cert in certs) {                                                            
         if (serialNumber.Equals(cert.SerialNumber)) {
             signCert = cert;                                                                             
             break;                                                                                            
         }                                                                                                
     }
     if (signCert == null) {
         throw new ArgumentException("Can't find signing certificate with serial " + serialNumber.ToString(16));
     }
     CalcSignCertificateChain();
     digestAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[2])[0]).Id;
     next = 3;
     if (signerInfo[next] is Asn1TaggedObject) {
         Asn1TaggedObject tagsig = (Asn1TaggedObject)signerInfo[next];
         Asn1Set sseq = Asn1Set.GetInstance(tagsig, false);
         sigAttr = sseq.GetEncoded(Asn1Encodable.Der);
         
         for (int k = 0; k < sseq.Count; ++k) {
             Asn1Sequence seq2 = (Asn1Sequence)sseq[k];
             if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_MESSAGE_DIGEST)) {
                 Asn1Set sset = (Asn1Set)seq2[1];
                 digestAttr = ((DerOctetString)sset[0]).GetOctets();
             }
             else if (((DerObjectIdentifier)seq2[0]).Id.Equals(ID_ADBE_REVOCATION)) {
                 Asn1Set setout = (Asn1Set)seq2[1];
                 Asn1Sequence seqout = (Asn1Sequence)setout[0];
                 for (int j = 0; j < seqout.Count; ++j) {
                     Asn1TaggedObject tg = (Asn1TaggedObject)seqout[j];
                     if (tg.TagNo != 1)
                         continue;
                     Asn1Sequence seqin = (Asn1Sequence)tg.GetObject();
                     FindOcsp(seqin);
                 }
             }
         }
         if (digestAttr == null)
             throw new ArgumentException("Authenticated attribute is missing the digest.");
         ++next;
     }
     digestEncryptionAlgorithm = ((DerObjectIdentifier)((Asn1Sequence)signerInfo[next++])[0]).Id;
     digest = ((DerOctetString)signerInfo[next++]).GetOctets();
     if (next < signerInfo.Count && (signerInfo[next] is DerTaggedObject)) {
         DerTaggedObject taggedObject = (DerTaggedObject) signerInfo[next];
         Asn1Set unat = Asn1Set.GetInstance(taggedObject, false);
         Org.BouncyCastle.Asn1.Cms.AttributeTable attble = new Org.BouncyCastle.Asn1.Cms.AttributeTable(unat);
         Org.BouncyCastle.Asn1.Cms.Attribute ts = attble[PkcsObjectIdentifiers.IdAASignatureTimeStampToken];
         if (ts != null) {
             Asn1Set attributeValues = ts.AttrValues;
             Asn1Sequence tokenSequence = Asn1Sequence.GetInstance(attributeValues[0]);
             Org.BouncyCastle.Asn1.Cms.ContentInfo contentInfo = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(tokenSequence);
             this.timeStampToken = new TimeStampToken(contentInfo);
         }
     }
     if (RSAdata != null || digestAttr != null) {
         messageDigest = GetHashClass();
     }
     sig = SignerUtilities.GetSigner(GetDigestAlgorithm());
     sig.Init(false, signCert.GetPublicKey());
 }
コード例 #37
0
ファイル: BCCertificateBuilder.cs プロジェクト: wflk/canape
        /// <summary>
        /// Create a new certificate
        /// </summary>
        /// <param name="issuer">Issuer certificate, if null then self-sign</param>
        /// <param name="subjectName">Subject name</param>
        /// <param name="serialNumber">Serial number of certificate, if null then will generate a new one</param>
        /// <param name="signature">If true create an AT_SIGNATURE key, otherwise AT_EXCHANGE</param>
        /// <param name="keySize">Size of RSA key</param>
        /// <param name="notBefore">Start date of certificate</param>
        /// <param name="notAfter">End date of certificate</param>
        /// <param name="extensions">Array of extensions, if null then no extensions</param>
        /// <param name="hashAlgorithm">Specify the signature hash algorithm</param>
        /// <returns>The created X509 certificate</returns>
        public SystemX509.X509Certificate2 CreateCert(SystemX509.X509Certificate2 issuer, SystemX509.X500DistinguishedName subjectName,
                                                      byte[] serialNumber, bool signature, int keySize, CertificateHashAlgorithm hashAlgorithm, DateTime notBefore,
                                                      DateTime notAfter, SystemX509.X509ExtensionCollection extensions)
        {
            X509V3CertificateGenerator builder    = new X509V3CertificateGenerator();
            AsymmetricAlgorithm        subjectKey = CreateRSAKey(keySize, signature);
            AsymmetricAlgorithm        signKey    = issuer == null ? subjectKey : issuer.PrivateKey;

            if (signKey == null)
            {
                throw new ArgumentException(Properties.Resources.CreateCert_NoPrivateKey);
            }

            AsymmetricCipherKeyPair bcSubjectKey = GetRsaKeyPair((RSACryptoServiceProvider)subjectKey);
            AsymmetricCipherKeyPair bcSignKey    = GetRsaKeyPair((RSACryptoServiceProvider)signKey);

            X509Name issuerNameObj = issuer == null?X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData))
                                         : X509Name.GetInstance(Asn1Object.FromByteArray(issuer.SubjectName.RawData));

            X509Name subjectNameObj = X509Name.GetInstance(Asn1Object.FromByteArray(subjectName.RawData));

            BigInteger subjectSerial = new BigInteger(1, serialNumber != null ? serialNumber : Guid.NewGuid().ToByteArray());
            BigInteger issuerSerial  = issuer == null ? subjectSerial : new BigInteger(1, issuer.GetSerialNumber());

            builder.SetIssuerDN(issuerNameObj);
            builder.SetSubjectDN(subjectNameObj);
            builder.SetSerialNumber(subjectSerial);
            builder.SetSignatureAlgorithm(HashAlgorithmToName(hashAlgorithm));
            builder.SetNotBefore(notBefore.ToUniversalTime());
            builder.SetNotAfter(notAfter.ToUniversalTime());
            builder.SetPublicKey(bcSubjectKey.Public);

            SubjectPublicKeyInfo   info         = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSignKey.Public);
            AuthorityKeyIdentifier authKeyId    = new AuthorityKeyIdentifier(info, new GeneralNames(new GeneralName(issuerNameObj)), issuerSerial);
            SubjectKeyIdentifier   subjectKeyid = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(bcSubjectKey.Public));

            builder.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, true, authKeyId);
            builder.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, true, subjectKeyid);

            if (extensions != null)
            {
                foreach (SystemX509.X509Extension ext in extensions)
                {
                    if (!ext.Oid.Value.Equals(X509Extensions.AuthorityKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(X509Extensions.SubjectKeyIdentifier.Id) &&
                        !ext.Oid.Value.Equals(szOID_AUTHORITY_KEY_IDENTIFIER2))
                    {
                        Asn1InputStream istm = new Org.BouncyCastle.Asn1.Asn1InputStream(ext.RawData);
                        Asn1Object      obj  = istm.ReadObject();
                        builder.AddExtension(ext.Oid.Value, ext.Critical, obj);
                    }
                }
            }

            X509Certificate cert = builder.Generate(bcSignKey.Private);

            SystemX509.X509Certificate2 ret = new SystemX509.X509Certificate2(cert.GetEncoded(), (string)null, SystemX509.X509KeyStorageFlags.Exportable);

            ret.PrivateKey = subjectKey;

            return(ret);
        }
コード例 #38
0
        /**
         * build an object given its tag and a byte stream to construct it
         * from.
         */
        internal Asn1Object BuildObject(
            int tag,
            int tagNo,
            byte[]      bytes)
        {
            if ((tag & Asn1Tags.Application) != 0)
            {
                return(new DerApplicationSpecific(tagNo, bytes));
            }

            switch (tag)
            {
            case Asn1Tags.Null:
                return(DerNull.Instance);

            case Asn1Tags.Sequence | Asn1Tags.Constructed:
            {
                Asn1EncodableVector v = BuildDerEncodableVector(bytes);
                return(new DerSequence(v));
            }

            case Asn1Tags.Set | Asn1Tags.Constructed:
            {
                Asn1EncodableVector v = BuildDerEncodableVector(bytes);
                return(new DerSet(v, false));
            }

            case Asn1Tags.Boolean:
                return(new DerBoolean(bytes));

            case Asn1Tags.Integer:
                return(new DerInteger(bytes));

            case Asn1Tags.Enumerated:
                return(new DerEnumerated(bytes));

            case Asn1Tags.ObjectIdentifier:
                return(new DerObjectIdentifier(bytes));

            case Asn1Tags.BitString:
            {
                int    padBits = bytes[0];
                byte[] data    = new byte[bytes.Length - 1];
                Array.Copy(bytes, 1, data, 0, bytes.Length - 1);
                return(new DerBitString(data, padBits));
            }

            case Asn1Tags.NumericString:
                return(new DerNumericString(bytes));

            case Asn1Tags.Utf8String:
                return(new DerUtf8String(bytes));

            case Asn1Tags.PrintableString:
                return(new DerPrintableString(bytes));

            case Asn1Tags.IA5String:
                return(new DerIA5String(bytes));

            case Asn1Tags.T61String:
                return(new DerT61String(bytes));

            case Asn1Tags.VisibleString:
                return(new DerVisibleString(bytes));

            case Asn1Tags.GeneralString:
                return(new DerGeneralString(bytes));

            case Asn1Tags.UniversalString:
                return(new DerUniversalString(bytes));

            case Asn1Tags.BmpString:
                return(new DerBmpString(bytes));

            case Asn1Tags.OctetString:
                return(new DerOctetString(bytes));

            case Asn1Tags.OctetString | Asn1Tags.Constructed:
                return(BuildDerConstructedOctetString(bytes));

            case Asn1Tags.UtcTime:
                return(new DerUtcTime(bytes));

            case Asn1Tags.GeneralizedTime:
                return(new DerGeneralizedTime(bytes));

            default:
            {
                //
                // with tagged object tag number is bottom 5 bits
                //
                if ((tag & (int)Asn1Tags.Tagged) != 0)
                {
                    bool isImplicit = ((tag & (int)Asn1Tags.Constructed) == 0);

                    if (bytes.Length == 0)                                    // empty tag!
                    {
                        Asn1Encodable ae = isImplicit
                                                                ?       (Asn1Encodable)DerNull.Instance
                                                                :       new DerSequence();

                        return(new DerTaggedObject(false, tagNo, ae));
                    }

                    //
                    // simple type - implicit... return an octet string
                    //
                    if (isImplicit)
                    {
                        return(new DerTaggedObject(false, tagNo, new DerOctetString(bytes)));
                    }

                    Asn1InputStream aIn  = new Asn1InputStream(bytes);
                    Asn1Encodable   dObj = aIn.ReadObject();


                    // explicitly tagged (probably!) - if it isn't we'd have to
                    // tell from the context

                    //if (aIn.available() == 0)
                    if (aIn.Position == bytes.Length)                             //FIXME?
                    {
                        return(new DerTaggedObject(tagNo, dObj));
                    }

                    //
                    // another implicit object, we'll create a sequence...
                    //
                    Asn1EncodableVector v = new Asn1EncodableVector();

                    while (dObj != null)
                    {
                        v.Add(dObj);
                        dObj = aIn.ReadObject();
                    }

                    return(new DerTaggedObject(false, tagNo, new DerSequence(v)));
                }

                return(new DerUnknownTag(tag, bytes));
            }
            }
        }