예제 #1
0
		/**
		* Constructor from Asn1Sequence.
		* <p/>
		* The sequence is of type CertificatePair:
		* <p/>
		* <pre>
		*       CertificatePair ::= SEQUENCE {
		*         forward		[0]	Certificate OPTIONAL,
		*         reverse		[1]	Certificate OPTIONAL,
		*         -- at least one of the pair shall be present -- }
		* </pre>
		*
		* @param seq The ASN.1 sequence.
		*/
		private CertificatePair(
			Asn1Sequence seq)
		{
			if (seq.Count != 1 && seq.Count != 2)
			{
				throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
			}

			foreach (object obj in seq)
			{
				Asn1TaggedObject o = Asn1TaggedObject.GetInstance(obj);
				if (o.TagNo == 0)
				{
					forward = X509CertificateStructure.GetInstance(o, true);
				}
				else if (o.TagNo == 1)
				{
					reverse = X509CertificateStructure.GetInstance(o, true);
				}
				else
				{
					throw new ArgumentException("Bad tag number: " + o.TagNo);
				}
			}
		}
예제 #2
0
        public Certificate(X509CertificateStructure[] certificateList)
        {
            if (certificateList == null)
                throw new ArgumentNullException("certificateList");

            this.mCertificateList = certificateList;
        }
예제 #3
0
        public CmpCertificate(X509CertificateStructure x509v3PKCert)
        {
            if (x509v3PKCert.Version != 3)
                throw new ArgumentException("only version 3 certificates allowed", "x509v3PKCert");

            this.x509v3PKCert = x509v3PKCert;
        }
예제 #4
0
 internal CertificateSubject(X509CertificateStructure cert)
 {
     IList ids = cert.Subject.GetOidList();
     IList values = cert.Subject.GetValueList();
     for (int index = 0; index < ids.Count; index++)
     {
         if (X509Name.CN.Equals(ids[index]))
         {
             CommonName = (string)values[index];
         }
         else if (X509Name.O.Equals(ids[index]))
         {
             Organistion = (string)values[index];
         }
         else if (X509Name.OU.Equals(ids[index]))
         {
             OrganistionUnit = (string)values[index];
         }
         else if (X509Name.L.Equals(ids[index]))
         {
             Location = (string)values[index];
         }
         else if (X509Name.ST.Equals(ids[index]))
         {
             State = (string)values[index];
         }
         else if (X509Name.C.Equals(ids[index]))
         {
             Country = (string)values[index];
         }
     }
 }    
