public override void PerformTest()
        {
            byte[] data = { 0, 1, 0, 1, 0, 0, 1 };

            Asn1Object[] values =
            {
                new BerOctetString(data),
                new BerSequence(new DerPrintableString("hello world")),
                new BerSet(new DerPrintableString("hello world")),
                new BerTaggedObject(0, new DerPrintableString("hello world")),
                new DerApplicationSpecific(0, data),
                new DerBitString(data),
                new DerBmpString("hello world"),
                DerBoolean.True,
                DerBoolean.False,
                new DerEnumerated(100),
                new DerGeneralizedTime("20070315173729Z"),
                new DerGeneralString("hello world"),
                new DerIA5String("hello"),
                new DerInteger(1000),
                DerNull.Instance,
                new DerNumericString("123456"),
                new DerObjectIdentifier("1.1.1.10000.1"),
                new DerOctetString(data),
                new DerPrintableString("hello world"),
                new DerSequence(new DerPrintableString("hello world")),
                new DerSet(new DerPrintableString("hello world")),
                new DerT61String("hello world"),
                new DerTaggedObject(0, new DerPrintableString("hello world")),
                new DerUniversalString(data),
                new DerUnknownTag(true, 500, data),
                new DerUtcTime(new DateTime()),
                new DerUtf8String("hello world"),
                new DerVisibleString("hello world")
            };

            MemoryStream bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            for (int i = 0; i != values.Length; i++)
            {
                aOut.WriteObject(values[i]);
            }

            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            for (int i = 0; i != values.Length; i++)
            {
                Asn1Object o = aIn.ReadObject();
                if (!o.Equals(values[i]))
                {
                    Fail("Failed equality test for " + o.GetType().Name);
                }

                if (o.GetHashCode() != values[i].GetHashCode())
                {
                    Fail("Failed hashCode test for " + o.GetType().Name);
                }
            }
        }
Exemplo n.º 2
0
		private void inputStreamTest()
		{
			foreach (string stream in streams)
			{
				Asn1InputStream aIn = new Asn1InputStream(Base64.Decode(stream));

				try
				{
					Object obj;
					while ((obj = aIn.ReadObject()) != null)
					{
					}

					Fail("bad stream parsed successfully!");
				}
				catch (IOException)
				{
					// ignore
				}
				// Note: C# may throw these instead, since no InMemoryRepresentable support
				catch (Asn1ParsingException)
				{
					// ignore
				}
			}
		}
Exemplo n.º 3
0
		private void checkConstruction(
			NameOrPseudonym	id,
			string			pseudonym,
			DirectoryString	surname,
			Asn1Sequence	givenName)
		{
			checkValues(id, pseudonym, surname, givenName);

			id = NameOrPseudonym.GetInstance(id);

			checkValues(id, pseudonym, surname, givenName);

			Asn1InputStream aIn = new Asn1InputStream(id.ToAsn1Object().GetEncoded());

			if (surname != null)
			{
				Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

				id = NameOrPseudonym.GetInstance(seq);
			}
			else
			{
				IAsn1String s = (IAsn1String) aIn.ReadObject();

				id = NameOrPseudonym.GetInstance(s);
			}

			checkValues(id, pseudonym, surname, givenName);
		}
Exemplo n.º 4
0
        public ITestResult Perform()
        {
            byte[] testIv = { 1, 2, 3, 4, 5, 6, 7, 8 };

            Asn1Encodable[] values =
            {
                new Cast5CbcParameters(testIv, 128),
                new NetscapeCertType(NetscapeCertType.Smime),
                new VerisignCzagExtension(new DerIA5String("hello")),
            #if INCLUDE_IDEA
                new IdeaCbcPar(testIv),
            #endif
                new NetscapeRevocationUrl(new DerIA5String("http://test"))
            };

            #if INCLUDE_IDEA
            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvMAoECAECAwQFBgcIFgtodHRwOi8vdGVzdA==");
            #else
            byte[] data = Base64.Decode("MA4ECAECAwQFBgcIAgIAgAMCBSAWBWhlbGxvFgtodHRwOi8vdGVzdA==");
            #endif

            try
            {
                MemoryStream bOut = new MemoryStream();
                Asn1OutputStream aOut = new Asn1OutputStream(bOut);

                for (int i = 0; i != values.Length; i++)
                {
                    aOut.WriteObject(values[i]);
                }

                if (!Arrays.AreEqual(bOut.ToArray(), data))
                {
                    return new SimpleTestResult(false, Name + ": Failed data check");
                }

                Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

                for (int i = 0; i != values.Length; i++)
                {
                    Asn1Object o = aIn.ReadObject();

                    if (!values[i].Equals(o))
                    {
                        return new SimpleTestResult(false, Name + ": Failed equality test for " + o);
                    }

                    if (o.GetHashCode() != values[i].GetHashCode())
                    {
                        return new SimpleTestResult(false, Name + ": Failed hashCode test for " + o);
                    }
                }

                return new SimpleTestResult(true, Name + ": Okay");
            }
            catch (Exception e)
            {
                return new SimpleTestResult(false, Name + ": Failed - exception " + e.ToString(), e);
            }
        }
