GetEncoded() public method

Return a Der encoded version of this certificate.
public GetEncoded ( ) : byte[]
return byte[]
Example #1
0
        /// <summary>
        /// https://stackoverflow.com/questions/22230745/generate-a-self-signed-certificate-on-the-fly
        /// </summary>
        /// <param name="subjectName"></param>
        /// <param name="subjectKeyPair"></param>
        /// <param name="resultKeyPair"></param>
        /// <returns></returns>
        public static X509Certificate2 GenerateCaCertificate(
            string subjectName,
            out AsymmetricCipherKeyPair resultKeyPair,
            AsymmetricCipherKeyPair subjectKeyPair = null)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

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

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

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

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

            // Generate a key pair if none was provided
            if (subjectKeyPair == null)
            {
                KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
                RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();
                keyPairGenerator.Init(keyGenerationParameters);
                subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            }

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // Selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded(), string.Empty, X509KeyStorageFlags.EphemeralKeySet);

            resultKeyPair = issuerKeyPair;

            return(x509);
        }
        public static X509Certificate2 CreateCertificate(X509Name subjectDN, DateTime effectiveDate, DateTime expirationDate, AsymmetricCipherKeyPair keyPair, X509Name issuerDN = null,
                                                         AsymmetricKeyParameter signingKey = null, Action <X509V3CertificateGenerator, BigInteger> extend = null)
        {
            if (issuerDN == null)
            {
                issuerDN = subjectDN;
            }

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            BigInteger serialNumber            = CreateSerialNumber();

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(issuerDN);

            // Converted time to Universal Time so that the time set when calling Generate is the same as the time specified
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());

            certGen.SetSubjectDN(subjectDN);
            certGen.SetPublicKey(keyPair.Public);
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            extend?.Invoke(certGen, serialNumber);

            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(signingKey ?? keyPair.Private);

            X509Certificate2 dotNetCert = new X509Certificate2(bcCert.GetEncoded());

            return(dotNetCert);
        }
Example #3
0
        private static void SaveCertificate(X509Certificate bcCertificate)
        {
            var certificate     = new X509Certificate2(bcCertificate.GetEncoded(), Password);
            var certificateData = certificate.Export(X509ContentType.Pkcs12, Password);

            File.WriteAllBytes(@"certificate.pfx", certificateData); //save certificate
        }
        /// <summary>
        /// Create the RSA certificate with a given public key.
        /// </summary>
        /// <returns>The signed certificate.</returns>
        private X509Certificate2 CreateForRSAWithPublicKey(ISignatureFactory signatureFactory = null)
        {
            // Cases locked out by API flow
            Debug.Assert(m_rsaPublicKey != null, "Need a public key for the certificate.");
            if ((IssuerCAKeyCert == null || !IssuerCAKeyCert.HasPrivateKey) && signatureFactory == null)
            {
                throw new NotSupportedException("Need an issuer certificate with a private key or a signature generator.");
            }

            // cert generators
            CreateDefaults();

            var cg = new X509V3CertificateGenerator();

            CreateMandatoryFields(cg);

            // set public key
            AsymmetricKeyParameter subjectPublicKey = X509Utils.GetPublicKeyParameter(m_rsaPublicKey);

            cg.SetPublicKey(subjectPublicKey);

            CreateExtensions(cg, subjectPublicKey);

            // sign certificate by issuer
            if (signatureFactory == null)
            {
                AsymmetricKeyParameter signingKey = X509Utils.GetPrivateKeyParameter(IssuerCAKeyCert);
                signatureFactory = new Asn1SignatureFactory(X509Utils.GetRSAHashAlgorithm(HashAlgorithmName), signingKey);
            }
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create the signed cert
            return(new X509Certificate2(x509.GetEncoded()));
        }
        internal SecureMimeDigitalCertificate(X509Certificate certificate)
        {
            Certificate = certificate;

            var pubkey = certificate.GetPublicKey ();
            if (pubkey is DsaKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.Dsa;
            else if (pubkey is RsaKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.RsaGeneral;
            else if (pubkey is ElGamalKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.ElGamalGeneral;
            else if (pubkey is ECKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.EllipticCurve;
            else if (pubkey is DHKeyParameters)
                PublicKeyAlgorithm = PublicKeyAlgorithm.DiffieHellman;

            var encoded = certificate.GetEncoded ();
            var fingerprint = new StringBuilder ();
            var sha1 = new Sha1Digest ();
            var data = new byte[20];

            sha1.BlockUpdate (encoded, 0, encoded.Length);
            sha1.DoFinal (data, 0);

            for (int i = 0; i < data.Length; i++)
                fingerprint.Append (data[i].ToString ("X2"));

            Fingerprint = fingerprint.ToString ();
        }
Example #6
0
        private static X509Certificate2 CheckSigner(this TimeStampToken tst, Timestamp value)
        {
            BC.X509Certificate signerBc = tst.GetSigner();
            if (signerBc == null)
            {
                trace.TraceEvent(TraceEventType.Warning, 0, "The signer of the time-stamp {0} isn't found", tst.TimeStampInfo.SerialNumber);
                X509CertificateHelper.AddErrorStatus(value.TimestampStatus, null, X509ChainStatusFlags.NotSignatureValid, "Signer not found");
                return(null);
            }

            //check the signature
            try
            {
                tst.Validate(signerBc);
            }
            catch (Exception e)
            {
                trace.TraceEvent(TraceEventType.Warning, 0, "The signature from {1} of the time-stamp {0} is invalid: {2}", tst.TimeStampInfo.SerialNumber, signerBc.SubjectDN, e.Message);
                X509CertificateHelper.AddErrorStatus(value.TimestampStatus, null, X509ChainStatusFlags.NotSignatureValid, "Time-stamp not signed by indicated certificate: " + e.Message);
            }

            //check if the certificate may be used for time-stamping
            IList signerExtKeyUsage = signerBc.GetExtendedKeyUsage();

            if (!signerExtKeyUsage.Contains("1.3.6.1.5.5.7.3.8"))
            {
                trace.TraceEvent(TraceEventType.Warning, 0, "The signer {1} of the time-stamp {0} isn't allowed to sign timestamps", tst.TimeStampInfo.SerialNumber, signerBc.SubjectDN);
                X509CertificateHelper.AddErrorStatus(value.TimestampStatus, null, X509ChainStatusFlags.NotSignatureValid, "The certificate may not be used for timestamps");
            }

            return(new X509Certificate2(signerBc.GetEncoded()));
        }
Example #7
0
        ToDotNetCert(CertPrivateKey key, BcCertificate certificate)
        {
            // merge into X509Certificate2

            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key.KeyPair.Private);

            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                certificate.GetEncoded());

#pragma warning disable CS0618 // Type or member is obsolete
            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());
#pragma warning restore CS0618 // Type or member is obsolete
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

#pragma warning disable CS0618 // Type or member is obsolete
            var rsa = new RsaPrivateKeyStructure(seq);
#pragma warning restore CS0618 // Type or member is obsolete
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return(x509);
        }
Example #8
0
        /// <summary>
        /// Load a certificate from an OpenSSL style file (PEM or DER)
        /// </summary>
        /// <param name="file">The file to load</param>
        /// <returns>The certificate, null if the file wasn't a certificate</returns>
        public static X509Certificate2 LoadCertFromOpenSslFile(string file)
        {
            X509Certificate2 ret = null;

            try
            {
                using (Stream stm = File.OpenRead(file))
                {
                    X509.X509CertificateParser parser = new X509.X509CertificateParser();
                    X509.X509Certificate       cert   = parser.ReadCertificate(stm);

                    if (cert != null)
                    {
                        ret = new X509Certificate2(cert.GetEncoded(), (string)null, X509KeyStorageFlags.Exportable);
                    }
                    else
                    {
                        throw new CryptographicException("Invalid OpenSSL Certificate");
                    }
                }
            }
            catch (CertificateException ex)
            {
                throw new CryptographicException(ex.Message, ex);
            }

            return(ret);
        }
        /// <summary>
        /// Converte um certificado Bouncy.Castle em System.Security
        /// </summary>
        /// <param name="sig"></param>
        /// <returns></returns>
        private static System.Security.Cryptography.X509Certificates.X509Certificate2 convertCertificate(BCX.X509Certificate sig)
        {
            X509Certificate2 certificate = new X509Certificate2();

            certificate.Import(sig.GetEncoded());

            return(certificate);
        }
Example #10
0
        public static X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, out AsymmetricKeyParameter CaPrivateKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name("CN=" + subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

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

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

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

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair    = subjectKeyPair;
            ISignatureFactory       signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            //var dotNetPrivateKey = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);

            X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded())
            {
                FriendlyName = subjectName,
                PrivateKey   = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)subjectKeyPair.Private)
            };

            CaPrivateKey = issuerKeyPair.Private;

            return(x509);
        }
        /// <summary>
        /// Import the specified certificate.
        /// </summary>
        /// <remarks>
        /// Import the specified certificate.
        /// </remarks>
        /// <param name="storeName">The store to import the certificate into.</param>
        /// <param name="certificate">The certificate.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="certificate"/> is <c>null</c>.
        /// </exception>
        public void Import(StoreName storeName, Org.BouncyCastle.X509.X509Certificate certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }

            Import(storeName, new X509Certificate2(certificate.GetEncoded()));
        }