예제 #5
0
		/**
		* Parse the ServerCertificate message.
		*
		* @param inStr 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)
		{
			int left = TlsUtilities.ReadUint24(inStr);
			if (left == 0)
			{
				return EmptyChain;
			}
			IList tmp = Platform.CreateArrayList();
			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);
				Asn1Object o = Asn1Object.FromStream(bis);
				tmp.Add(X509CertificateStructure.GetInstance(o));
				if (bis.Position < bis.Length)
				{
					throw new ArgumentException("Sorry, there is garbage data left after the certificate");
				}
			}
            X509CertificateStructure[] certs = new X509CertificateStructure[tmp.Count];
            for (int i = 0; i < tmp.Count; ++i)
            {
                certs[i] = (X509CertificateStructure)tmp[i];
            }
			return new Certificate(certs);
		}
예제 #6
0
        public static (Org.BouncyCastle.Crypto.Tls.Certificate crtificate, AsymmetricKeyParameter privateKey) CreateSelfSignedTlsCert(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivateKey)
        {
            const int keyStrength = DEFAULT_KEY_SIZE;

            if (issuerPrivateKey == null)
            {
                issuerPrivateKey = CreatePrivateKeyResource(issuerName);
            }

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivateKey, random);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.DnsName, "localhost"), new GeneralName(GeneralName.DnsName, "127.0.0.1") }));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(new List <DerObjectIdentifier>()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.1")
            }));

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(70);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // self sign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            var chain          = new Org.BouncyCastle.Asn1.X509.X509CertificateStructure[] { X509CertificateStructure.GetInstance(certificate.GetEncoded()) };
            var tlsCertificate = new Org.BouncyCastle.Crypto.Tls.Certificate(chain);

            return(tlsCertificate, subjectKeyPair.Private);
        }
		public X509CertificateStructure[] GetCertificates()
		{
			X509CertificateStructure[] result = new X509CertificateStructure[certificates.Count];
			for (int i = 0; i < certificates.Count; ++i)
			{
				result[i] = X509CertificateStructure.GetInstance(certificates[i]);
			}
			return result;
		}
예제 #8
0
 public static Certificate LoadCertificateChain(string[] resources)
 {
     Org.BouncyCastle.Asn1.X509.X509CertificateStructure[]
     chain = new Org.BouncyCastle.Asn1.X509.X509CertificateStructure[resources.Length];
     for (int i = 0; i < resources.Length; ++i)
     {
         chain[i] = LoadCertificateResource(resources[i]);
     }
     return(new Certificate(chain));
 }
예제 #9
0
        public static Certificate LoadCertificateChain(X509Certificate2[] certificates)
        {
            var chain = new Org.BouncyCastle.Asn1.X509.X509CertificateStructure[certificates.Length];

            for (int i = 0; i < certificates.Length; i++)
            {
                chain[i] = LoadCertificateResource(certificates[i]);
            }

            return(new Certificate(chain));
        }
        public X509Certificate(
			X509CertificateStructure c)
        {
            this.c = c;

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));

                if (str != null)
                {
                    basicConstraints = BasicConstraints.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct BasicConstraints: " + e);
            }

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));

                if (str != null)
                {
                    DerBitString bits = DerBitString.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));

                    byte[] bytes = bits.GetBytes();
                    int length = (bytes.Length * 8) - bits.PadBits;

                    keyUsage = new bool[(length < 9) ? 9 : length];

                    for (int i = 0; i != length; i++)
                    {
            //						keyUsage[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
                        keyUsage[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
                    }
                }
                else
                {
                    keyUsage = null;
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct KeyUsage: " + e);
            }
        }
예제 #11
0
        internal static string Fingerprint(X509CertificateStructure c)
        {
            byte[] der = c.GetEncoded();
            byte[] sha1 = Sha256DigestOf(der);
            byte[] hexBytes = Hex.Encode(sha1);
            string hex = Encoding.ASCII.GetString(hexBytes).ToUpper(CultureInfo.InvariantCulture);

            StringBuilder fp = new StringBuilder();
            int i = 0;
            fp.Append(hex.Substring(i, 2));
            while ((i += 2) < hex.Length)
            {
                fp.Append(':');
                fp.Append(hex.Substring(i, 2));
            }
            return fp.ToString();
        }
예제 #12
0
        public static RTCDtlsFingerprint Fingerprint(string hashAlgorithm, Org.BouncyCastle.Asn1.X509.X509CertificateStructure c)
        {
            if (!IsHashSupported(hashAlgorithm))
            {
                throw new ApplicationException($"Hash algorithm {hashAlgorithm} is not supported for DTLS fingerprints.");
            }

            IDigest digestAlgorithm = DigestUtilities.GetDigest(hashAlgorithm.ToString());

            byte[] der  = c.GetEncoded();
            byte[] hash = DigestOf(digestAlgorithm, der);

            return(new RTCDtlsFingerprint
            {
                algorithm = digestAlgorithm.AlgorithmName.ToLower(),
                value = hash.HexStr(':')
            });
        }
		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);
		}
예제 #14
0
 private CertificatePair(Asn1Sequence seq)
 {
     if (seq.Count != 1 && seq.Count != 2)
     {
         throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");
     }
     foreach (object current in seq)
     {
         Asn1TaggedObject instance = Asn1TaggedObject.GetInstance(current);
         if (instance.TagNo == 0)
         {
             this.forward = X509CertificateStructure.GetInstance(instance, true);
         }
         else
         {
             if (instance.TagNo != 1)
             {
                 throw new ArgumentException("Bad tag number: " + instance.TagNo);
             }
             this.reverse = X509CertificateStructure.GetInstance(instance, true);
         }
     }
 }
예제 #15
0
 private CertificatePair(Asn1Sequence seq)
 {
     //IL_0032: Unknown result type (might be due to invalid IL or missing references)
     //IL_0093: Unknown result type (might be due to invalid IL or missing references)
     if (seq.Count != 1 && seq.Count != 2)
     {
         throw new ArgumentException(string.Concat((object)"Bad sequence size: ", (object)seq.Count), "seq");
     }
     global::System.Collections.IEnumerator enumerator = seq.GetEnumerator();
     try
     {
         while (enumerator.MoveNext())
         {
             object           current  = enumerator.get_Current();
             Asn1TaggedObject instance = Asn1TaggedObject.GetInstance(current);
             if (instance.TagNo == 0)
             {
                 forward = X509CertificateStructure.GetInstance(instance, explicitly: true);
                 continue;
             }
             if (instance.TagNo == 1)
             {
                 reverse = X509CertificateStructure.GetInstance(instance, explicitly: true);
                 continue;
             }
             throw new ArgumentException(string.Concat((object)"Bad tag number: ", (object)instance.TagNo));
         }
     }
     finally
     {
         global::System.IDisposable disposable = enumerator as global::System.IDisposable;
         if (disposable != null)
         {
             disposable.Dispose();
         }
     }
 }
 protected virtual X509Certificate CreateX509Certificate(
     X509CertificateStructure c)
 {
     return new X509Certificate(c);
 }
예제 #17
0
        /**
        * Private constructure from an cert array.
        *
        * @param certs The certs the chain should contain.
        */
        private Certificate(
			X509CertificateStructure[] certs)
        {
            this.certs = certs;
        }
