Inheritance: FilterStream
コード例 #1
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;
 }
コード例 #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
        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 "";
            }
        }
コード例 #4
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);
        }
コード例 #5
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);
            }
		}
コード例 #6
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);
        }
コード例 #7
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;
 }
コード例 #8
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);
		}
コード例 #9
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());
        }
コード例 #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
 private static ECDiffieHellmanCngPublicKey GetECDiffieHellmanCngPublicKey(X509Certificate2 cert)
 {
     var keyAlgoDerBytes = cert.GetKeyAlgorithmParameters();
     var keyAlgoAsn1 = new Asn1InputStream(keyAlgoDerBytes).ReadObject();
     var keyAlgoOid = new DerObjectIdentifier(keyAlgoAsn1.ToString());
     var xmlImport = Rfc4050XmlMaker("ECDH", keyAlgoOid, cert);
     var ecDiffieHellmanCngPublicKey = ECDiffieHellmanCngPublicKey.FromXmlString(xmlImport);
     return ecDiffieHellmanCngPublicKey;
 }
コード例 #12
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);
			}
		}
コード例 #13
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));
            }
        }
コード例 #14
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);
			}
		}
コード例 #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
 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;
 }
コード例 #17
0
        public static Asn1Object FromStream(Stream inStr)
        {
            Asn1Object result;

            try
            {
                result = new Asn1InputStream(inStr).ReadObject();
            }
            catch (InvalidCastException)
            {
                throw new IOException("cannot recognise object in stream");
            }
            return(result);
        }
コード例 #18
0
        public static Asn1Object FromByteArray(byte[] data)
        {
            Asn1Object result;

            try
            {
                result = new Asn1InputStream(data).ReadObject();
            }
            catch (InvalidCastException)
            {
                throw new IOException("cannot recognise object in stream");
            }
            return(result);
        }
コード例 #19
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);
        }
コード例 #20
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;
		}
コード例 #21
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
        }
コード例 #22
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);
     }
 }
コード例 #23
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);
            }
        }
コード例 #24
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);
			}
		}
コード例 #25
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);
			}
		}
コード例 #26
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");
			}
		}
コード例 #27
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");
            }
        }
コード例 #28
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));
		}
コード例 #29
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);
        }
コード例 #30
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));
		}
コード例 #31
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");
     }
 }
コード例 #32
0
        protected static Asn1Object GetExtensionValue(X509Certificate cert,
            string oid)
        {
            if (cert == null)
            {
                return null;
            }

            byte[] bytes = cert.GetExtensionValue(new DerObjectIdentifier(oid)).GetOctets();

            if (bytes == null)
            {
                return null;
            }

            Asn1InputStream aIn = new Asn1InputStream(bytes);

            return aIn.ReadObject();
        }
コード例 #33
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());
        }
コード例 #34
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);
			}
		}
コード例 #35
0
        public static Asn1Object FromByteArray(byte[] data)
        {
            Asn1Object obj3;

            try
            {
                MemoryStream inputStream = new MemoryStream(data, false);
                Asn1Object   obj2        = new Asn1InputStream(inputStream, data.Length).ReadObject();
                if (inputStream.Position != inputStream.Length)
                {
                    throw new IOException("extra data found after object");
                }
                obj3 = obj2;
            }
            catch (InvalidCastException)
            {
                throw new IOException("cannot recognise object in byte array");
            }
            return(obj3);
        }
コード例 #36
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");
     }
 }
コード例 #37
0
        private Asn1Object BuildObject(int tag, int tagNo, int length)
        {
            bool flag = (tag & 32) != 0;
            DefiniteLengthInputStream definiteLengthInputStream = new DefiniteLengthInputStream(this.s, length);

            if ((tag & 64) != 0)
            {
                return(new DerApplicationSpecific(flag, tagNo, definiteLengthInputStream.ToArray()));
            }
            if ((tag & 128) != 0)
            {
                return(new Asn1StreamParser(definiteLengthInputStream).ReadTaggedObject(flag, tagNo));
            }
            if (!flag)
            {
                return(Asn1InputStream.CreatePrimitiveDerObject(tagNo, definiteLengthInputStream, this.tmpBuffers));
            }
            if (tagNo == 4)
            {
                return(new BerOctetString(this.BuildDerEncodableVector(definiteLengthInputStream)));
            }
            if (tagNo == 8)
            {
                return(new DerExternal(this.BuildDerEncodableVector(definiteLengthInputStream)));
            }
            switch (tagNo)
            {
            case 16:
                return(this.CreateDerSequence(definiteLengthInputStream));

            case 17:
                return(this.CreateDerSet(definiteLengthInputStream));

            default:
                throw new IOException("unknown tag " + tagNo + " encountered");
            }
        }