Example #12
0
        /// <summary>
        /// Converts the instance of BouncyCastle X509Certificate class to the DER encoded byte array
        /// </summary>
        /// <param name="cert">Instance of BouncyCastle X509Certificate class</param>
        /// <returns>DER encoded byte array</returns>
        public static byte[] ToDerEncodedByteArray(BCX509.X509Certificate cert)
        {
            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            return(cert.GetEncoded());
        }
        public bool Match(X509Certificate x509Cert)
        {
            try
            {
                if (this.holder.BaseCertificateID != null)
                {
                    bool result = this.holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && this.MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), this.holder.BaseCertificateID.Issuer);
                    return(result);
                }
                if (this.holder.EntityName != null && this.MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), this.holder.EntityName))
                {
                    bool result = true;
                    return(result);
                }
                if (this.holder.ObjectDigestInfo != null)
                {
                    IDigest digest = null;
                    try
                    {
                        digest = DigestUtilities.GetDigest(this.DigestAlgorithm);
                    }
                    catch (Exception)
                    {
                        bool result = false;
                        return(result);
                    }
                    switch (this.DigestedObjectType)
                    {
                    case 0:
                    {
                        byte[] encoded = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(x509Cert.GetPublicKey()).GetEncoded();
                        digest.BlockUpdate(encoded, 0, encoded.Length);
                        break;
                    }

                    case 1:
                    {
                        byte[] encoded2 = x509Cert.GetEncoded();
                        digest.BlockUpdate(encoded2, 0, encoded2.Length);
                        break;
                    }
                    }
                    if (!Arrays.AreEqual(DigestUtilities.DoFinal(digest), this.GetObjectDigest()))
                    {
                        bool result = false;
                        return(result);
                    }
                }
            }
            catch (CertificateEncodingException)
            {
                bool result = false;
                return(result);
            }
            return(false);
        }
Example #14
0
		/// <summary>
		/// Import the specified certificate.
		/// </summary>
		/// <remarks>
		/// Import the specified certificate.
		/// </remarks>
		/// <param name="certificate">The certificate.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="certificate"/> is <c>null</c>.
		/// </exception>
		public override void Import (Org.BouncyCastle.X509.X509Certificate certificate)
		{
			if (certificate == null)
				throw new ArgumentNullException ("certificate");

			var store = new X509Store (StoreName.AddressBook, StoreLocation);

			store.Open (OpenFlags.ReadWrite);
			store.Add (new X509Certificate2 (certificate.GetEncoded ()));
			store.Close ();
		}