예제 #18
0
        /**
         * Parse a {@link Certificate} from a {@link Stream}.
         *
         * @param input the {@link Stream} to parse from.
         * @return a {@link Certificate} object.
         * @throws IOException
         */
        public static Certificate Parse(Stream input)
        {
            int totalLength = TlsUtilities.ReadUint24(input);
            if (totalLength == 0)
            {
                return EmptyChain;
            }

            byte[] certListData = TlsUtilities.ReadFully(totalLength, input);

            MemoryStream buf = new MemoryStream(certListData, false);

            IList certificate_list = Platform.CreateArrayList();
            while (buf.Position < buf.Length)
            {
                byte[] derEncoding = TlsUtilities.ReadOpaque24(buf);
                Asn1Object asn1Cert = TlsUtilities.ReadDerObject(derEncoding);
                certificate_list.Add(X509CertificateStructure.GetInstance(asn1Cert));
            }

            X509CertificateStructure[] certificateList = new X509CertificateStructure[certificate_list.Count];
            for (int i = 0; i < certificate_list.Count; ++i)
            {
                certificateList[i] = (X509CertificateStructure)certificate_list[i];
            }
            return new Certificate(certificateList);
        }
예제 #19
0
 public CertificatePair(X509CertificateStructure forward, X509CertificateStructure reverse)
 {
     this.forward = forward;
     this.reverse = reverse;
 }
예제 #20
0
 private static X509CertificateStructure[] CopyCertList(X509CertificateStructure[] orig)
 {
     return (X509CertificateStructure[])orig.Clone();
 }
예제 #21
0
 public CscaMasterList(
     X509CertificateStructure[] certStructs)
 {
     certList = CopyCertList(certStructs);
 }
예제 #22
0
 public X509TestPublicKeyCertificate(X509CertificateStructure in_Cert)
     : base(in_Cert)
 {
 }