コード例 #38
0
        public virtual IAsn1Convertible ReadObject()
        {
            int num = _in.ReadByte();

            if (num == -1)
            {
                return(null);
            }
            Set00Check(enabled: false);
            int  num2 = Asn1InputStream.ReadTagNumber(_in, num);
            bool flag = (num & 0x20) != 0;
            int  num3 = Asn1InputStream.ReadLength(_in, _limit);

            if (num3 < 0)
            {
                if (!flag)
                {
                    throw new IOException("indefinite length primitive encoding encountered");
                }
                IndefiniteLengthInputStream inStream         = new IndefiniteLengthInputStream(_in, _limit);
                Asn1StreamParser            asn1StreamParser = new Asn1StreamParser(inStream, _limit);
                if ((num & 0x40) != 0)
                {
                    return(new BerApplicationSpecificParser(num2, asn1StreamParser));
                }
                if ((num & 0x80) != 0)
                {
                    return(new BerTaggedObjectParser(constructed: true, num2, asn1StreamParser));
                }
                return(asn1StreamParser.ReadIndef(num2));
            }
            DefiniteLengthInputStream definiteLengthInputStream = new DefiniteLengthInputStream(_in, num3);

            if ((num & 0x40) != 0)
            {
                return(new DerApplicationSpecific(flag, num2, definiteLengthInputStream.ToArray()));
            }
            if ((num & 0x80) != 0)
            {
                return(new BerTaggedObjectParser(flag, num2, new Asn1StreamParser(definiteLengthInputStream)));
            }
            if (flag)
            {
                switch (num2)
                {
                case 4:
                    return(new BerOctetStringParser(new Asn1StreamParser(definiteLengthInputStream)));

                case 16:
                    return(new DerSequenceParser(new Asn1StreamParser(definiteLengthInputStream)));

                case 17:
                    return(new DerSetParser(new Asn1StreamParser(definiteLengthInputStream)));

                case 8:
                    return(new DerExternalParser(new Asn1StreamParser(definiteLengthInputStream)));

                default:
                    throw new IOException("unknown tag " + num2 + " encountered");
                }
            }
            int num4 = num2;

            if (num4 != 4)
            {
                try
                {
                    return(Asn1InputStream.CreatePrimitiveDerObject(num2, definiteLengthInputStream, tmpBuffers));

IL_019e:
                    IAsn1Convertible result;
                    return(result);
                }
                catch (ArgumentException exception)
                {
                    throw new Asn1Exception("corrupted stream detected", exception);
IL_01b2:
                    IAsn1Convertible result;
                    return(result);
                }
            }
            return(new DerOctetStringParser(definiteLengthInputStream));
        }
コード例 #39
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));
            }
            }
        }
コード例 #40
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);
						}
					}
				}
			}
		}