Exemplo n.º 5
0
        private X509Crl ReadDerCrl(Asn1InputStream dIn)
        {
            Asn1Sequence asn1Sequence = (Asn1Sequence)dIn.ReadObject();

            if (asn1Sequence.Count > 1 && asn1Sequence[0] is DerObjectIdentifier && asn1Sequence[0].Equals(PkcsObjectIdentifiers.SignedData))
            {
                this.sCrlData = SignedData.GetInstance(Asn1Sequence.GetInstance((Asn1TaggedObject)asn1Sequence[1], true)).Crls;
                return(this.GetCrl());
            }
            return(this.CreateX509Crl(CertificateList.GetInstance(asn1Sequence)));
        }
Exemplo n.º 6
0
        private X509Certificate ReadDerCertificate(Asn1InputStream dIn)
        {
            Asn1Sequence asn1Sequence = (Asn1Sequence)dIn.ReadObject();

            if (asn1Sequence.Count > 1 && asn1Sequence[0] is DerObjectIdentifier && asn1Sequence[0].Equals(PkcsObjectIdentifiers.SignedData))
            {
                sData = SignedData.GetInstance(Asn1Sequence.GetInstance((Asn1TaggedObject)asn1Sequence[1], explicitly: true)).Certificates;
                return(GetCertificate());
            }
            return(CreateX509Certificate(X509CertificateStructure.GetInstance(asn1Sequence)));
        }
Exemplo n.º 7
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));
            }
        }
Exemplo n.º 8
0
 /// <summary>Get the "subject" from the TBSCertificate bytes that are passed in.</summary>
 /// <param name="enc">A TBSCertificate in a byte array</param>
 /// <returns>a ASN1Primitive</returns>
 public static Asn1Object GetSubject(byte[] enc)
 {
     try {
         Asn1InputStream @in = new Asn1InputStream(new MemoryStream(enc));
         Asn1Sequence    seq = (Asn1Sequence)@in.ReadObject();
         return((Asn1Object)seq[seq[0] is Asn1TaggedObject ? 5 : 4]);
     }
     catch (System.IO.IOException e) {
         throw new PdfException(e);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Lookup and Parse AIA URLs. Normally it should include two URLs:
        /// 1. AIA OCSP
        /// 2. AIA Issuer
        /// </summary>
        /// <param name="cert"></param>
        /// <returns></returns>
        AIA ParseAIA(System.Security.Cryptography.X509Certificates.X509Certificate2 cert)
        {
            try
            {
                var bc = (new Org.BouncyCastle.X509.X509CertificateParser()).ReadCertificate(cert.RawData);

                byte[] bytes = bc.GetExtensionValue(new DerObjectIdentifier(
                                                        Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityInfoAccess.Id)).GetOctets();

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

                Asn1InputStream aIn = new Asn1InputStream(bytes);
                Asn1Object      obj = aIn.ReadObject();

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

                Asn1Sequence s        = (Asn1Sequence)obj;
                var          elements = s.GetEnumerator();

                string ocspUrl = null, issuerUrl = null;
                while (elements.MoveNext())
                {
                    Asn1Sequence        element = (Asn1Sequence)elements.Current;
                    DerObjectIdentifier oid     = (DerObjectIdentifier)element[0];

                    if (oid.Id.Equals("1.3.6.1.5.5.7.48.1"))
                    {
                        var taggedObject = (Asn1TaggedObject)element[1];
                        ocspUrl = ExtractAIAUrl(taggedObject);
                    }
                    else if (oid.Id.Equals("1.3.6.1.5.5.7.48.2"))
                    {
                        var taggedObject = (Asn1TaggedObject)element[1];
                        issuerUrl = ExtractAIAUrl(taggedObject);
                    }
                }
                return(new AIA()
                {
                    Issuer = issuerUrl,
                    Ocsp = ocspUrl
                });
            }
            catch (Exception ex)
            {
                //Log.Error(ex);
                return(null);
            }
        }
Exemplo n.º 10
0
 private OcspResp(Asn1InputStream aIn)
 {
     //IL_002b: Unknown result type (might be due to invalid IL or missing references)
     try
     {
         resp = OcspResponse.GetInstance(aIn.ReadObject());
     }
     catch (global::System.Exception ex)
     {
         throw new IOException("malformed response: " + ex.get_Message(), ex);
     }
 }
Exemplo n.º 11
0
        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));
            }
        }
Exemplo n.º 12
0
        public static void Main(string[] args)
        {
            FileStream      inputStream     = File.OpenRead(args[0]);
            Asn1InputStream asn1InputStream = new Asn1InputStream((Stream)(object)inputStream);
            Asn1Object      obj;

            while ((obj = asn1InputStream.ReadObject()) != null)
            {
                Console.WriteLine(Asn1Dump.DumpAsString(obj));
            }
            Platform.Dispose((Stream)(object)asn1InputStream);
        }
Exemplo n.º 13
0
        public static (BigInteger r, BigInteger s, BigInteger v) GetRSV(byte[] signature)
        {
            using (var stream = new Asn1InputStream(signature))
            {
                var sequence = (DerSequence)stream.ReadObject();
                var r        = ((DerInteger)sequence[0]).Value;
                var s        = ((DerInteger)sequence[1]).Value;
                var v        = ((DerInteger)sequence[2]).Value;

                return(r, s, v);
            }
        }