예제 #23
0
 public static X509CertificateStructure GetInstance(Asn1TaggedObject obj, bool explicitly)
 {
     return(X509CertificateStructure.GetInstance(Asn1Sequence.GetInstance(obj, explicitly)));
 }
        protected virtual X509CertificateStructure CorruptCertificateSignature(X509CertificateStructure cert)
        {
            Asn1EncodableVector v = new Asn1EncodableVector();
            v.Add(cert.TbsCertificate);
            v.Add(cert.SignatureAlgorithm);
            v.Add(CorruptBitString(cert.Signature));

            return X509CertificateStructure.GetInstance(new DerSequence(v));
        }
예제 #25
0
		/// <exception cref="System.IO.IOException"></exception>
        //private IDictionary<DerObjectIdentifier, Asn1Encodable> ExtendUnsignedAttributes(IDictionary
        //    <DerObjectIdentifier, Asn1Encodable> unsignedAttrs, X509Certificate signingCertificate
        //    , DateTime signingDate, CertificateSource optionalCertificateSource)
        private IDictionary ExtendUnsignedAttributes(IDictionary unsignedAttrs
            , X509Certificate signingCertificate, DateTime signingDate
            , CertificateSource optionalCertificateSource)
		{
			ValidationContext validationContext = certificateVerifier.ValidateCertificate(signingCertificate
				, signingDate, optionalCertificateSource, null, null);
			try
			{
				IList<X509CertificateStructure> certificateValues = new AList<X509CertificateStructure
					>();
				AList<CertificateList> crlValues = new AList<CertificateList>();
				AList<BasicOcspResponse> ocspValues = new AList<BasicOcspResponse>();
				foreach (CertificateAndContext c in validationContext.GetNeededCertificates())
				{
					if (!c.Equals(signingCertificate))
					{
                        certificateValues.AddItem(X509CertificateStructure.GetInstance(((Asn1Sequence)Asn1Object.FromByteArray
                            (c.GetCertificate().GetEncoded()))));
					}
				}
				foreach (X509Crl relatedcrl in validationContext.GetNeededCRL())
				{                    
					crlValues.AddItem(CertificateList.GetInstance((Asn1Sequence)Asn1Object.FromByteArray(((X509Crl
						)relatedcrl).GetEncoded())));
				}
				foreach (BasicOcspResp relatedocspresp in validationContext.GetNeededOCSPResp())
				{                    
					ocspValues.AddItem((BasicOcspResponse.GetInstance((Asn1Sequence)Asn1Object.FromByteArray(
						relatedocspresp.GetEncoded()))));
				}
				CertificateList[] crlValuesArray = new CertificateList[crlValues.Count];
				BasicOcspResponse[] ocspValuesArray = new BasicOcspResponse[ocspValues.Count];
				RevocationValues revocationValues = new RevocationValues(Sharpen.Collections.ToArray
					(crlValues, crlValuesArray), Sharpen.Collections.ToArray(ocspValues, ocspValuesArray
					), null);
				//unsignedAttrs.Put(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new Attribute
                unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new BcCms.Attribute
					(PkcsObjectIdentifiers.IdAAEtsRevocationValues, new DerSet(revocationValues))
					);
				X509CertificateStructure[] certValuesArray = new X509CertificateStructure[certificateValues
					.Count];
				//unsignedAttrs.Put(PkcsObjectIdentifiers.IdAAEtsCertValues, new Attribute(PkcsObjectIdentifiers.IdAAEtsCertValues, new DerSet(new DerSequence(Sharpen.Collections.ToArray(certificateValues
                unsignedAttrs.Add(PkcsObjectIdentifiers.IdAAEtsCertValues, new BcCms.Attribute(PkcsObjectIdentifiers.IdAAEtsCertValues, new DerSet(new DerSequence(Sharpen.Collections.ToArray(certificateValues
					, certValuesArray)))));
			}
			catch (CertificateEncodingException e)
			{
				throw new RuntimeException(e);
			}
			catch (CrlException e)
			{
				throw new RuntimeException(e);
			}
			return unsignedAttrs;
		}
		private void checkValues(
			RequestedCertificate		requested,
			RequestedCertificate.Choice	type,
			byte[]						certOctets,
			X509CertificateStructure	cert)
		{
			checkMandatoryField("certType", (int) type, (int) requested.Type);

			if (requested.Type == RequestedCertificate.Choice.Certificate)
			{
				checkMandatoryField("certificate", cert.GetEncoded(), requested.GetCertificateBytes());
			}
			else
			{
				checkMandatoryField("certificateOctets", certOctets, requested.GetCertificateBytes());
			}
		}