コード例 #41
0
		/**
		 * Checks a certificate if it is revoked.
		 *
		 * @param paramsPKIX       PKIX parameters.
		 * @param cert             Certificate to check if it is revoked.
		 * @param validDate        The date when the certificate revocation status should be
		 *                         checked.
		 * @param sign             The issuer certificate of the certificate <code>cert</code>.
		 * @param workingPublicKey The public key of the issuer certificate <code>sign</code>.
		 * @param certPathCerts    The certificates of the certification path.
		 * @throws AnnotatedException if the certificate is revoked or the status cannot be checked
		 *                            or some error occurs.
		 */
		protected static void CheckCrls(
			PkixParameters			paramsPKIX,
			X509Certificate			cert,
			DateTime				validDate,
			X509Certificate			sign,
			AsymmetricKeyParameter	workingPublicKey,
			IList					certPathCerts)
		{
			Exception lastException = null;
			CrlDistPoint crldp = null;

			try
			{
				crldp = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(cert, X509Extensions.CrlDistributionPoints));
			}
			catch (Exception e)
			{
				throw new Exception("CRL distribution point extension could not be read.", e);
			}

			try
			{
				PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crldp, paramsPKIX);
			}
			catch (Exception e)
			{
				throw new Exception(
					"No additional CRL locations could be decoded from CRL distribution point extension.", e);
			}
			CertStatus certStatus = new CertStatus();
			ReasonsMask reasonsMask = new ReasonsMask();

			bool validCrlFound = false;

			// for each distribution point
			if (crldp != null)
			{
				DistributionPoint[] dps = null;
				try
				{
					dps = crldp.GetDistributionPoints();
				}
				catch (Exception e)
				{
					throw new Exception("Distribution points could not be read.", e);
				}
				if (dps != null)
				{
					for (int i = 0; i < dps.Length && certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons; i++)
					{
						PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();
						try
						{
							CheckCrl(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask, certPathCerts);
							validCrlFound = true;
						}
						catch (Exception e)
						{
							lastException = e;
						}
					}
				}
			}

			/*
			 * If the revocation status has not been determined, repeat the process
			 * above with any available CRLs not specified in a distribution point
			 * but issued by the certificate issuer.
			 */

			if (certStatus.Status == CertStatus.Unrevoked && !reasonsMask.IsAllReasons)
			{
				try
				{
					/*
					 * assume a DP with both the reasons and the cRLIssuer fields
					 * omitted and a distribution point name of the certificate
					 * issuer.
					 */
					Asn1Object issuer = null;
					try
					{
						issuer = new Asn1InputStream(cert.IssuerDN.GetEncoded()).ReadObject();
					}
					catch (Exception e)
					{
						throw new Exception("Issuer from certificate for CRL could not be reencoded.", e);
					}
					DistributionPoint dp = new DistributionPoint(new DistributionPointName(0, new GeneralNames(
						new GeneralName(GeneralName.DirectoryName, issuer))), null, null);
					PkixParameters paramsPKIXClone = (PkixParameters)paramsPKIX.Clone();

					CheckCrl(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask,
						certPathCerts);

					validCrlFound = true;
				}
				catch (Exception e)
				{
					lastException = e;
				}
			}

			if (!validCrlFound)
			{
				throw lastException;
			}
			if (certStatus.Status != CertStatus.Unrevoked)
			{
				// TODO This format is forced by the NistCertPath tests
				string formattedDate = certStatus.RevocationDate.Value.ToString(
					"G", System.util.Util.GetStandartEnUSLocale());
				string message = "Certificate revocation after " + formattedDate;
				message += ", reason: " + CrlReasons[certStatus.Status];
				throw new Exception(message);
			}

			if (!reasonsMask.IsAllReasons && certStatus.Status == CertStatus.Unrevoked)
			{
				certStatus.Status = CertStatus.Undetermined;
			}

			if (certStatus.Status == CertStatus.Undetermined)
			{
				throw new Exception("Certificate status could not be determined.");
			}
		}
コード例 #42
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));
 }
コード例 #43
0
        public virtual IAsn1Convertible ReadObject()
        {
            int num = this._in.ReadByte();

            if (num == -1)
            {
                return(null);
            }
            this.Set00Check(false);
            int  num2 = Asn1InputStream.ReadTagNumber(this._in, num);
            bool flag = (num & 32) != 0;
            int  num3 = Asn1InputStream.ReadLength(this._in, this._limit);

            if (num3 < 0)
            {
                if (!flag)
                {
                    throw new IOException("indefinite length primitive encoding encountered");
                }
                IndefiniteLengthInputStream inStream         = new IndefiniteLengthInputStream(this._in, this._limit);
                Asn1StreamParser            asn1StreamParser = new Asn1StreamParser(inStream, this._limit);
                if ((num & 64) != 0)
                {
                    return(new BerApplicationSpecificParser(num2, asn1StreamParser));
                }
                if ((num & 128) != 0)
                {
                    return(new BerTaggedObjectParser(true, num2, asn1StreamParser));
                }
                return(asn1StreamParser.ReadIndef(num2));
            }
            else
            {
                DefiniteLengthInputStream definiteLengthInputStream = new DefiniteLengthInputStream(this._in, num3);
                if ((num & 64) != 0)
                {
                    return(new DerApplicationSpecific(flag, num2, definiteLengthInputStream.ToArray()));
                }
                if ((num & 128) != 0)
                {
                    return(new BerTaggedObjectParser(flag, num2, new Asn1StreamParser(definiteLengthInputStream)));
                }
                if (flag)
                {
                    int num4 = num2;
                    if (num4 == 4)
                    {
                        return(new BerOctetStringParser(new Asn1StreamParser(definiteLengthInputStream)));
                    }
                    if (num4 == 8)
                    {
                        return(new DerExternalParser(new Asn1StreamParser(definiteLengthInputStream)));
                    }
                    switch (num4)
                    {
                    case 16:
                        return(new DerSequenceParser(new Asn1StreamParser(definiteLengthInputStream)));

                    case 17:
                        return(new DerSetParser(new Asn1StreamParser(definiteLengthInputStream)));

                    default:
                        throw new IOException("unknown tag " + num2 + " encountered");
                    }
                }
                else
                {
                    int num5 = num2;
                    if (num5 == 4)
                    {
                        return(new DerOctetStringParser(definiteLengthInputStream));
                    }
                    IAsn1Convertible result;
                    try
                    {
                        result = Asn1InputStream.CreatePrimitiveDerObject(num2, definiteLengthInputStream, this.tmpBuffers);
                    }
                    catch (ArgumentException exception)
                    {
                        throw new Asn1Exception("corrupted stream detected", exception);
                    }
                    return(result);
                }
            }
        }