Example #15
0
        private static byte[] GeneratePkcs12(
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keys,
            Org.BouncyCastle.X509.X509Certificate cert,
            string friendlyName,
            string password,
            System.Collections.Generic.Dictionary <string, Org.BouncyCastle.X509.X509Certificate> chain)
        {
            System.Collections.Generic.List <X509CertificateEntry> chainCerts =
                new System.Collections.Generic.List <X509CertificateEntry>();

            // Create the PKCS12 store
            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            // Add a Certificate entry
            X509CertificateEntry certEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certEntry); // use DN as the Alias.
                                                                //chainCerts.Add(certEntry);

            // Add chain entries
            System.Collections.Generic.List <byte[]> additionalCertsAsBytes =
                new System.Collections.Generic.List <byte[]>();
            if (chain != null && chain.Count > 0)
            {
                foreach (System.Collections.Generic.KeyValuePair <string, X509Certificate> additionalCert in chain)
                {
                    additionalCertsAsBytes.Add(additionalCert.Value.GetEncoded());
                }
            }

            if (chain != null && chain.Count > 0)
            {
                System.Collections.Generic.IEnumerable <X509Certificate> addicionalCertsAsX09Chain =
                    BuildCertificateChainBC(cert.GetEncoded(), additionalCertsAsBytes);

                foreach (X509Certificate addCertAsX09 in addicionalCertsAsX09Chain)
                {
                    chainCerts.Add(new X509CertificateEntry(addCertAsX09));
                }
            }

            // Add a key entry
            AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(keys.Private);

            // no chain
            store.SetKeyEntry(friendlyName, keyEntry, new X509CertificateEntry[] { certEntry });

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                store.Save(memoryStream, password.ToCharArray(), new Org.BouncyCastle.Security.SecureRandom());
                return(memoryStream.ToArray());
            }
        }
		/**
		 * create with a signer with extra signed/unsigned attributes.
		 */
		public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
		{
			this.key = key;
			this.cert = cert;
			this.digestOID = digestOID;
			this.tsaPolicyOID = tsaPolicyOID;
			this.unsignedAttr = unsignedAttr;

			TspUtil.ValidateCertificate(cert);

			//
			// Add the ESSCertID attribute
			//
			IDictionary signedAttrs;
			if (signedAttr != null)
			{
				signedAttrs = signedAttr.ToDictionary();
			}
			else
			{
				signedAttrs = Platform.CreateHashtable();
			}

			try
			{
				byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

				EssCertID essCertid = new EssCertID(hash);

				Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
					PkcsObjectIdentifiers.IdAASigningCertificate,
					new DerSet(new SigningCertificate(essCertid)));

				signedAttrs[attr.AttrType] = attr;
			}
			catch (CertificateEncodingException e)
			{
				throw new TspException("Exception processing certificate.", e);
			}
			catch (SecurityUtilityException e)
			{
				throw new TspException("Can't find a SHA-1 implementation.", e);
			}

			this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
		}
Example #17
0
        private static X509Certificate2 GenerateX509WithPrivateKey(
            AsymmetricCipherKeyPair keyPair,
            X509Certificate bcCert)
        {
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
            var asn1Seq        = (Asn1Sequence)Asn1Object.FromByteArray(
                privateKeyInfo.ParsePrivateKey().GetDerEncoded());
            var rsaPrivateKeyStruct = RsaPrivateKeyStructure.GetInstance(asn1Seq);
            var rsa      = DotNetUtilities.ToRSA(rsaPrivateKeyStruct);
            var x509Cert = new X509Certificate2(bcCert.GetEncoded());

            return(x509Cert.CopyWithPrivateKey(rsa));
        }
Example #18
0
        public DocsPaVO.documento.SignerInfo GetCertSignersInfo(Org.BouncyCastle.X509.X509Certificate cert1)
        {
            DocsPaVO.documento.SignerInfo retval = new DocsPaVO.documento.SignerInfo();
            retval.SubjectInfo = new DocsPaVO.documento.SubjectInfo();
            string Subject = buildSubject(cert1.SubjectDN);

            ParseCNIPASubjectInfo(ref retval.SubjectInfo, Subject);
            retval.CertificateInfo.IssuerName         = cert1.IssuerDN.ToString();
            retval.CertificateInfo.SerialNumber       = BitConverter.ToString(cert1.SerialNumber.ToByteArray()).Replace("-", "");
            retval.CertificateInfo.SignatureAlgorithm = cert1.SigAlgName;
            retval.CertificateInfo.SubjectName        = Subject;
            retval.CertificateInfo.ValidFromDate      = cert1.NotBefore.ToLocalTime();
            retval.CertificateInfo.ValidToDate        = cert1.NotAfter.ToLocalTime();
            retval.CertificateInfo.ThumbPrint         = BitConverter.ToString(System.Security.Cryptography.SHA1.Create().ComputeHash(cert1.GetEncoded())).Replace("-", "");
            retval.CertificateInfo.X509Certificate    = cert1.GetEncoded();
            // controlla revoca
            X509Certificate2 cert = new X509Certificate2(cert1.GetEncoded());

            retval.CertificateInfo.RevocationStatus            = CheckCertificate(cert);
            retval.CertificateInfo.RevocationStatusDescription = DecodeStatus(retval.CertificateInfo.RevocationStatus);

            return(retval);
        }