Exemplo n.º 14
0
 private OcspResp(
     Asn1InputStream aIn)
 {
     try
     {
         this.resp = OcspResponse.GetInstance(aIn.ReadObject());
     }
     catch (Exception e)
     {
         throw new IOException("malformed response: " + e.Message, e);
     }
 }
Exemplo n.º 15
0
        private byte[] TimestampAuthorityResponse(EstEIDReader estEidReader, byte[] signedPkcs)
        {
            ArrayList newSigners = new ArrayList();

            CmsSignedData sd = new CmsSignedData(signedPkcs);

            foreach (SignerInformation si in sd.GetSignerInfos().GetSigners())
            {
                // possible TSA URLs
                //string TsaServerUrl = "http://www.edelweb.fr/cgi-bin/service-tsp";
                //string TsaServerUrl = "http://dse200.ncipher.com/TSS/HttpTspServer";

                byte[] signedDigest  = si.GetSignature();
                byte[] timeStampHash = ComputeHash(estEidReader, signedDigest);

                string TsaServerUrl = stamp.Url;
                string TsaUser      = stamp.User;
                string TsaPassword  = stamp.Password;
                string error        = string.Empty;

                byte[] timeStampToken = X509Utils.GetTimestampToken(TsaServerUrl,
                                                                    TsaUser,
                                                                    TsaPassword,
                                                                    timeStampHash,
                                                                    ref error);

                if (timeStampToken == null)
                {
                    throw new Exception(Resources.TSA_ERROR + error);
                }

                Hashtable  ht     = new Hashtable();
                Asn1Object derObj = new Asn1InputStream(timeStampToken).ReadObject();
                DerSet     derSet = new DerSet(derObj);

                Org.BouncyCastle.Asn1.Cms.Attribute unsignAtt = new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(X509Utils.ID_TIME_STAMP_TOKEN), derSet);

                ht.Add(X509Utils.ID_TIME_STAMP_TOKEN, unsignAtt);

                Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAtts = new Org.BouncyCastle.Asn1.Cms.AttributeTable(ht);

                newSigners.Add(SignerInformation.ReplaceUnsignedAttributes(si, unsignedAtts));
            }

            SignerInformationStore newSignerInformationStore = new SignerInformationStore(newSigners);

            CmsSignedData newSd = CmsSignedData.ReplaceSigners(sd, newSignerInformationStore);

            // Encode the CMS/PKCS #7 message
            return(newSd.GetEncoded());
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Parses a transport extension from an attestation certificate and returns
        ///     a List of HardwareFeatures supported by the security key.
        /// </summary>
        /// <remarks>
        ///     Parses a transport extension from an attestation certificate and returns
        ///     a List of HardwareFeatures supported by the security key. The specification of
        ///     the HardwareFeatures in the certificate should match their internal definition in
        ///     device_auth.proto
        ///     <p>
        ///         The expected transport extension value is a BIT STRING containing the enabled
        ///         transports:
        ///     </p>
        ///     <p>
        ///         FIDOU2FTransports ::= BIT STRING {
        ///         bluetoothRadio(0), -- Bluetooth Classic
        ///         bluetoothLowEnergyRadio(1),
        ///         uSB(2),
        ///         nFC(3)
        ///         }
        ///     </p>
        ///     <p>
        ///         Note that the BIT STRING must be wrapped in an OCTET STRING.
        ///         An extension that encodes BT, BLE, and NFC then looks as follows:
        ///     </p>
        ///     <p>
        ///         SEQUENCE (2 elem)
        ///         OBJECT IDENTIFIER 1.3.6.1.4.1.45724.2.1.1
        ///         OCTET STRING (1 elem)
        ///         BIT STRING (4 bits) 1101
        ///     </p>
        /// </remarks>
        /// <param name="cert">the certificate to parse for extension</param>
        /// <returns>
        ///     the supported transports as a List of HardwareFeatures or null if no extension
        ///     was found
        /// </returns>
        /// <exception cref="CertificateParsingException" />
        public static IList <SecurityKeyDataTransports> ParseTransportsExtension(X509Certificate cert)
        {
            var extValue       = cert.GetExtensionValue(transportExtensionOid);
            var transportsList = new List <SecurityKeyDataTransports>();

            if (extValue == null)
            {
                // No transports extension found.
                return(null);
            }

            // Read out the OctetString
            var asn1Object = extValue.ToAsn1Object();

            if (!(asn1Object is DerOctetString))
            {
                throw new CertificateParsingException("No Octet String found in transports extension");
            }
            var octet = (DerOctetString)asn1Object;

            // Read out the BitString

            try
            {
                using (var ais = new Asn1InputStream(octet.GetOctets()))
                {
                    asn1Object = ais.ReadObject();
                }
            }
            catch (IOException e)
            {
                throw new CertificateParsingException("Not able to read object in transports extension", e);
            }
            if (!(asn1Object is DerBitString))
            {
                throw new CertificateParsingException("No BitString found in transports extension");
            }

            var bitString = (DerBitString)asn1Object;
            var values    = bitString.GetBytes();
            var bitSet    = new BitArray(values);

            // We might have more defined transports than used by the extension
            for (var i = 0; i < BITS_IN_A_BYTE; i++)
            {
                if (bitSet.Get(BITS_IN_A_BYTE - i - 1))
                {
                    transportsList.Add((SecurityKeyDataTransports)i);
                }
            }
            return(transportsList);
        }