예제 #27
0
		/// <summary>
		/// Create an System.Security.Cryptography.X509Certificate from an X509Certificate Structure.
		/// </summary>
		/// <param name="x509Struct"></param>
		/// <returns>A System.Security.Cryptography.X509Certificate.</returns>
		public static SystemX509.X509Certificate ToX509Certificate(
			X509CertificateStructure x509Struct)
		{
			return new SystemX509.X509Certificate(x509Struct.GetDerEncoded());
		}
예제 #28
0
		private void ValidateKeyUsage(X509CertificateStructure c, int keyUsageBits)
		{
			X509Extensions exts = c.TbsCertificate.Extensions;
			if (exts != null)
			{
				X509Extension ext = exts.GetExtension(X509Extensions.KeyUsage);
				if (ext != null)
				{
					DerBitString ku = KeyUsage.GetInstance(ext);
					int bits = ku.GetBytes()[0];
					if ((bits & keyUsageBits) != keyUsageBits)
					{
						handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_certificate_unknown);
					}
				}
			}
		}
		/**
		* Constructor from a given details.
		* <p/>
		* Only one parameter can be given. All other must be <code>null</code>.
		*
		* @param certificate Given as Certificate
		*/
		public RequestedCertificate(
			X509CertificateStructure certificate)
		{
			this.cert = certificate;
		}
예제 #30
0
		/**
		* Private constructor from a cert array.
		*
		* @param certs The certs the chain should contain.
		*/
		public Certificate(X509CertificateStructure[] certs)
		{
			this.certs = certs;
		}
예제 #31
0
		/**
		* Constructor from a given details.
		*
		* @param forward Certificates issued to this CA.
		* @param reverse Certificates issued by this CA to other CAs.
		*/
		public CertificatePair(
			X509CertificateStructure	forward,
			X509CertificateStructure	reverse)
		{
			this.forward = forward;
			this.reverse = reverse;
		}
예제 #32
0
		/// <summary>Return true.</summary>
		public bool IsValid(
			X509CertificateStructure[] certs)
		{
			return true;
		}
 internal static void ValidateKeyUsage(X509CertificateStructure c, int keyUsageBits)
 {
     X509Extensions exts = c.TbsCertificate.Extensions;
     if (exts != null)
     {
         X509Extension ext = exts.GetExtension(X509Extensions.KeyUsage);
         if (ext != null)
         {
             DerBitString ku = KeyUsage.GetInstance(ext);
             int bits = ku.GetBytes()[0];
             if ((bits & keyUsageBits) != keyUsageBits)
             {
                 throw new TlsFatalAlert(AlertDescription.certificate_unknown);
             }
         }
     }
 }
예제 #34
0
		/**
		* Private constructor from a cert array.
		*
		* @param certs The certs the chain should contain.
		*/
		public Certificate(X509CertificateStructure[] certs)
		{
			if (certs == null)
				throw new ArgumentNullException("certs");

			this.certs = certs;
		}
예제 #35
0
 internal static Certificate LoadCertificateChain(string[] resources)
 {
     X509CertificateStructure[] chain = new X509CertificateStructure[resources.Length];
     for (int i = 0; i < resources.Length; ++i)
     {
         chain[i] = LoadCertificateResource(resources[i]);
     }
     return new Certificate(chain);
 }
예제 #36
0
		/// <summary>Return true.</summary>
		public bool IsValid(Uri targetUri, X509CertificateStructure[] certs)
		{
			return true;
		}