Example #19
0
        internal X509Certificate GetCertificateTest(ParametersValidation validationRequest, out StepType stepType, out SoapException exc, out int timeout)
        {
            int special;

            var r = GetCommand <X509Certificate>("GetCertificate", GetCertificate, validationRequest, true, out stepType, out exc, out timeout, out special);

            if (1 == special && null != m_X509CertificateFromUploadPKCS12Alias)
            {
                if (null != r && m_X509CertificateFromUploadPKCS12Alias == r.Alias)
                {
                    r.CertificateContent = m_X509CertificateFromUploadPKCS12;
                }
            }

            if (2 == special && null != m_X509CertificateFromUploadAlias)
            {
                if (null != r && m_X509CertificateFromUploadAlias == r.Alias)
                {
                    r.CertificateContent = m_X509CertificateFromUpload;
                }
            }

            if (3 == special && null != m_X509CertificateFromUploadAlias)
            {
                if (null != r && m_X509CertificateFromUploadAlias == r.Alias)
                {
                    r.CertificateContent = TestCommon.ReadBinary(TestCommon.TLSCertificate1Uri);
                }
            }
            else
            {
                if (3 == special && null != r && "ONVIF_Certificate_Test" == r.Alias)
                {
                    r.CertificateContent = TestCommon.ReadBinary(TestCommon.TLSCertificate1Uri);
                }
            }

            if (4 == special)
            {
                r.CertificateContent = m_X509CertificateSS.GetEncoded();
            }

            if (r != null)
            {
                m_X509CertificateFromGet = r.CertificateContent;
            }

            return(r);
        }
        /// <summary>
        /// Call to request a certificate
        /// </summary>
        /// <param name="csr">Certificate signing request</param>
        /// <param name="effectiveDate">Effective date of certificate</param>
        /// <param name="expirationDate">Expiration date of certificate</param>
        /// <param name="ca">Signing authority</param>
        /// <param name="asn1Set">Extensions</param>
        /// <exception cref="InvalidParameterException">Thrown if <paramref name="ca"/> is null</exception>
        /// <returns>Certificate signed by <paramref name="ca"/></returns>
        public static X509Certificate2 RequestCertificate(Pkcs10CertificationRequest csr, DateTime effectiveDate, DateTime expirationDate, X509Certificate2 ca, Asn1Set asn1Set)
        {
            AsymmetricKeyParameter keyParameter = null;

            if (ca == null)
            {
                throw new InvalidParameterException("ca can not be null");
            }

            keyParameter = TransformRSAPrivateKey((RSACryptoServiceProvider)ca.PrivateKey);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(CreateSerialNumber());
            certGen.SetIssuerDN(new X509Name(ca.Subject));
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());
            certGen.SetSubjectDN(csr.GetCertificationRequestInfo().Subject);
            certGen.SetPublicKey(csr.GetPublicKey());
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            if (asn1Set != null)
            {
                // Iterate through each extension and add it to the certificate
                for (int i = 0; i < asn1Set.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(asn1Set[i]);

                    if (attr != null && attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier extOid in extensions.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions.GetExtension(extOid);

                            certGen.AddExtension(extOid, ext.IsCritical, ext.GetParsedValue());
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate bcCert = certGen.Generate(keyParameter);

            return(new X509Certificate2(bcCert.GetEncoded()));
        }
Example #21
0
        /// <summary>Gets the SHA-256 Thumbprint of the certificate.</summary>
        /// <remarks>
        /// A Thumbprint is a SHA-256 hash of the raw certificate data and is often used
        /// as a unique identifier for a particular certificate in a certificate store.
        /// </remarks>
        /// <returns>The SHA-256 Thumbprint.</returns>
        /// <param name="certificate">The certificate.</param>
        /// <exception cref="T:System.ArgumentNullException">
        /// <paramref name="certificate" /> is <c>null</c>.
        /// </exception>
        public static string GetSha256Thumbprint(this X509Certificate certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            var encoded = certificate.GetEncoded();

            byte[] hashBytes;
            using (var hasher = new SHA256Managed())
            {
                hashBytes = hasher.ComputeHash(encoded);
            }
            string result = BitConverter.ToString(hashBytes)
                            // this will remove all the dashes in between each two characters
                            .Replace("-", string.Empty).ToLower();

            return(result);
        }
Example #22
0
        public static byte[] GenerateRootCertificate(string certName, string Password, out byte[] PlainCer)
        {
            PlainCer = null;

            X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();

            X509Name CN = new X509Name("CN=" + certName);

            RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator();

            keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));

            AsymmetricCipherKeyPair keypair = keypairgen.GenerateKeyPair();

            certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            certGen.SetIssuerDN(CN);
            certGen.SetNotAfter(new DateTime(2099, 1, 1));
            certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            certGen.SetSubjectDN(CN);
            certGen.SetPublicKey(keypair.Public);

            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random);

            Org.BouncyCastle.X509.X509Certificate newCert = certGen.Generate(signatureFactory);

            Pkcs12Store pkcs = new Pkcs12Store();

            pkcs.SetCertificateEntry(certName, new X509CertificateEntry(newCert));
            AsymmetricKeyEntry keyentry = new AsymmetricKeyEntry(keypair.Private);

            pkcs.SetKeyEntry(certName, keyentry, new[] { new X509CertificateEntry(newCert) });
            MemoryStream mem = new MemoryStream();

            pkcs.Save(mem, Password.ToCharArray(), random);
            PlainCer = newCert.GetEncoded();

            return(mem.GetBuffer());
        }
Example #23
0
        /// <summary>
        /// Generate single certificate
        /// </summary>
        /// <param name="hash"></param>
        /// <param name="san"></param>
        /// <returns></returns>
        private X509Certificate2 GenerateCertificate(string hash, out string san)
        {
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetNotBefore(DateTime.UtcNow);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.AddHours(1));

            san = string.Format("{0}.{1}.acme.invalid", hash.Substring(0, 32), hash.Substring(32));
            X509Name subjectDN = new X509Name(string.Format("CN={0}", san));
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false,
                                              new DerSequence(new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, san) }));
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false,
                                              new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth }));
            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true,
                                              new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment));
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(keyPair.Public);

            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", keyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            var flags = X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet;
            var x509  = new X509Certificate2(certificate.GetEncoded(), (string)null, flags);

            x509.FriendlyName = san;
            x509.PrivateKey   = ToDotNetKey((RsaPrivateCrtKeyParameters)keyPair.Private);
            return(x509);
        }
Example #24
0
        public CertificateWithKey Generate(AsymmetricCipherKeyPair signerKeyPair)
        {
            Validate();

            ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, signerKeyPair.Private, random);

            certificateGenerator.SetPublicKey(keyPair.Public);

            X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            certificate.Verify(signerKeyPair.Public);
            var x509 = new X509Certificate2(certificate.GetEncoded());

            var result = new CertificateWithKey
            {
                Certificate = x509,
                KeyPair     = keyPair
            };

            return(result);
        }