コード例 #44
0
        public virtual IAsn1Convertible ReadObject()
        {
            int tag = _in.ReadByte();

            if (tag == -1)
            {
                return(null);
            }

            // turn of looking for "00" while we resolve the tag
            Set00Check(false);

            //
            // calculate tag number
            //
            int tagNo = Asn1InputStream.ReadTagNumber(_in, tag);

            bool isConstructed = (tag & Asn1Tags.Constructed) != 0;

            //
            // calculate length
            //
            int length = Asn1InputStream.ReadLength(_in, _limit);

            if (length < 0)             // indefinite length method
            {
                if (!isConstructed)
                {
                    throw new IOException("indefinite length primitive encoding encountered");
                }

                IndefiniteLengthInputStream indIn = new IndefiniteLengthInputStream(_in, _limit);
                Asn1StreamParser            sp    = new Asn1StreamParser(indIn, _limit);

                if ((tag & Asn1Tags.Application) != 0)
                {
                    return(new BerApplicationSpecificParser(tagNo, sp));
                }

                if ((tag & Asn1Tags.Tagged) != 0)
                {
                    return(new BerTaggedObjectParser(true, tagNo, sp));
                }

                return(sp.ReadIndef(tagNo));
            }
            else
            {
                DefiniteLengthInputStream defIn = new DefiniteLengthInputStream(_in, length);

                if ((tag & Asn1Tags.Application) != 0)
                {
                    return(new DerApplicationSpecific(isConstructed, tagNo, defIn.ToArray()));
                }

                if ((tag & Asn1Tags.Tagged) != 0)
                {
                    return(new BerTaggedObjectParser(isConstructed, tagNo, new Asn1StreamParser(defIn)));
                }

                if (isConstructed)
                {
                    // TODO There are other tags that may be constructed (e.g. BitString)
                    switch (tagNo)
                    {
                    case Asn1Tags.OctetString:
                        //
                        // yes, people actually do this...
                        //
                        return(new BerOctetStringParser(new Asn1StreamParser(defIn)));

                    case Asn1Tags.Sequence:
                        return(new DerSequenceParser(new Asn1StreamParser(defIn)));

                    case Asn1Tags.Set:
                        return(new DerSetParser(new Asn1StreamParser(defIn)));

                    case Asn1Tags.External:
                        return(new DerExternalParser(new Asn1StreamParser(defIn)));

                    default:
                        throw new IOException("unknown tag " + tagNo + " encountered");
                    }
                }

                // Some primitive encodings can be handled by parsers too...
                switch (tagNo)
                {
                case Asn1Tags.OctetString:
                    return(new DerOctetStringParser(defIn));
                }

                try
                {
                    return(Asn1InputStream.CreatePrimitiveDerObject(tagNo, defIn, tmpBuffers));
                }
                catch (ArgumentException e)
                {
                    throw new Asn1Exception("corrupted stream detected", e);
                }
            }
        }
コード例 #45
0
 public Asn1StreamParser(
     Stream inStream)
     : this(inStream, Asn1InputStream.FindLimit(inStream))
 {
 }