Exemplo n.º 17
0
        public static void Main(string[] args)
        {
            FileStream fIn = File.OpenRead(args[0]);
            Asn1InputStream bIn = new Asn1InputStream(fIn);

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

            Platform.Dispose(bIn);
        }
Exemplo n.º 18
0
        // helper methods

        /**
         * @param certificate   the certificate from which we need the ExtensionValue
         * @param oid the Object Identifier value for the extension.
         * @return  the extension value as an ASN1Primitive object
         * @throws IOException
         */
        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());
        }
Exemplo n.º 19
0
            /**
             * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
             * API.
             *
             * @return the X509Certificate
             */
            public Object ParseObject(PemObject obj)
            {
                try
                {
                    Asn1InputStream aIn = new Asn1InputStream(obj.GetContent());

                    return(ContentInfo.GetInstance(aIn.ReadObject()));
                }
                catch (Exception e)
                {
                    throw new OpenSslPemParsingException("problem parsing PKCS7 object: " + e.ToString(), e);
                }
            }
Exemplo n.º 20
0
        // helper methods
        /// <param name="certificate">the certificate from which we need the ExtensionValue</param>
        /// <param name="oid">the Object Identifier value for the extension.</param>
        /// <returns>the extension value as an ASN1Primitive object</returns>
        private static Asn1Object GetExtensionValue(X509Certificate certificate, String oid)
        {
            byte[] bytes = SignUtils.GetExtensionValueByOid(certificate, oid);
            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());
        }
Exemplo n.º 21
0
        public static string DumpDer(byte[] der)
        {
            StringBuilder   builder = new StringBuilder();
            Asn1InputStream decoder = new Asn1InputStream(der);
            DerSequence     seq     = (DerSequence)decoder.ReadObject();

            builder.AppendLine("Version : " + Encoders.Hex.EncodeData(seq[0].GetDerEncoded()));
            builder.AppendLine("Private : " + Encoders.Hex.EncodeData(seq[1].GetDerEncoded()));
            builder.AppendLine("Params : " + Encoders.Hex.EncodeData(((DerTaggedObject)seq[2]).GetObject().GetDerEncoded()));
            builder.AppendLine("Public : " + Encoders.Hex.EncodeData(seq[3].GetDerEncoded()));
            decoder.Close();
            return(builder.ToString());
        }
Exemplo n.º 22
0
        public static byte[] ConvertDerToP1393(byte[] bcSignature)
        {
            var asn1Stream = new Asn1InputStream(bcSignature);

            var bcDerSequence = ((DerSequence)asn1Stream.ReadObject());
            var bcR           = ((DerInteger)bcDerSequence[0]).PositiveValue.ToByteArrayUnsigned();
            var bcS           = ((DerInteger)bcDerSequence[1]).PositiveValue.ToByteArrayUnsigned();

            var buff = new byte[bcR.Length + bcS.Length];

            Array.Copy(bcR, 0, buff, 0, bcR.Length);
            Array.Copy(bcS, 0, buff, bcR.Length, bcS.Length);
            return(buff);
        }
Exemplo n.º 23
0
        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();
        }
Exemplo n.º 24
0
        public static void MainOld(string[] args)
        {
            FileStream      fIn = File.OpenRead(args[0]);
            Asn1InputStream bIn = new Asn1InputStream(fIn);

            Asn1Object obj;

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

            Platform.Dispose(bIn);
        }
Exemplo n.º 25
0
 protected static Asn1Object GetExtensionValue(X509Certificate cert, string oid)
 {
     if (cert != null)
     {
         byte[] octets = cert.GetExtensionValue(new DerObjectIdentifier(oid)).GetOctets();
         if (octets != null)
         {
             Asn1InputStream asn1InputStream = new Asn1InputStream(octets);
             return(asn1InputStream.ReadObject());
         }
         return(null);
     }
     return(null);
 }
Exemplo n.º 26
0
        /**
         * Creates a CertPath of the specified type.
         * This constructor is protected because most users should use
         * a CertificateFactory to create CertPaths.
         *
         * @param type the standard name of the type of Certificatesin this path
         **/
        public PkixCertPath(
            Stream inStream,
            string encoding)
//			: base("X.509")
        {
            string upper = Platform.ToUpperInvariant(encoding);

            IList certs;

            try
            {
                if (upper.Equals(Platform.ToUpperInvariant("PkiPath")))
                {
                    Asn1InputStream derInStream = new Asn1InputStream(inStream);
                    Asn1Object      derObject   = derInStream.ReadObject();
                    if (!(derObject is Asn1Sequence))
                    {
                        throw new CertificateException(
                                  "input stream does not contain a ASN1 SEQUENCE while reading PkiPath encoded data to load CertPath");
                    }

                    certs = Platform.CreateArrayList();

                    foreach (Asn1Encodable ae in (Asn1Sequence)derObject)
                    {
                        byte[] derBytes     = ae.GetEncoded(Asn1Encodable.Der);
                        Stream certInStream = new MemoryStream(derBytes, false);

                        // TODO Is inserting at the front important (list will be sorted later anyway)?
                        certs.Insert(0, new X509CertificateParser().ReadCertificate(certInStream));
                    }
                }
                else if (upper.Equals("PKCS7") || upper.Equals("PEM"))
                {
                    certs = Platform.CreateArrayList(new X509CertificateParser().ReadCertificates(inStream));
                }
                else
                {
                    throw new CertificateException("unsupported encoding: " + encoding);
                }
            }
            catch (IOException ex)
            {
                throw new CertificateException(
                          "IOException throw while decoding CertPath:\n"
                          + ex.ToString());
            }

            this.certificates = SortCerts(certs);
        }