Example #25
0
        public void TestCreateKeyStore()
        {
            AsymmetricCipherKeyPair    keyPair    = KeyStoreUtil.GenerateKeyPair();
            RsaPrivateCrtKeyParameters RSAprivKey = (RsaPrivateCrtKeyParameters)keyPair.Private;
            RsaKeyParameters           RSApubKey  = (RsaKeyParameters)keyPair.Public;

            Org.BouncyCastle.X509.X509Certificate cert = KeyStoreUtil.CreateCert("Test", RSApubKey, RSAprivKey);
            Console.WriteLine(cert.ToString());

            string pfxPath = TEST_PFX_PATH;

            if (File.Exists(pfxPath))
            {
                pfxPath += "_old";
                if (File.Exists(pfxPath))
                {
                    File.Delete(pfxPath);
                }
            }
            FileStream fs = new FileStream(pfxPath, FileMode.CreateNew);

            KeyStoreUtil.WritePkcs12(RSAprivKey, cert, TEST_PFX_PASSWORD, fs);
            fs.Close();

            string crtPath = TEST_CRT_PATH;

            if (File.Exists(crtPath))
            {
                crtPath += "_old";
                if (File.Exists(crtPath))
                {
                    File.Delete(crtPath);
                }
            }
            FileStream certFileStream = new FileStream(crtPath, FileMode.CreateNew);

            byte[] encodedCert = cert.GetEncoded();
            certFileStream.Write(encodedCert, 0, encodedCert.Length);
            certFileStream.Close();
        }
        /// <summary>
        /// Renews a <see cref="X509Certificate2"/>. This keeps all but the serial number, effective date, and expiration date./>
        /// </summary>
        /// <param name="certificate">Certificate being renewed</param>
        /// <param name="effectiveDate">New effective date</param>
        /// <param name="expirationDate">New expiration date</param>
        /// <param name="caCertificate">Signing certificate</param>
        /// <returns>New <seealso cref="X509Certificate2"/> renewed from <paramref name="certificate"/></returns>
        public static X509Certificate2 Renew(X509Certificate2 certificate, DateTime effectiveDate, DateTime expirationDate,
                                             X509Certificate2 caCertificate)
        {
            AsymmetricKeyParameter signingKey = caCertificate == null ? null : Certificate.TransformRSAPrivateKey((RSACryptoServiceProvider)caCertificate.PrivateKey);
            var privateKeyParameter           = TransformRSAPrivateKey((RSACryptoServiceProvider)certificate.PrivateKey);
            var bcCert                      = DotNetUtilities.FromX509Certificate(certificate);
            var publicKeyParameter          = bcCert.GetPublicKey();
            AsymmetricCipherKeyPair keyPair = new AsymmetricCipherKeyPair(publicKeyParameter, privateKeyParameter);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
            BigInteger serialNumber            = CreateSerialNumber();

            certGen.SetSerialNumber(serialNumber);
            certGen.SetIssuerDN(bcCert.IssuerDN);

            // Converted time to Universal Time so that the time set when calling Generate is the same as the time specified
            certGen.SetNotBefore(effectiveDate.ToUniversalTime());
            certGen.SetNotAfter(expirationDate.ToUniversalTime());

            certGen.SetSubjectDN(bcCert.SubjectDN);
            certGen.SetPublicKey(keyPair.Public);
            certGen.SetSignatureAlgorithm(SIGNATURE_ALGORITHM);

            // Copy all extensions
            foreach (var ext in certificate.Extensions)
            {
                certGen.CopyAndAddExtension(ext.Oid.Value, ext.Critical, bcCert);
            }

            Org.BouncyCastle.X509.X509Certificate bcNewCert = certGen.Generate(signingKey ?? keyPair.Private);

            X509Certificate2 dotNetCert = new X509Certificate2(bcNewCert.GetEncoded())
            {
                // Restore private key
                PrivateKey = certificate.PrivateKey
            };

            return(dotNetCert);
        }
Example #27
0
 public static void ExportCertificate(BcCertificate cert, EncodingFormat fmt, Stream target)
 {
     if (fmt == EncodingFormat.PEM)
     {
         using (var tw = new StringWriter())
         {
             var pw = new PemWriter(tw);
             pw.WriteObject(cert);
             var pemBytes = Encoding.UTF8.GetBytes(tw.GetStringBuilder().ToString());
             target.Write(pemBytes, 0, pemBytes.Length);
         }
     }
     else if (fmt == EncodingFormat.DER)
     {
         var der = cert.GetEncoded();
         target.Write(der, 0, der.Length);
     }
     else
     {
         throw new NotSupportedException("unsupported encoding format");
     }
 }
Example #28
0
        public byte[] GetEncoded()
        {
            try
            {
                X509CertificateStructure f = null, r = null;

                if (forward != null)
                {
                    f = X509CertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(forward.GetEncoded()));

                    if (f == null)
                    {
                        throw new CertificateEncodingException("unable to get encoding for forward");
                    }
                }

                if (reverse != null)
                {
                    r = X509CertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(reverse.GetEncoded()));

                    if (r == null)
                    {
                        throw new CertificateEncodingException("unable to get encoding for reverse");
                    }
                }

                return(new CertificatePair(f, r).GetDerEncoded());
            }
            catch (Exception e)
            {
                // TODO
//				throw new ExtCertificateEncodingException(e.toString(), e);
                throw new CertificateEncodingException(e.Message, e);
            }
        }
Example #29
0
        public static X509Certificate2 GenerateCACertificate(string subjectName, ref AsymmetricKeyParameter CaPrivateKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

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

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

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

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            CaPrivateKey = issuerKeyPair.Private;

            return(x509);
            //return issuerKeyPair.Private;
        }
Example #30
0
 public bool Add(X509Certificate certificate)
 {
     using (var cert = SecCertificate.Create (certificate.GetEncoded ())) {
         var status = SecCertificateAddToKeychain (cert.Handle, Handle);
         return status == OSStatus.Ok || status == OSStatus.DuplicateItem;
     }
 }