コード例 #46
0
        public Asn1Object ReadObject()
        {
            int num = this.ReadByte();

            if (num <= 0)
            {
                if (num == 0)
                {
                    throw new IOException("unexpected end-of-contents marker");
                }
                return(null);
            }
            else
            {
                int  num2 = Asn1InputStream.ReadTagNumber(this.s, num);
                bool flag = (num & 32) != 0;
                int  num3 = Asn1InputStream.ReadLength(this.s, this.limit);
                if (num3 >= 0)
                {
                    Asn1Object result;
                    try
                    {
                        result = this.BuildObject(num, num2, num3);
                    }
                    catch (ArgumentException exception)
                    {
                        throw new Asn1Exception("corrupted stream detected", exception);
                    }
                    return(result);
                }
                if (!flag)
                {
                    throw new IOException("indefinite length primitive encoding encountered");
                }
                IndefiniteLengthInputStream inStream = new IndefiniteLengthInputStream(this.s, this.limit);
                Asn1StreamParser            parser   = new Asn1StreamParser(inStream, this.limit);
                if ((num & 64) != 0)
                {
                    return(new BerApplicationSpecificParser(num2, parser).ToAsn1Object());
                }
                if ((num & 128) != 0)
                {
                    return(new BerTaggedObjectParser(true, num2, parser).ToAsn1Object());
                }
                int num4 = num2;
                if (num4 == 4)
                {
                    return(new BerOctetStringParser(parser).ToAsn1Object());
                }
                if (num4 == 8)
                {
                    return(new DerExternalParser(parser).ToAsn1Object());
                }
                switch (num4)
                {
                case 16:
                    return(new BerSequenceParser(parser).ToAsn1Object());

                case 17:
                    return(new BerSetParser(parser).ToAsn1Object());

                default:
                    throw new IOException("unknown BER object encountered");
                }
            }
        }
コード例 #47
0
 public Asn1InputStream(Stream inputStream) : this(inputStream, Asn1InputStream.FindLimit(inputStream))
 {
 }
コード例 #48
0
        internal static Asn1Object CreatePrimitiveDerObject(int tagNo, DefiniteLengthInputStream defIn, byte[][] tmpBuffers)
        {
            if (tagNo == 1)
            {
                return(DerBoolean.FromOctetString(Asn1InputStream.GetBuffer(defIn, tmpBuffers)));
            }
            if (tagNo == 6)
            {
                return(DerObjectIdentifier.FromOctetString(Asn1InputStream.GetBuffer(defIn, tmpBuffers)));
            }
            if (tagNo != 10)
            {
                byte[] array = defIn.ToArray();
                switch (tagNo)
                {
                case 2:
                    return(new DerInteger(array));

                case 3:
                    return(DerBitString.FromAsn1Octets(array));

                case 4:
                    return(new DerOctetString(array));

                case 5:
                    return(DerNull.Instance);

                case 12:
                    return(new DerUtf8String(array));

                case 18:
                    return(new DerNumericString(array));

                case 19:
                    return(new DerPrintableString(array));

                case 20:
                    return(new DerT61String(array));

                case 22:
                    return(new DerIA5String(array));

                case 23:
                    return(new DerUtcTime(array));

                case 24:
                    return(new DerGeneralizedTime(array));

                case 26:
                    return(new DerVisibleString(array));

                case 27:
                    return(new DerGeneralString(array));

                case 28:
                    return(new DerUniversalString(array));

                case 30:
                    return(new DerBmpString(array));
                }
                throw new IOException("unknown tag " + tagNo + " encountered");
            }
            return(DerEnumerated.FromOctetString(Asn1InputStream.GetBuffer(defIn, tmpBuffers)));
        }