Exemplo n.º 27
0
        private void ReadSigKey(byte[] sig, out BigIntegerBouncy r, out BigIntegerBouncy s)
        {
            // sig is two DER encoded integers: r and s
            // total length is variable

            using (var stream = new Asn1InputStream(sig.ToArray()))
            {
                var sequence = (DerSequence)stream.ReadObject();
                r = ((DerInteger)sequence[0]).Value;
                s = ((DerInteger)sequence[1]).Value;

                Debug.Assert(sequence.Count == 2);
                //TODO Debug.Assert(sig.SequenceEqual(sequence.GetDerEncoded()));
            }
        }
Exemplo n.º 28
0
        public static Asn1Object ReadAsn1Object(byte[] encoding)
        {
            Asn1InputStream asn1   = new Asn1InputStream(encoding);
            Asn1Object      result = asn1.ReadObject();

            if (null == result)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }
            if (null != asn1.ReadObject())
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }
            return(result);
        }
Exemplo n.º 29
0
        public Certificate(PalX509Certificate cert)
        {
            ReadOnlyMemory <byte> data = cert.ExportCertificate();

            Asn1InputStream decoder = new Asn1InputStream(data.ToArray());

            Asn1Object   obj = decoder.ReadObject();
            Asn1Sequence seq = Asn1Sequence.GetInstance(obj);

            X509CertificateStructure st = X509CertificateStructure.GetInstance(seq);

            this.CertData = new X509Certificate(st);

            InitFields();
        }
Exemplo n.º 30
0
        private bool ValidateAlternateSigner(X509Certificate certificate, X509Certificate issuer)
        {
            byte[]           bytes            = certificate.GetExtensionValue(new DerObjectIdentifier(X509Extensions.ExtendedKeyUsage.Id)).GetOctets();
            Asn1InputStream  aIn              = new Asn1InputStream(bytes);
            var              As1              = aIn.ReadObject();
            ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.GetInstance(As1);
            var              extendedKey      = extendedKeyUsage.GetAllUsages().Cast <DerObjectIdentifier>().ToList();

            if (extendedKey.Any(x => x.Id == "1.3.6.1.5.5.7.3.9"))
            {
                certificate.Verify(issuer.GetPublicKey());
                return(true);
            }
            return(false);
        }
        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);
        }
 private static TimeStampResp readTimeStampResp(Asn1InputStream input)
 {
     try
     {
         return(TimeStampResp.GetInstance(input.ReadObject()));
     }
     catch (ArgumentException ex)
     {
         throw new TspException("malformed timestamp response: " + ex, ex);
     }
     catch (InvalidCastException ex2)
     {
         throw new TspException("malformed timestamp response: " + ex2, ex2);
     }
 }
Exemplo n.º 33
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
        }
Exemplo n.º 34
0
 private OcspReq(Asn1InputStream aIn)
 {
     try
     {
         this.req = OcspRequest.GetInstance(aIn.ReadObject());
     }
     catch (ArgumentException ex)
     {
         throw new IOException("malformed request: " + ex.Message);
     }
     catch (InvalidCastException ex2)
     {
         throw new IOException("malformed request: " + ex2.Message);
     }
 }
Exemplo n.º 35
0
 private TimeStampRequest(Asn1InputStream str)
 {
     try
     {
         this.req = TimeStampReq.GetInstance(str.ReadObject());
     }
     catch (InvalidCastException arg)
     {
         throw new IOException("malformed request: " + arg);
     }
     catch (ArgumentException arg2)
     {
         throw new IOException("malformed request: " + arg2);
     }
 }