Example #31
0
 private static byte[] ExportCertificate(X509Certificate certificate, AsymmetricCipherKeyPair subjectKeyPair, TCertificateFormat certificateFormat)
 {
     byte[] result = null;
     switch (certificateFormat)
     {
         case TCertificateFormat.NotSet:
             break;
         case TCertificateFormat.PEM:
             using (MemoryStream stream = new MemoryStream())
             {
                 using (StreamWriter writer = new StreamWriter(stream))
                 {
                     Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemWriter = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(writer);
                     if (subjectKeyPair.Private is ECKeyParameters)
                     {
                         ECPrivateKeyParameters priv = (ECPrivateKeyParameters)subjectKeyPair.Private;
                         ECDomainParameters dp = priv.Parameters;
                         int orderBitLength = dp.N.BitLength;
                         Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure ec;
                         Org.BouncyCastle.Asn1.X9.X962Parameters x962;
                         if (priv.PublicKeyParamSet == null)
                         {
                             Org.BouncyCastle.Asn1.X9.X9ECParameters ecP = new Org.BouncyCastle.Asn1.X9.X9ECParameters(dp.Curve, dp.G, dp.N, dp.H, dp.GetSeed());
                             x962 = new Org.BouncyCastle.Asn1.X9.X962Parameters(ecP);
                         }
                         else
                         {
                             x962 = new Org.BouncyCastle.Asn1.X9.X962Parameters(priv.PublicKeyParamSet);
                         }
                         ec = new Org.BouncyCastle.Asn1.Sec.ECPrivateKeyStructure(orderBitLength, priv.D, SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public).PublicKeyData, x962);
                         pemWriter.WriteObject(new Org.BouncyCastle.Utilities.IO.Pem.PemObject("EC PRIVATE KEY", ec.GetEncoded()));
                     }
                     else
                     {
                         pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(subjectKeyPair.Private));
                     }
                     pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(subjectKeyPair.Public));
                     pemWriter.WriteObject(new Org.BouncyCastle.OpenSsl.MiscPemGenerator(certificate));
                     writer.Flush();
                     result = stream.ToArray();
                 }
             }
             break;
         case TCertificateFormat.PFX:
             //Asn1Sequence asn1Sequence = Asn1Sequence.GetInstance(Asn1Object.FromByteArray(certificate.GetEncoded()));
             //asn1Sequence.GetObjects
             //Org.BouncyCastle.Asn1.Pkcs.Pfx pfx = new Org.BouncyCastle.Asn1.Pkcs.Pfx();
             //Org.BouncyCastle.Asn1.Pkcs.PrivateKeyInfo info = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
             //result = pfx.GetEncoded(Asn1Encodable.Der);
             break;
         case TCertificateFormat.CER:
             result = certificate.GetEncoded();
             break;
         default:
             break;
     }
     return result;
 }