コード例 #49
0
        public virtual IAsn1Convertible ReadObject()
        {
            IAsn1Convertible convertible;
            int tag = this._in.ReadByte();

            if (tag == -1)
            {
                return(null);
            }
            this.Set00Check(false);
            int  num2          = Asn1InputStream.ReadTagNumber(this._in, tag);
            bool isConstructed = (tag & 0x20) != 0;
            int  length        = Asn1InputStream.ReadLength(this._in, this._limit);

            if (length < 0)
            {
                if (!isConstructed)
                {
                    throw new IOException("indefinite length primitive encoding encountered");
                }
                IndefiniteLengthInputStream stream = new IndefiniteLengthInputStream(this._in, this._limit);
                Asn1StreamParser            parser = new Asn1StreamParser(stream, this._limit);
                if ((tag & 0x40) != 0)
                {
                    return(new BerApplicationSpecificParser(num2, parser));
                }
                if ((tag & 0x80) != 0)
                {
                    return(new BerTaggedObjectParser(true, num2, parser));
                }
                return(parser.ReadIndef(num2));
            }
            DefiniteLengthInputStream inStream = new DefiniteLengthInputStream(this._in, length);

            if ((tag & 0x40) != 0)
            {
                return(new DerApplicationSpecific(isConstructed, num2, inStream.ToArray()));
            }
            if ((tag & 0x80) != 0)
            {
                return(new BerTaggedObjectParser(isConstructed, num2, new Asn1StreamParser(inStream)));
            }
            if (isConstructed)
            {
                switch (num2)
                {
                case 0x10:
                    return(new DerSequenceParser(new Asn1StreamParser(inStream)));

                case 0x11:
                    return(new DerSetParser(new Asn1StreamParser(inStream)));

                case 4:
                    return(new BerOctetStringParser(new Asn1StreamParser(inStream)));

                case 8:
                    return(new DerExternalParser(new Asn1StreamParser(inStream)));
                }
                throw new IOException("unknown tag " + num2 + " encountered");
            }
            if (num2 == 4)
            {
                return(new DerOctetStringParser(inStream));
            }
            try
            {
                convertible = Asn1InputStream.CreatePrimitiveDerObject(num2, inStream, this.tmpBuffers);
            }
            catch (ArgumentException exception)
            {
                throw new Asn1Exception("corrupted stream detected", exception);
            }
            return(convertible);
        }
コード例 #50
0
        public virtual IAsn1Convertible ReadObject()
        {
            //IL_004f: Unknown result type (might be due to invalid IL or missing references)
            //IL_014a: Unknown result type (might be due to invalid IL or missing references)
            //IL_0174: Expected O, but got Unknown
            int num = _in.ReadByte();

            if (num == -1)
            {
                return(null);
            }
            Set00Check(enabled: false);
            int  num2 = Asn1InputStream.ReadTagNumber(_in, num);
            bool flag = (num & 0x20) != 0;
            int  num3 = Asn1InputStream.ReadLength(_in, _limit);

            if (num3 < 0)
            {
                if (!flag)
                {
                    throw new IOException("indefinite length primitive encoding encountered");
                }
                IndefiniteLengthInputStream inStream         = new IndefiniteLengthInputStream(_in, _limit);
                Asn1StreamParser            asn1StreamParser = new Asn1StreamParser((Stream)(object)inStream, _limit);
                if (((uint)num & 0x40u) != 0)
                {
                    return(new BerApplicationSpecificParser(num2, asn1StreamParser));
                }
                if (((uint)num & 0x80u) != 0)
                {
                    return(new BerTaggedObjectParser(constructed: true, num2, asn1StreamParser));
                }
                return(asn1StreamParser.ReadIndef(num2));
            }
            DefiniteLengthInputStream definiteLengthInputStream = new DefiniteLengthInputStream(_in, num3);

            if (((uint)num & 0x40u) != 0)
            {
                return(new DerApplicationSpecific(flag, num2, definiteLengthInputStream.ToArray()));
            }
            if (((uint)num & 0x80u) != 0)
            {
                return(new BerTaggedObjectParser(flag, num2, new Asn1StreamParser((Stream)(object)definiteLengthInputStream)));
            }
            if (flag)
            {
                switch (num2)
                {
                case 4:
                    return(new BerOctetStringParser(new Asn1StreamParser((Stream)(object)definiteLengthInputStream)));

                case 16:
                    return(new DerSequenceParser(new Asn1StreamParser((Stream)(object)definiteLengthInputStream)));

                case 17:
                    return(new DerSetParser(new Asn1StreamParser((Stream)(object)definiteLengthInputStream)));

                case 8:
                    return(new DerExternalParser(new Asn1StreamParser((Stream)(object)definiteLengthInputStream)));

                default:
                    throw new IOException(string.Concat((object)"unknown tag ", (object)num2, (object)" encountered"));
                }
            }
            int num4 = num2;

            if (num4 == 4)
            {
                return(new DerOctetStringParser(definiteLengthInputStream));
            }
            try
            {
                return(Asn1InputStream.CreatePrimitiveDerObject(num2, definiteLengthInputStream, tmpBuffers));
            }
            catch (ArgumentException val)
            {
                ArgumentException exception = val;
                throw new Asn1Exception("corrupted stream detected", (global::System.Exception)(object) exception);
            }
        }
コード例 #51
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);
        }