Exemplo n.º 36
0
		public override void PerformTest()
		{
			Asn1InputStream aIn = new Asn1InputStream(outOfBoundsLength);

			try
			{
				aIn.ReadObject();
				Fail("out of bounds length not detected.");
			}
			catch (IOException e)
			{
				if (!e.Message.StartsWith("DER length more than 4 bytes"))
				{
					Fail("wrong exception: " + e.Message);
				}
			}

			aIn = new Asn1InputStream(negativeLength);

			try
			{
				aIn.ReadObject();
				Fail("negative length not detected.");
			}
			catch (IOException e)
			{
				if (!e.Message.Equals("Corrupted stream - negative length found"))
				{
					Fail("wrong exception: " + e.Message);
				}
			}

			aIn = new Asn1InputStream(outsideLimitLength);

			try
			{
				aIn.ReadObject();
				Fail("outside limit length not detected.");
			}
			catch (IOException e)
			{
				if (!e.Message.Equals("Corrupted stream - out of bounds length found"))
				{
					Fail("wrong exception: " + e.Message);
				}
			}
		}
		private void checkConstruction(
			OtherSigningCertificate	otherCert,
			OtherCertID				otherCertID)
		{
			checkValues(otherCert, otherCertID);

			otherCert = OtherSigningCertificate.GetInstance(otherCert);

			checkValues(otherCert, otherCertID);

			Asn1InputStream aIn = new Asn1InputStream(otherCert.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			otherCert = OtherSigningCertificate.GetInstance(seq);

			checkValues(otherCert, otherCertID);
		}
		private void checkConstruction(
			AdditionalInformationSyntax syntax,
			DirectoryString information)
		{
			checkValues(syntax, information);

			syntax = AdditionalInformationSyntax.GetInstance(syntax);

			checkValues(syntax, information);

			Asn1InputStream aIn = new Asn1InputStream(syntax.ToAsn1Object().GetEncoded());

			IAsn1String info = (IAsn1String) aIn.ReadObject();

			syntax = AdditionalInformationSyntax.GetInstance(info);

			checkValues(syntax, information);
		}
Exemplo n.º 39
0
		private void checkConstruction(
			Restriction		restriction,
			DirectoryString	res)
		{
			checkValues(restriction, res);

			restriction = Restriction.GetInstance(restriction);

			checkValues(restriction, res);

			Asn1InputStream aIn = new Asn1InputStream(restriction.ToAsn1Object().GetEncoded());

			IAsn1String str = (IAsn1String) aIn.ReadObject();

			restriction = Restriction.GetInstance(str);

			checkValues(restriction, res);
		}
Exemplo n.º 40
0
		private void checkConstruction(
			CertHash			certHash,
			AlgorithmIdentifier	algId,
			byte[]				digest)
		{
			checkValues(certHash, algId, digest);

			certHash = CertHash.GetInstance(certHash);

			checkValues(certHash, algId, digest);

			Asn1InputStream aIn = new Asn1InputStream(certHash.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			certHash = CertHash.GetInstance(seq);

			checkValues(certHash, algId, digest);
		}
Exemplo n.º 41
0
		private void checkConstruction(
			Admissions      admissions,
			GeneralName     name,
			NamingAuthority auth)
		{
			checkValues(admissions, name, auth);

			admissions = Admissions.GetInstance(admissions);

			checkValues(admissions, name, auth);

			Asn1InputStream aIn = new Asn1InputStream(admissions.ToAsn1Object().GetEncoded());

			Asn1Sequence info = (Asn1Sequence)aIn.ReadObject();

			admissions = Admissions.GetInstance(info);

			checkValues(admissions, name, auth);
		}
		private void checkConstruction(
			AdmissionSyntax	syntax,
			GeneralName		authority,
			Asn1Sequence	admissions)
		{
			checkValues(syntax, authority, admissions);

			syntax = AdmissionSyntax.GetInstance(syntax);

			checkValues(syntax, authority, admissions);

			Asn1InputStream aIn = new Asn1InputStream(syntax.ToAsn1Object().GetEncoded());

			Asn1Sequence info = (Asn1Sequence) aIn.ReadObject();

			syntax = AdmissionSyntax.GetInstance(info);

			checkValues(syntax, authority, admissions);
		}
Exemplo n.º 43
0
		private void checkConstruction(
			ContentHints		hints,
			DerObjectIdentifier	contentType,
			DerUtf8String		description)
		{
			checkValues(hints, contentType, description);

			hints = ContentHints.GetInstance(hints);

			checkValues(hints, contentType, description);

			Asn1InputStream aIn = new Asn1InputStream(hints.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			hints = ContentHints.GetInstance(seq);

			checkValues(hints, contentType, description);
		}
		private void checkConstruction(
			DeclarationOfMajority			decl,
			DeclarationOfMajority.Choice	type,
			DerGeneralizedTime				dateOfBirth,
			int								notYoungerThan)
		{
			checkValues(decl, type, dateOfBirth, notYoungerThan);

			decl = DeclarationOfMajority.GetInstance(decl);

			checkValues(decl, type, dateOfBirth, notYoungerThan);

			Asn1InputStream aIn = new Asn1InputStream(decl.ToAsn1Object().GetEncoded());

			DerTaggedObject info = (DerTaggedObject) aIn.ReadObject();

			decl = DeclarationOfMajority.GetInstance(info);

			checkValues(decl, type, dateOfBirth, notYoungerThan);
		}
Exemplo n.º 45
0
		private void checkConstruction(
			OtherCertID			certID,
			AlgorithmIdentifier	algId,
			byte[]				digest,
			IssuerSerial		issuerSerial)
		{
			checkValues(certID, algId, digest, issuerSerial);

			certID = OtherCertID.GetInstance(certID);

			checkValues(certID, algId, digest, issuerSerial);

			Asn1InputStream aIn = new Asn1InputStream(certID.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			certID = OtherCertID.GetInstance(seq);

			checkValues(certID, algId, digest, issuerSerial);
		}
		private void checkConstruction(
			NamingAuthority		auth,
			DerObjectIdentifier	namingAuthorityID,
			string				namingAuthorityURL,
			DirectoryString		namingAuthorityText)
		{
			checkValues(auth, namingAuthorityID, namingAuthorityURL, namingAuthorityText);

			auth = NamingAuthority.GetInstance(auth);

			checkValues(auth, namingAuthorityID, namingAuthorityURL, namingAuthorityText);

			Asn1InputStream aIn = new Asn1InputStream(auth.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			auth = NamingAuthority.GetInstance(seq);

			checkValues(auth, namingAuthorityID, namingAuthorityURL, namingAuthorityText);
		}
		private void checkConstruction(
			RequestedCertificate		requested,
			RequestedCertificate.Choice	type,
			byte[]						certOctets,
			X509CertificateStructure	cert)
		{
			checkValues(requested, type, certOctets, cert);

			requested = RequestedCertificate.GetInstance(requested);

			checkValues(requested, type, certOctets, cert);

			Asn1InputStream aIn = new Asn1InputStream(requested.ToAsn1Object().GetEncoded());

			object obj = aIn.ReadObject();

			requested = RequestedCertificate.GetInstance(obj);

			checkValues(requested, type, certOctets, cert);
		}
Exemplo n.º 48
0
		private void checkConstruction(
			MonetaryLimit	limit,
			string			currency,
			int				amount,
			int				exponent)
		{
			checkValues(limit, currency, amount, exponent);

			limit = MonetaryLimit.GetInstance(limit);

			checkValues(limit, currency, amount, exponent);

			Asn1InputStream aIn = new Asn1InputStream(limit.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			limit = MonetaryLimit.GetInstance(seq);

			checkValues(limit, currency, amount, exponent);
		}
		private void checkConstruction(
			ProcurationSyntax	procuration,
			string				country,
			DirectoryString		typeOfSubstitution,
			GeneralName			thirdPerson,
			IssuerSerial		certRef)
		{
			checkValues(procuration, country, typeOfSubstitution, thirdPerson, certRef);

			procuration = ProcurationSyntax.GetInstance(procuration);

			checkValues(procuration, country, typeOfSubstitution, thirdPerson, certRef);

			Asn1InputStream aIn = new Asn1InputStream(procuration.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			procuration = ProcurationSyntax.GetInstance(seq);

			checkValues(procuration, country, typeOfSubstitution, thirdPerson, certRef);
		}
		private void checkConstruction(
			ProfessionInfo			profInfo,
			NamingAuthority			auth,
			DirectoryString[]		professionItems,
			DerObjectIdentifier[]	professionOids,
			string					registrationNumber,
			DerOctetString			addProfInfo)
		{
			checkValues(profInfo, auth, professionItems, professionOids, registrationNumber, addProfInfo);

			profInfo = ProfessionInfo.GetInstance(profInfo);

			checkValues(profInfo, auth, professionItems, professionOids, registrationNumber, addProfInfo);

			Asn1InputStream aIn = new Asn1InputStream(profInfo.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			profInfo = ProfessionInfo.GetInstance(seq);

			checkValues(profInfo, auth, professionItems, professionOids, registrationNumber, addProfInfo);
		}
Exemplo n.º 51
0
        private void TbsV1CertGenerate()
        {
			V1TbsCertificateGenerator gen = new V1TbsCertificateGenerator();
            DateTime startDate = MakeUtcDateTime(1970, 1, 1, 0, 0, 1);
            DateTime endDate = MakeUtcDateTime(1970, 1, 1, 0, 0, 12);

            gen.SetSerialNumber(new DerInteger(1));

            gen.SetStartDate(new Time(startDate));
            gen.SetEndDate(new Time(endDate));

            gen.SetIssuer(new X509Name("CN=AU,O=Bouncy Castle"));
            gen.SetSubject(new X509Name("CN=AU,O=Bouncy Castle,OU=Test 1"));

            gen.SetSignature(new AlgorithmIdentifier(PkcsObjectIdentifiers.MD5WithRsaEncryption, DerNull.Instance));

            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance),
                new RsaPublicKeyStructure(BigInteger.One, BigInteger.Two));

            gen.SetSubjectPublicKeyInfo(info);

            TbsCertificateStructure tbs = gen.GenerateTbsCertificate();

			if (!Arrays.AreEqual(tbs.GetEncoded(), v1Cert))
            {
                Fail("failed v1 cert generation");
            }

            //
            // read back test
            //
            Asn1InputStream aIn = new Asn1InputStream(v1Cert);
            Asn1Object o = aIn.ReadObject();

            if (!Arrays.AreEqual(o.GetEncoded(), v1Cert))
            {
                Fail("failed v1 cert read back test");
            }
        }
Exemplo n.º 52
0
		private void checkConstruction(
			PersonalData		data,
			NameOrPseudonym		nameOrPseudonym,
			BigInteger			nameDistinguisher,
			DerGeneralizedTime	dateOfBirth,
			DirectoryString		placeOfBirth,
			string				gender,
			DirectoryString		postalAddress)
		{
			checkValues(data, nameOrPseudonym, nameDistinguisher, dateOfBirth, placeOfBirth, gender, postalAddress);

			data = PersonalData.GetInstance(data);

			checkValues(data, nameOrPseudonym, nameDistinguisher, dateOfBirth, placeOfBirth, gender, postalAddress);

			Asn1InputStream aIn = new Asn1InputStream(data.ToAsn1Object().GetEncoded());

			Asn1Sequence seq = (Asn1Sequence) aIn.ReadObject();

			data = PersonalData.GetInstance(seq);

			checkValues(data, nameOrPseudonym, nameDistinguisher, dateOfBirth, placeOfBirth, gender, postalAddress);
		}
Exemplo n.º 53
0
		public override void PerformTest()
		{
			DerApplicationSpecific app = (DerApplicationSpecific)
				Asn1Object.FromByteArray(longTagged);

			app = (DerApplicationSpecific) Asn1Object.FromByteArray(app.GetContents());

			Asn1InputStream aIn = new Asn1InputStream(app.GetContents());

			Asn1TaggedObject tagged = (Asn1TaggedObject) aIn.ReadObject();

			if (tagged.TagNo != 32)
			{
				Fail("unexpected tag value found - not 32");
			}

			tagged = (Asn1TaggedObject) Asn1Object.FromByteArray(tagged.GetEncoded());

			if (tagged.TagNo != 32)
			{
				Fail("unexpected tag value found on recode - not 32");
			}

			tagged = (Asn1TaggedObject) aIn.ReadObject();

			if (tagged.TagNo != 33)
			{
				Fail("unexpected tag value found - not 33");
			}

			tagged = (Asn1TaggedObject) Asn1Object.FromByteArray(tagged.GetEncoded());

			if (tagged.TagNo != 33)
			{
				Fail("unexpected tag value found on recode - not 33");
			}

			aIn = new Asn1InputStream(longAppSpecificTag);

			app = (DerApplicationSpecific)aIn.ReadObject();

			if (app.ApplicationTag != 97)
			{
				Fail("incorrect tag number read");
			}

			app = (DerApplicationSpecific)Asn1Object.FromByteArray(app.GetEncoded());

			if (app.ApplicationTag != 97)
			{
				Fail("incorrect tag number read on recode");
			}

			SecureRandom sr = new SecureRandom();
			for (int i = 0; i < 100; ++i)
			{
				int testTag = (sr.NextInt() & int.MaxValue) >> sr.Next(26);
				app = new DerApplicationSpecific(testTag, new byte[]{ 1 });
				app = (DerApplicationSpecific)Asn1Object.FromByteArray(app.GetEncoded());

				if (app.ApplicationTag != testTag)
				{
					Fail("incorrect tag number read on recode (random test value: " + testTag + ")");
				}
			}
		}
Exemplo n.º 54
0
 public static EcdsaSignature DecodeFromDer(byte[] bytes)
 {
     Asn1InputStream decoder = new Asn1InputStream(bytes);
     DerInteger r, s;
     try
     {
         DerSequence seq = (DerSequence)decoder.ReadObject();
         r = (DerInteger) seq[0];
         s = (DerInteger) seq[1];
     }
     catch (System.InvalidCastException)
     {
         return null;
     }
     finally
     {
         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);
 }
Exemplo n.º 55
0
        private void TbsV2CertListGenerate()
        {
            V2TbsCertListGenerator gen = new V2TbsCertListGenerator();

            gen.SetIssuer(new X509Name("CN=AU,O=Bouncy Castle"));

            gen.AddCrlEntry(new DerInteger(1), new Time(new DateTime(1970, 1, 1, 0, 0, 1)), ReasonFlags.AACompromise);

            gen.SetNextUpdate(new Time(new DateTime(1970, 1, 1, 0, 0, 2)));

            gen.SetThisUpdate(new Time(new DateTime(1970, 1, 1, 0, 0, 0, 500)));

            gen.SetSignature(new AlgorithmIdentifier(PkcsObjectIdentifiers.Sha1WithRsaEncryption, DerNull.Instance));

            //
            // extensions
            //
            IList order = new ArrayList();
            IDictionary extensions = new Hashtable();
            SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                new AlgorithmIdentifier(
                    OiwObjectIdentifiers.ElGamalAlgorithm,
                    new ElGamalParameter(BigInteger.One, BigInteger.Two)),
                new DerInteger(3));

            order.Add(X509Extensions.AuthorityKeyIdentifier);
            order.Add(X509Extensions.IssuerAlternativeName);
            order.Add(X509Extensions.CrlNumber);
            order.Add(X509Extensions.IssuingDistributionPoint);

            extensions.Add(X509Extensions.AuthorityKeyIdentifier, new X509Extension(true, new DerOctetString(CreateAuthorityKeyId(info, new X509Name("CN=AU,O=Bouncy Castle,OU=Test 2"), 2))));
            extensions.Add(X509Extensions.IssuerAlternativeName, new X509Extension(false, new DerOctetString(GeneralNames.GetInstance(new DerSequence(new GeneralName(new X509Name("CN=AU,O=Bouncy Castle,OU=Test 3")))))));
            extensions.Add(X509Extensions.CrlNumber, new X509Extension(false, new DerOctetString(new DerInteger(1))));
            extensions.Add(X509Extensions.IssuingDistributionPoint, new X509Extension(true, new DerOctetString(IssuingDistributionPoint.GetInstance(DerSequence.Empty))));

            X509Extensions ex = new X509Extensions(order, extensions);

            gen.SetExtensions(ex);

            TbsCertificateList tbs = gen.GenerateTbsCertList();

            if (!Arrays.AreEqual(tbs.GetEncoded(), v2CertList))
            {
                Fail("failed v2 cert list generation");
            }

            //
            // read back test
            //
            Asn1InputStream aIn = new Asn1InputStream(v2CertList);
            Asn1Object o = aIn.ReadObject();

            if (!Arrays.AreEqual(o.GetEncoded(), v2CertList))
            {
                Fail("failed v2 cert list read back test");
            }
        }