Example #32
0
	// Send either ValidatePair or Pair (depending on Action)
	// request to iPhone and return true upon success or false otherwise.
	private bool Pair(PairAction Action)
	{
		#region Preparation of certificates
		X509V3CertificateGenerator DeviceCG = new X509V3CertificateGenerator();
		DeviceCG.SetPublicKey(DevicePublicKey);
		DeviceCG.SetSerialNumber(Org.BouncyCastle.Math.BigInteger.Zero);
		DeviceCG.SetNotBefore(iPhone.RootCertificate.NotBefore);
		DeviceCG.SetNotAfter(iPhone.RootCertificate.NotAfter);
		DeviceCG.SetSignatureAlgorithm("SHA1WithRSAEncryption");
		DeviceCG.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints, true, new Org.BouncyCastle.Asn1.X509.BasicConstraints(false));
		DeviceCertificate = DeviceCG.Generate(iPhone.RootKey.Private);

		// The \n at the end of these certificates is crucial; hung me up for a while.
		string sDeviceCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(DeviceCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bDeviceCertificate = System.Text.Encoding.UTF8.GetBytes(sDeviceCertificate);
		string sHostCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(iPhone.HostCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bHostCertificate = System.Text.Encoding.UTF8.GetBytes(sHostCertificate);
		string sRootCertificate = "-----BEGIN CERTIFICATE-----\n"
									+ Convert.ToBase64String(iPhone.RootCertificate.GetEncoded())
									+ "\n-----END CERTIFICATE-----\n";
		byte[] bRootCertificate = System.Text.Encoding.UTF8.GetBytes(sRootCertificate);
		#endregion

		MemoryStream MS = new MemoryStream();
		XmlWriter XTW = XmlWriter.Create(MS, XWS);
		XTW.WriteStartDocument();
		XTW.WriteDocType("plist", sApplePubID, sAppleSysID, null);
		XTW.WriteStartElement("plist");
		XTW.WriteAttributeString("version", "1.0");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "PairRecord");
		XTW.WriteStartElement("dict");

		XTW.WriteElementString("key", "DeviceCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bDeviceCertificate, 0, bDeviceCertificate.Length);
		XTW.WriteEndElement(); // DeviceCertificate data

		XTW.WriteElementString("key", "HostCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bHostCertificate, 0, bHostCertificate.Length);
		XTW.WriteEndElement(); // HostCertificate data

		XTW.WriteElementString("key", "HostID");
		XTW.WriteElementString("string", iPhone.sHostID);
		XTW.WriteElementString("key", "RootCertificate");
		XTW.WriteStartElement("data");
		XTW.WriteBase64(bRootCertificate, 0, bRootCertificate.Length);
		XTW.WriteEndElement(); // RootCertificate data

		XTW.WriteEndElement(); // inner dict

		XTW.WriteElementString("key", "Request");
		switch (Action)
		{
			case PairAction.Pair:
				XTW.WriteElementString("string", "Pair");
				break;

			case PairAction.ValidatePair:
				XTW.WriteElementString("string", "ValidatePair");
				break;

			case PairAction.Unpair:
				XTW.WriteElementString("string", "Unpair");
				break;
		}

		XTW.WriteEndElement(); // outer dict
		XTW.WriteEndElement(); // plist
		XTW.WriteEndDocument();
		XTW.Flush();

		byte[] bXMLData = MS.GetBuffer();
		XTW.Close(); // Closes MS, too.

		PListSend(bXMLData);
		bXMLData = PListReceive();

		if (!CheckXMLForSuccess(bXMLData))
			return false;

		// Have to validate after pairing for "trusted host status", apparently.
		if (Action == PairAction.Pair)
			return Pair(PairAction.ValidatePair);

		return true;
	}
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID,
			Asn1.Cms.AttributeTable	signedAttr,
			Asn1.Cms.AttributeTable	unsignedAttr)
        {
            this.key = key;
            this.cert = cert;
            this.digestOID = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // add the essCertid
            //
            Hashtable signedAttrs;
            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            IDigest digest;
            try
            {
                digest = DigestUtilities.GetDigest("SHA-1");
            }
            catch (Exception e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            try
            {
                byte[] certEncoded = cert.GetEncoded();
                digest.BlockUpdate(certEncoded, 0, certEncoded.Length);
                byte[] hash = DigestUtilities.DoFinal(digest);

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }
    /// <summary>
    /// Creates a self signed application instance certificate.
    /// </summary>
    /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
    /// <param name="storePath">The store path (syntax depends on storeType).</param>
    /// <param name="password">The password to use to protect the certificate.</param>
    /// <param name="applicationUri">The application uri (created if not specified).</param>
    /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
    /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
    /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
    /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
    /// <param name="startTime">The start time.</param>
    /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
    /// <param name="hashSizeInBits">The hash size in bits.</param>
    /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
    /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
    /// <returns>The certificate with a private key.</returns>
    public static X509Certificate2 CreateCertificate(
        string storeType,
        string storePath,
        string password,
        string applicationUri,
        string applicationName,
        string subjectName,
        IList <String> domainNames,
        ushort keySize,
        DateTime startTime,
        ushort lifetimeInMonths,
        ushort hashSizeInBits,
        bool isCA = false,
        X509Certificate2 issuerCAKeyCert = null,
        byte[] publicKey = null)
    {
        if (issuerCAKeyCert != null)
        {
            if (!issuerCAKeyCert.HasPrivateKey)
            {
                throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
            }
        }

        if (publicKey != null && issuerCAKeyCert == null)
        {
            throw new NotSupportedException("Cannot use a public key without a CA certificate with a private key.");
        }

        // set default values.
        X509Name subjectDN = SetSuitableDefaults(
            ref applicationUri,
            ref applicationName,
            ref subjectName,
            ref domainNames,
            ref keySize,
            ref lifetimeInMonths);

        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            // cert generators
            SecureRandom random           = new SecureRandom(cfrg);
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

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

            // subject and issuer DN
            X509Name issuerDN = null;
            if (issuerCAKeyCert != null)
            {
                issuerDN = new CertificateFactoryX509Name(issuerCAKeyCert.Subject);
            }
            else
            {
                // self signed
                issuerDN = subjectDN;
            }
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // set Private/Public Key
            AsymmetricKeyParameter subjectPublicKey;
            AsymmetricKeyParameter subjectPrivateKey;
            if (publicKey == null)
            {
                var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
                var keyPairGenerator        = new RsaKeyPairGenerator();
                keyPairGenerator.Init(keyGenerationParameters);
                AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();
                subjectPublicKey  = subjectKeyPair.Public;
                subjectPrivateKey = subjectKeyPair.Private;
            }
            else
            {
                // special case, if a cert is signed by CA, the private key of the cert is not needed
                subjectPublicKey  = PublicKeyFactory.CreateKey(publicKey);
                subjectPrivateKey = null;
            }
            cg.SetPublicKey(subjectPublicKey);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                            new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectPublicKey)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier references the issuer cert or itself when self signed
            AsymmetricKeyParameter issuerPublicKey;
            BigInteger             issuerSerialNumber;
            if (issuerCAKeyCert != null)
            {
                issuerPublicKey    = GetPublicKeyParameter(issuerCAKeyCert);
                issuerSerialNumber = GetSerialNumber(issuerCAKeyCert);
            }
            else
            {
                issuerPublicKey    = subjectPublicKey;
                issuerSerialNumber = serialNumber;
            }

            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerPublicKey),
                                                       new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                                             KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                }));

                // subject alternate name
                List <GeneralName> generalNames = new List <GeneralName>();
                generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri));
                generalNames.AddRange(CreateSubjectAlternateNameDomains(domainNames));
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(generalNames.ToArray()));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            AsymmetricKeyParameter signingKey;
            if (issuerCAKeyCert != null)
            {
                // signed by issuer
                signingKey = GetPrivateKeyParameter(issuerCAKeyCert);
            }
            else
            {
                // self signed
                signingKey = subjectPrivateKey;
            }
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(GetRSAHashAlgorithm(hashSizeInBits), signingKey, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // convert to X509Certificate2
            X509Certificate2 certificate = null;
            if (subjectPrivateKey == null)
            {
                // create the cert without the private key
                certificate = new X509Certificate2(x509.GetEncoded());
            }
            else
            {
                // note: this cert has a private key!
                certificate = CreateCertificateWithPrivateKey(x509, null, subjectPrivateKey, random);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath) && !String.IsNullOrEmpty(storeType))
            {
                using (ICertificateStore store = CertificateStoreIdentifier.CreateStore(storeType))
                {
                    if (store == null)
                    {
                        throw new ArgumentException("Invalid store type");
                    }

                    store.Open(storePath);
                    store.Add(certificate, password).Wait();
                    store.Close();
                }
            }

            return(certificate);
        }
    }
		public bool Match(
//			Certificate cert)
			X509Certificate x509Cert)
		{
//			if (!(cert is X509Certificate))
//			{
//				return false;
//			}
//
//			X509Certificate x509Cert = (X509Certificate)cert;

			try
			{
				if (holder.BaseCertificateID != null)
				{
					return holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber)
						&& MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer);
				}

				if (holder.EntityName != null)
				{
					if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName))
					{
						return true;
					}
				}

				if (holder.ObjectDigestInfo != null)
				{
					IDigest md = null;
					try
					{
						md = DigestUtilities.GetDigest(DigestAlgorithm);
					}
					catch (Exception)
					{
						return false;
					}

					switch (DigestedObjectType)
					{
						case ObjectDigestInfo.PublicKey:
						{
							// TODO: DSA Dss-parms

							//byte[] b = x509Cert.GetPublicKey().getEncoded();
							// TODO Is this the right way to encode?
							byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
								x509Cert.GetPublicKey()).GetEncoded();
							md.BlockUpdate(b, 0, b.Length);
							break;
						}

						case ObjectDigestInfo.PublicKeyCert:
						{
							byte[] b = x509Cert.GetEncoded();
							md.BlockUpdate(b, 0, b.Length);
							break;
						}

						// TODO Default handler?
					}

					// TODO Shouldn't this be the other way around?
					if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest()))
					{
						return false;
					}
				}
			}
			catch (CertificateEncodingException)
			{
				return false;
			}

			return false;
		}
Example #36
0
        public unsafe bool Contains(X509Certificate certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException ("certificate");

            if (disposed)
                throw new ObjectDisposedException ("SecKeychain");

            // Note: we don't have to use an alias attribute, it's just that it might be faster to use it (fewer certificates we have to compare raw data for)
            byte[] alias = Encoding.UTF8.GetBytes (certificate.GetCommonName ());
            IntPtr searchRef, itemRef;
            bool found = false;
            byte[] certData;
            OSStatus status;

            fixed (byte* aliasPtr = alias) {
                SecKeychainAttribute* attrs = stackalloc SecKeychainAttribute [1];
                int n = 0;

                if (alias != null)
                    attrs[n++] = new SecKeychainAttribute (SecItemAttr.Alias, (uint) alias.Length, (IntPtr) aliasPtr);

                SecKeychainAttributeList attrList = new SecKeychainAttributeList (n, (IntPtr) attrs);

                status = SecKeychainSearchCreateFromAttributes (Handle, SecItemClass.Certificate, &attrList, out searchRef);
                if (status != OSStatus.Ok)
                    throw new Exception ("Could not enumerate certificates from the keychain. Error:\n" + GetError (status));

                certData = certificate.GetEncoded ();

                while (!found && SecKeychainSearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) {
                    SecItemClass itemClass = 0;
                    IntPtr data = IntPtr.Zero;
                    uint length = 0;

                    status = SecKeychainItemCopyContent (itemRef, ref itemClass, IntPtr.Zero, ref length, ref data);
                    if (status == OSStatus.Ok) {
                        if (certData.Length == (int) length) {
                            byte[] rawData = new byte[(int) length];

                            Marshal.Copy (data, rawData, 0, (int) length);

                            found = true;
                            for (int i = 0; i < rawData.Length; i++) {
                                if (rawData[i] != certData[i]) {
                                    found = false;
                                    break;
                                }
                            }
                        }

                        SecKeychainItemFreeContent (IntPtr.Zero, data);
                    }

                    CFRelease (itemRef);
                }

                CFRelease (searchRef);
            }

            return found;
        }
Example #37
0
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

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

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

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

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerPrivKey, random);

            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);


            // merge into X509Certificate2
            X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                //throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure     rsa       = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return(x509);
        }
        public bool Match(
//			Certificate cert)
            X509Certificate x509Cert)
        {
//			if (!(cert is X509Certificate))
//			{
//				return false;
//			}
//
//			X509Certificate x509Cert = (X509Certificate)cert;

            try
            {
                if (holder.BaseCertificateID != null)
                {
                    return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) &&
                           MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer));
                }

                if (holder.EntityName != null)
                {
                    if (MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName))
                    {
                        return(true);
                    }
                }

                if (holder.ObjectDigestInfo != null)
                {
                    IDigest md = null;
                    try
                    {
                        md = DigestUtilities.GetDigest(DigestAlgorithm);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }

                    switch (DigestedObjectType)
                    {
                    case ObjectDigestInfo.PublicKey:
                    {
                        // TODO: DSA Dss-parms

                        //byte[] b = x509Cert.GetPublicKey().getEncoded();
                        // TODO Is this the right way to encode?
                        byte[] b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(
                            x509Cert.GetPublicKey()).GetEncoded();
                        md.BlockUpdate(b, 0, b.Length);
                        break;
                    }

                    case ObjectDigestInfo.PublicKeyCert:
                    {
                        byte[] b = x509Cert.GetEncoded();
                        md.BlockUpdate(b, 0, b.Length);
                        break;
                    }

                        // TODO Default handler?
                    }

                    // TODO Shouldn't this be the other way around?
                    if (!Arrays.AreEqual(DigestUtilities.DoFinal(md), GetObjectDigest()))
                    {
                        return(false);
                    }
                }
            }
            catch (CertificateEncodingException)
            {
                return(false);
            }

            return(false);
        }
		public static SystemX509.X509Certificate ToX509Certificate(
			X509Certificate x509Cert)
		{
			return new SystemX509.X509Certificate(x509Cert.GetEncoded());
		}
Example #40
0
		/**
		 * Validate the time stamp token.
		 * <p>
		 * To be valid the token must be signed by the passed in certificate and
		 * the certificate must be the one referred to by the SigningCertificate
		 * attribute included in the hashed attributes of the token. The
		 * certificate must also have the ExtendedKeyUsageExtension with only
		 * KeyPurposeID.IdKPTimeStamping and have been valid at the time the
		 * timestamp was created.
		 * </p>
		 * <p>
		 * A successful call to validate means all the above are true.
		 * </p>
		 */
		public void Validate(
			X509Certificate cert)
		{
			try
			{
				byte[] hash = DigestUtilities.CalculateDigest(
					certID.GetHashAlgorithm(), cert.GetEncoded());

				if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), hash))
				{
					throw new TspValidationException("certificate hash does not match certID hash.");
				}

				if (certID.IssuerSerial != null)
				{
					if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
					{
						throw new TspValidationException("certificate serial number does not match certID for signature.");
					}

					GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
					X509Name principal = PrincipalUtilities.GetIssuerX509Principal(cert);
					bool found = false;

					for (int i = 0; i != names.Length; i++)
					{
						if (names[i].TagNo == 4
							&& X509Name.GetInstance(names[i].Name).Equivalent(principal))
						{
							found = true;
							break;
						}
					}

					if (!found)
					{
						throw new TspValidationException("certificate name does not match certID for signature. ");
					}
				}

				TspUtil.ValidateCertificate(cert);

				cert.CheckValidity(tstInfo.GenTime);

				if (!tsaSignerInfo.Verify(cert))
				{
					throw new TspValidationException("signature not created by certificate.");
				}
			}
			catch (CmsException e)
			{
				if (e.InnerException != null)
				{
					throw new TspException(e.Message, e.InnerException);
				}

				throw new TspException("CMS exception: " + e, e);
			}
			catch (CertificateEncodingException e)
			{
				throw new TspException("problem processing certificate: " + e, e);
			}
			catch (SecurityUtilityException e)
			{
				throw new TspException("cannot find algorithm: " + e.Message, e);
			}
		}
Example #41
0
        public bool Add(X509Certificate certificate)
        {
            if (Contains (certificate))
                return true;

            using (var cert = SecCertificate.Create (certificate.GetEncoded ())) {
                return SecCertificateAddToKeychain (cert.Handle, Handle) == OSStatus.Ok;
            }
        }
Example #42
0
		/**
		 * Return a DERObject containing the encoded certificate.
		 *
		 * @param cert the X509Certificate object to be encoded
		 *
		 * @return the DERObject
		 **/
		private Asn1Object ToAsn1Object(
			X509Certificate cert)
		{
			try
			{
				return Asn1Object.FromByteArray(cert.GetEncoded());
			}
			catch (Exception e)
			{
				throw new CertificateEncodingException("Exception while encoding certificate", e);
			}
		}