An Object representing an X509 Certificate. Has static methods for loading Certificates encoded in many forms that return X509Certificate Objects.
Inheritance: X509ExtensionBase
 // Certificate Revocation Lists
 
 /**
  * Gets the URL of the Certificate Revocation List for a Certificate
  * @param certificate   the Certificate
  * @return  the String where you can check if the certificate was revoked
  * @throws CertificateParsingException
  * @throws IOException 
  */
 public static String GetCRLURL(X509Certificate certificate)  {
     try {
         Asn1Object obj = GetExtensionValue(certificate, X509Extensions.CrlDistributionPoints.Id);
         if (obj == null) {
             return null;
         }
         CrlDistPoint dist = CrlDistPoint.GetInstance(obj);
         DistributionPoint[] dists = dist.GetDistributionPoints();
         foreach (DistributionPoint p in dists) {
             DistributionPointName distributionPointName = p.DistributionPointName;
             if (DistributionPointName.FullName != distributionPointName.PointType) {
                 continue;
             }
             GeneralNames generalNames = (GeneralNames)distributionPointName.Name;
             GeneralName[] names = generalNames.GetNames();
             foreach (GeneralName name in names) {
                 if (name.TagNo != GeneralName.UniformResourceIdentifier) {
                     continue;
                 }
                 DerIA5String derStr = DerIA5String.GetInstance((Asn1TaggedObject)name.ToAsn1Object(), false);
                 return derStr.GetString();
             }
         }
     } catch {
     }
     return null;
 }
Example #2
0
	    /**
	     * Verifies if a a valid OCSP response is found for the certificate.
	     * If this method returns false, it doesn't mean the certificate isn't valid.
	     * It means we couldn't verify it against any OCSP response that was available.
	     * @param signCert	the certificate that needs to be checked
	     * @param issuerCert	its issuer
	     * @return a list of <code>VerificationOK</code> objects.
	     * The list will be empty if the certificate couldn't be verified.
	     * @see com.itextpdf.text.pdf.security.RootStoreVerifier#verify(java.security.cert.X509Certificate, java.security.cert.X509Certificate, java.util.Date)
	     */
	    override public List<VerificationOK> Verify(X509Certificate signCert, X509Certificate issuerCert, DateTime signDate) {
		    List<VerificationOK> result = new List<VerificationOK>();
		    int validOCSPsFound = 0;
		    // first check in the list of OCSP responses that was provided
		    if (ocsps != null) {
			    foreach (BasicOcspResp ocspResp in ocsps) {
				    if (Verify(ocspResp, signCert, issuerCert, signDate))
					    validOCSPsFound++;
			    }
		    }
		    // then check online if allowed
		    bool online = false;
		    if (onlineCheckingAllowed && validOCSPsFound == 0) {
			    if (Verify(GetOcspResponse(signCert, issuerCert), signCert, issuerCert, signDate)) {
				    validOCSPsFound++;
				    online = true;
			    }
		    }
		    // show how many valid OCSP responses were found
		    LOGGER.Info("Valid OCSPs found: " + validOCSPsFound);
		    if (validOCSPsFound > 0)
			    result.Add(new VerificationOK(signCert, this, "Valid OCSPs Found: " + validOCSPsFound + (online ? " (online)" : "")));
		    if (verifier != null)
			    result.AddRange(verifier.Verify(signCert, issuerCert, signDate));
		    // verify using the previous verifier in the chain (if any)
		    return result;
	    }
Example #3
0
 public Crl(X509Certificate issuerCertificate, List<string> cdpAddresses)
 {
     _issuerCertificate = issuerCertificate;
     _cdpAddresses = cdpAddresses;
     _timer = new Timer(UpdateCrl);
     UpdateCrl(null);
 }
Example #4
0
 public static int CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date)
 {
     List<BasicOcspResp> ocsps = new List<BasicOcspResp>();
     if (pkcs7.Ocsp != null)
         ocsps.Add(pkcs7.Ocsp);
     OcspVerifier ocspVerifier = new OcspVerifier(null, ocsps);
     List<VerificationOK> verification =
         ocspVerifier.Verify(signCert, issuerCert, date);
     if (verification.Count == 0)
     {
         List<X509Crl> crls = new List<X509Crl>();
         if (pkcs7.CRLs != null)
             foreach (X509Crl crl in pkcs7.CRLs)
                 crls.Add(crl);
         CrlVerifier crlVerifier = new CrlVerifier(null, crls);
         verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
     }
     if (verification.Count == 0)
     {
         Console.WriteLine("No se pudo verificar estado de revocación del certificado por CRL ni OCSP");
         return CER_STATUS_NOT_VERIFIED;
     }
     else
     {
         foreach (VerificationOK v in verification)
             Console.WriteLine(v);
         return 0;
     }
 }
        public OcspReq Generate(
			string					signingAlgorithm,
			IAsymmetricKeyParameter	privateKey,
			X509Certificate[]		chain)
        {
            return Generate(signingAlgorithm, privateKey, chain, null);
        }
 /**
 * add a signer - no attributes other than the default ones will be
 * provided here.
 *
 * @param key signing key to use
 * @param cert certificate containing corresponding public key
 * @param digestOID digest algorithm OID
 */
 public void AddSigner(
     AsymmetricKeyParameter	privateKey,
     X509Certificate			cert,
     string					digestOID)
 {
     AddSigner(privateKey, cert, GetEncOid(privateKey, digestOID), digestOID);
 }
Example #7
0
 /**
 * Sets the crypto information to sign.
 * @param privKey the private key
 * @param certChain the certificate chain
 * @param crlList the certificate revocation list. It can be <CODE>null</CODE>
 */    
 public void SetSignInfo(ICipherParameters privKey, X509Certificate[] certChain, object[] crlList) {
     pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, PdfName.ADBE_PKCS7_SHA1.Equals(Get(PdfName.SUBFILTER)));
     pkcs.SetExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
     if (PdfName.ADBE_X509_RSA_SHA1.Equals(Get(PdfName.SUBFILTER))) {
         if (certChain.Length > 1) {
             PdfArray arr = new PdfArray();
             for (int ii = 0; ii < certChain.Length; ii++) {
                 arr.Add(new PdfString(certChain[ii].GetEncoded()));
             }
             Put(PdfName.CERT, arr);
         }
         else {
             MemoryStream bout = new MemoryStream();
             for (int k = 0; k < certChain.Length; ++k) {
                 byte[] tmp = certChain[k].GetEncoded();
                 bout.Write(tmp, 0, tmp.Length);
             }
             bout.Close();
             Cert = bout.ToArray();
         }
         Contents = pkcs.GetEncodedPKCS1();
     }
     else
         Contents = pkcs.GetEncodedPKCS7();
     name = PdfPKCS7.GetSubjectFields(pkcs.SigningCertificate).GetField("CN");
     if (name != null)
         Put(PdfName.NAME, new PdfString(name, PdfObject.TEXT_UNICODE));
     pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, PdfName.ADBE_PKCS7_SHA1.Equals(Get(PdfName.SUBFILTER)));
     pkcs.SetExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
 }
Example #8
0
		/**
		 * Validate the passed in certificate as being of the correct type to be used
		 * for time stamping. To be valid it must have an ExtendedKeyUsage extension
		 * which has a key purpose identifier of id-kp-timeStamping.
		 *
		 * @param cert the certificate of interest.
		 * @throws TspValidationException if the certicate fails on one of the check points.
		 */
		public static void ValidateCertificate(
			X509Certificate cert)
		{
			if (cert.Version != 3)
				throw new ArgumentException("Certificate must have an ExtendedKeyUsage extension.");

			Asn1OctetString ext = cert.GetExtensionValue(X509Extensions.ExtendedKeyUsage);
			if (ext == null)
				throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension.");

			if (!cert.GetCriticalExtensionOids().Contains(X509Extensions.ExtendedKeyUsage.Id))
				throw new TspValidationException("Certificate must have an ExtendedKeyUsage extension marked as critical.");

			try
			{
				ExtendedKeyUsage extKey = ExtendedKeyUsage.GetInstance(
					Asn1Object.FromByteArray(ext.GetOctets()));

				if (!extKey.HasKeyPurposeId(KeyPurposeID.IdKPTimeStamping) || extKey.Count != 1)
					throw new TspValidationException("ExtendedKeyUsage not solely time stamping.");
			}
			catch (IOException)
			{
				throw new TspValidationException("cannot process ExtendedKeyUsage extension");
			}
		}
        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 #10
0
        public static void SaveToFile(
            X509Certificate newCert,
            AsymmetricCipherKeyPair kp,
            string FilePath,
            string CertAlias,
            string Password)
        {
            var newStore = new Pkcs12Store();

            var certEntry = new X509CertificateEntry(newCert);

            newStore.SetCertificateEntry(
                CertAlias,
                certEntry
                );

            newStore.SetKeyEntry(
                CertAlias,
                new AsymmetricKeyEntry(kp.Private),
                new[] { certEntry }
                );

            using (var certFile = File.Create(FilePath))
            {
                newStore.Save(
                    certFile,
                    Password.ToCharArray(),
                    new SecureRandom(new CryptoApiRandomGenerator())
                    );
            }
        }
        public static OcspReqAndId CreateOcspRequest(X509Certificate rootCertificate, string serialNumber)
        {
            Asn1OctetString issuerNameHash = CreateIssuerNameHash(rootCertificate);
            Asn1OctetString issuerKeyHash = CreateIssuerKeyHash(rootCertificate);

            return CreateOcspRequest(issuerNameHash, issuerKeyHash, serialNumber);
        }
		static void AssertDefaultValues (CmsRecipient recipient, X509Certificate certificate)
		{
			Assert.AreEqual (certificate, recipient.Certificate);
			Assert.AreEqual (1, recipient.EncryptionAlgorithms.Length);
			Assert.AreEqual (EncryptionAlgorithm.TripleDes, recipient.EncryptionAlgorithms[0]);
			Assert.AreEqual (SubjectIdentifierType.IssuerAndSerialNumber, recipient.RecipientIdentifierType);
		}
Example #13
0
        /// <summary>
        /// Import the specified certificate.
        /// </summary>
        /// <param name="certificate">The certificate.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="certificate"/> is <c>null</c>.
        /// </exception>
        public override void Import(X509Certificate certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException ("certificate");

            certificates.Add (certificate);
        }
Example #14
0
 /// <exception cref="System.IO.IOException"></exception>
 public BasicOcspResp GetOcspResponse(X509Certificate certificate, X509Certificate
      issuerCertificate)
 {
     LOG.Info("find OCSP response");
     try
     {
         foreach (BasicOcspResp basicOCSPResp in GetOCSPResponsesFromSignature())
         {
             CertificateID certId = new CertificateID(CertificateID.HashSha1, issuerCertificate
                 , certificate.SerialNumber);
             foreach (SingleResp singleResp in basicOCSPResp.Responses)
             {
                 if (singleResp.GetCertID().Equals(certId))
                 {
                     LOG.Info("OCSP response found");
                     return basicOCSPResp;
                 }
             }
         }
         OcspNotFound(certificate, issuerCertificate);
         return null;
     }
     catch (OcspException e)
     {
         LOG.Error("OcspException: " + e.Message);
         return null;
     }
 }
 /// <summary>
 /// Initialisiert eine neue Instanz der <see cref="BouncyCastlePkcs7EncryptionHandler"/> Klasse.
 /// </summary>
 /// <param name="senderCertificate">Das X509-Zertifikat des Absenders (PKCS#12)</param>
 /// <param name="receiverCertificate">Das X509-Zertifikat des Empfängers</param>
 /// <param name="oldSenderCertificates">Die abgelaufenen X509-Zertifikate des Absenders</param>
 public BouncyCastlePkcs7EncryptionHandler(Pkcs12Store senderCertificate, X509Certificate receiverCertificate,
     IEnumerable<Pkcs12Store> oldSenderCertificates = null)
 {
     _senderCertificate = senderCertificate;
     _receiverCertificate = receiverCertificate;
     _allSenderCertificates = (oldSenderCertificates ?? new Pkcs12Store[0]).Concat(new[] { senderCertificate }).Reverse().ToList();
 }
Example #16
0
		public virtual bool IsSignedBy(X509Certificate potentialIssuer)
		{
			try
			{
				GetCertificate().Verify(potentialIssuer.GetPublicKey());
				return true;
			}
			catch (InvalidKeyException)
			{
				return false;
			}
			catch (CertificateException)
			{
				return false;
			}
			catch (NoSuchAlgorithmException)
			{
				return false;
			}
			/*catch (NoSuchProviderException e)
			{
				throw new RuntimeException(e);
			}*/
			catch (SignatureException)
			{
				return false;
			}
		}
Example #17
0
 /// <summary>
 /// CustomPdfReader to be able to work with streams.
 /// </summary>
 public CustomPdfReader(Stream isp, X509Certificate certificate, ICipherParameters certificateKey)
 {
     this.certificate = certificate;
     this.certificateKey = certificateKey;
     tokens = new PRTokeniser(new RandomAccessFileOrArray(isp));
     ReadPdf();
 }
        public X509CertificateEntry(
            X509Certificate cert,
            IDictionary     attributes)
			: base(attributes)
        {
            this.cert = cert;
        }
Example #19
0
 public Certificate(CertificateRequest request, CertificateIssuer issuer)
 {
     _subject = request.Dn;
     _subjectPublicKey = request.PublicKey;
     _issuer = issuer.DistinguishedName;
     _cert = Create(request, issuer.Key.PrivateAsymmetricKey);
 }
Example #20
0
 // Certificate Revocation Lists
 
 /**
  * Gets the URL of the Certificate Revocation List for a Certificate
  * @param certificate   the Certificate
  * @return  the String where you can check if the certificate was revoked
  * @throws CertificateParsingException
  * @throws IOException 
  */
 public static String GetCRLURL(X509Certificate certificate)  {
     try {
         Asn1Object obj = GetExtensionValue(certificate, X509Extensions.CrlDistributionPoints.Id);
         if (obj == null) {
             return null;
         }
         CrlDistPoint dist = CrlDistPoint.GetInstance(obj);
         DistributionPoint[] dists = dist.GetDistributionPoints();
         foreach (DistributionPoint p in dists) {
             DistributionPointName distributionPointName = p.DistributionPointName;
             if (DistributionPointName.FullName != distributionPointName.PointType) {
                 continue;
             }
             GeneralNames generalNames = (GeneralNames)distributionPointName.Name;
             GeneralName[] names = generalNames.GetNames();
             foreach (GeneralName name in names) {
                 if (name.TagNo != GeneralName.UniformResourceIdentifier) {
                     continue;
                 }
                 DerIA5String derStr = DerIA5String.GetInstance((Asn1TaggedObject)name.ToAsn1Object(), false);
                 //return derStr.GetString();
                 //jbonilla - El URL del CRL para el BCE está en la tercera posición y solo se puede acceder desde HTTP.
                 string urlCrl = derStr.GetString();
                 if (urlCrl.ToUpperInvariant().StartsWith("HTTP") && urlCrl.ToUpperInvariant().Contains("CRL"))
                     return derStr.GetString();
             }
         }
     } catch {
     }
     return null;
 }
Example #21
0
 public virtual byte[] GetEncoded(X509Certificate checkCert, String url) {
     try {
         if (url == null) {
             if (checkCert == null)
                 return null;
             url = PdfPKCS7.GetCrlUrl(checkCert);
         }
         if (url == null)
             return null;
         HttpWebRequest con = (HttpWebRequest)WebRequest.Create(url);
         HttpWebResponse response = (HttpWebResponse)con.GetResponse();
         if (response.StatusCode != HttpStatusCode.OK)
             throw new IOException(MessageLocalization.GetComposedMessage("invalid.http.response.1", (int)response.StatusCode));
         //Get Response
         Stream inp = response.GetResponseStream();
         byte[] buf = new byte[1024];
         MemoryStream bout = new MemoryStream();
         while (true) {
             int n = inp.Read(buf, 0, buf.Length);
             if (n <= 0)
                 break;
             bout.Write(buf, 0, n);
         }
         inp.Close();
         return bout.ToArray();
     }
     catch (Exception ex) {
         if (LOGGER.IsLogging(Level.ERROR))
             LOGGER.Error("CrlClientImp", ex);
     }
     return null;
 }
        /**
         * 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);
        }
		public X509CertificateEntry(
            X509Certificate	cert,
            Hashtable		attributes)
			: base(attributes)
        {
            this.cert = cert;
        }
		/// <summary>Constructor</summary>
		/// <param name="forward">Certificate from the other CA to this CA.</param>
		/// <param name="reverse">Certificate from this CA to the other CA.</param>
		public X509CertificatePair(
			X509Certificate	forward,
			X509Certificate	reverse)
		{
			this.forward = forward;
			this.reverse = reverse;
		}
Example #25
0
		static void CheckCertificateCanBeUsedForSigning (X509Certificate certificate)
		{
			var flags = certificate.GetKeyUsageFlags ();

			if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
				throw new ArgumentException ("The certificate cannot be used for signing.");
		}
Example #26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RawRegisterResponse"/> class.
 /// </summary>
 /// <param name="userPublicKey">The user public key.</param>
 /// <param name="keyHandle">The key handle.</param>
 /// <param name="attestationCertificate">The attestation certificate.</param>
 /// <param name="signature">The signature.</param>
 public RawRegisterResponse(byte[] userPublicKey, byte[] keyHandle,
                            X509Certificate attestationCertificate, byte[] signature)
 {
     _userPublicKey = userPublicKey;
     _keyHandle = keyHandle;
     _attestationCertificate = attestationCertificate;
     _signature = signature;
 }
		/**
		 * basic creation - only the default attributes will be included here.
		 */
		public TimeStampTokenGenerator(
			AsymmetricKeyParameter	key,
			X509Certificate			cert,
			string					digestOID,
			string					tsaPolicyOID)
			: this(key, cert, digestOID, tsaPolicyOID, null, null)
		{
		}
 /**
 * add a signer - no attributes other than the default ones will be
 * provided here.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 */
 public void AddSigner(
     AsymmetricKeyParameter	privateKey,
     X509Certificate			cert,
     string					digestOID)
 {
     AddSigner(privateKey, cert, digestOID,
         new DefaultSignedAttributeTableGenerator(), null);
 }
 public KeyRegisterResponse(byte[] userPublicKey, byte[] keyHandle, X509Certificate attestationCertificate,
     byte[] signature)
 {
     UserPublicKey = userPublicKey;
     KeyHandle = keyHandle;
     AttestationCertificate = attestationCertificate;
     Signature = signature;
 }
Example #30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.Cryptography.CmsRecipient"/> class.
        /// </summary>
        /// <param name="certificate">The recipient's certificate.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="certificate"/> is <c>null</c>.
        /// </exception>
        public CmsRecipient(X509Certificate certificate)
        {
            if (certificate == null)
                throw new ArgumentNullException ("certificate");

            RecipientIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
            Certificate = certificate;
        }
Example #31
0
        public AsymmetricKeyParameter GenerateCACertificate(string subjectName, string privateKeyFilePassword, string rootsigningCertFileName, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

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

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

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

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

            KeyUsage keyUsage = new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

            // 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
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            System.Security.Cryptography.X509Certificates.X509Certificate2 x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            #region Private Key

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

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(pinfo.ParsePrivateKey().GetDerEncoded());
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure     rsa       = RsaPrivateKeyStructure.GetInstance(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);
            #endregion

            // Add CA certificate to Root store
            AddCertToStore(x509, System.Security.Cryptography.X509Certificates.StoreName.Root, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);

            File.WriteAllBytes(rootsigningCertFileName.Replace(".pfx", ".cer"), x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert));

            // Export Certificate with private key
            File.WriteAllBytes(rootsigningCertFileName, x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, privateKeyFilePassword));

            return(issuerKeyPair.Private);
        }
Example #32
0
 internal static bool CheckIfIssuersMatch(CertificateID certID, X509Certificate issuerCert)
 {
     return(certID.MatchesIssuer(issuerCert));
 }
        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);
        }
 /// <summary>
 /// Import the specified certificate.
 /// </summary>
 /// <remarks>
 /// Imports the specified certificate into the <see cref="StoreName.AddressBook"/> store.
 /// </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)
 {
     Import(StoreName.AddressBook, certificate);
 }
Example #35
0
        private static bool CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date)
        {
            List <BasicOcspResp> ocsps = new List <BasicOcspResp>();

            if (pkcs7.Ocsp != null)
            {
                ocsps.Add(pkcs7.Ocsp);
            }
            OcspVerifier          ocspVerifier = new OcspVerifier(null, ocsps);
            List <VerificationOK> verification =
                ocspVerifier.Verify(signCert, issuerCert, date);

            if (verification.Count == 0)
            {
                List <X509Crl> crls = new List <X509Crl>();
                if (pkcs7.CRLs != null)
                {
                    foreach (X509Crl crl in pkcs7.CRLs)
                    {
                        crls.Add(crl);
                    }
                }

                if (crls.Count > 0)
                {
                    CrlVerifier crlVerifier = new CrlVerifier(null, crls);
                    verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
                }
            }
            if (verification.Count == 0)
            {
                return(false);
            }
            else
            {
                foreach (VerificationOK v in verification)
                {
                    Console.WriteLine(v);
                }
            }

            return(verification.Count > 0);
        }
Example #36
0
 static bool CanSignOcspResponses(X509Certificate ocspCertificate)
 {
     return(ocspCertificate.GetExtendedKeyUsage().Contains(KeyPurposeID.IdKPOcspSigning.Id));
 }
    /// <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));
                for (int i = 0; i < domainNames.Count; i++)
                {
                    int domainType = GeneralName.OtherName;
                    switch (Uri.CheckHostName(domainNames[i]))
                    {
                    case UriHostNameType.Dns: domainType = GeneralName.DnsName; break;

                    case UriHostNameType.IPv4:
                    case UriHostNameType.IPv6: domainType = GeneralName.IPAddress; break;

                    default: continue;
                    }
                    generalNames.Add(new GeneralName(domainType, domainNames[i]));
                }

                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);
                    store.Close();
                }
            }

            return(certificate);
        }
    }
        /// <summary>
        /// Create the RSA certificate as Pfx byte array with a private key.
        /// </summary>
        /// <returns>
        /// Returns the Pfx with certificate and private key.
        /// </returns>
        private byte[] CreatePfxForRSA(string passcode, ISignatureFactory signatureFactory = null)
        {
            // Cases locked out by API flow
            Debug.Assert(m_rsaPublicKey == null, "A public key is not supported for the certificate.");

            if (signatureFactory != null && IssuerCAKeyCert == null)
            {
                throw new NotSupportedException("Need an issuer certificate for a signature generator.");
            }

            if (IssuerCAKeyCert != null &&
                (!IssuerCAKeyCert.HasPrivateKey && signatureFactory == null))
            {
                throw new NotSupportedException("Need an issuer certificate with a private key or a signature generator.");
            }

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

                CreateDefaults(cfrg);

                X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
                CreateMandatoryFields(cg);

                // create Private/Public Keypair
                AsymmetricKeyParameter subjectPublicKey  = null;
                AsymmetricKeyParameter subjectPrivateKey = null;
                using (var rsa = new RSACryptoServiceProvider(m_keySize == 0 ? X509Defaults.RSAKeySize : m_keySize))
                {
                    subjectPublicKey  = X509Utils.GetPublicKeyParameter(rsa);
                    subjectPrivateKey = X509Utils.GetPrivateKeyParameter(rsa);
                }

                cg.SetPublicKey(subjectPublicKey);
                CreateExtensions(cg, subjectPublicKey);

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

                // note: this Pfx has a private key!
                return(X509Utils.CreatePfxWithPrivateKey(x509, null, subjectPrivateKey, passcode, random));
            }
        }
Example #39
0
/*
 *  private void verifyTimestamp(TimeStampToken token, X509CRL crl) throws SignVerificationException, XPathExpressionException {
 *              // Read timestamp signature certificate
 *              X509CertificateHolder signCert = getTimestampSignatureCertificate(token);
 *              if (signCert == null) {
 *                      throw new SignVerificationException("Cannot retrieve timestamp signature certificate (Rule 26).");
 *              }
 *
 *              // Rule 26 - Validity
 *              // Check current certificate validity
 *              if (!signCert.isValidOn(new Date())) {
 *                      throw new SignVerificationException("Timestamp signature certificate is not valid now (Rule 26).");
 *              }
 *
 *              // Check against CRL
 *              X509CRLEntry entry = crl.getRevokedCertificate(signCert.getSerialNumber());
 *              if (entry != null) {
 *                      throw new SignVerificationException("Timestamp signature certificate is revoked (Rule 26).");
 *              }
 *
 *              // Rule 27 - Message imprint
 *              byte[] timestampDigest = token.getTimeStampInfo().getMessageImprintDigest();
 *              String hashAlgorithm = token.getTimeStampInfo().getHashAlgorithm().getAlgorithm().getId();
 *
 *              Element signature = querySelector("//ds:Signature/ds:SignatureValue", "Cannot find element 'ds:SignatureValue' (Rule 27).");
 *              byte[] signatureValue = Base64.decode(signature.getTextContent().getBytes());
 *
 *              MessageDigest messageDigest = null;
 *              try {
 *                      messageDigest = MessageDigest.getInstance(hashAlgorithm, "BC");
 *              } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
 *                      throw new SignVerificationException("Unsupported digest type (Rule 27).");
 *              }
 *
 *              byte[] signatureDigest = messageDigest.digest(signatureValue);
 *              if (!Arrays.equals(timestampDigest, signatureDigest)) {
 *                      throw new SignVerificationException("Timestamp MessageImprint check failure (Rule 27).");
 *              }
 * }*/
        private bool validateTimestamp()
        {
            TimeStampToken      token = null;
            X509Crl             ss    = null;
            XmlNamespaceManager mn    = new XmlNamespaceManager(doc.NameTable);
            X509CrlParser       xx    = new X509CrlParser();

            mn.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#");
            string crlUrl = "http://test.ditec.sk/DTCCACrl/DTCCACrl.crl";

            Org.BouncyCastle.X509.X509Certificate signerCert = null;

            try
            {
                var timestamp = this.doc.SelectSingleNode($"//xades:EncapsulatedTimeStamp", mn);

                var    webClient = new WebClient();
                byte[] crlBytes  = webClient.DownloadData(crlUrl);

                token = new TimeStampToken(new CmsSignedData(Convert.FromBase64String(timestamp.InnerText)));

                ss = xx.ReadCrl(crlBytes);

                if (timestamp == null || crlBytes == null || token == null || ss == null)
                {
                    generalException(new Exception());
                    return(false);
                }

                var store = token.GetCertificates("Collection");

                var certs = new ArrayList(store.GetMatches(null));

                foreach (Org.BouncyCastle.X509.X509Certificate cert in certs)
                {
                    string cerIssuer  = cert.IssuerDN.ToString(true, new Hashtable());
                    string signIssuer = token.SignerID.Issuer.ToString(true, new Hashtable());

                    if (cerIssuer == signIssuer && cert.SerialNumber.Equals(token.SignerID.SerialNumber))
                    {
                        signerCert = cert;
                        if (signerCert == null)
                        {
                            generalException(new Exception());
                            return(false);
                        }
                        break;
                    }
                }
                if (!signerCert.IsValidNow)
                {
                    return(false);
                }

                X509CrlEntry revokeCheck = ss.GetRevokedCertificate(signerCert.SerialNumber);
                if (revokeCheck == null)
                {
                    generalException(new Exception());
                    return(false);
                }
            }
            catch (Exception e)
            {
                generalException(e);
            }


            return(false);
        }
Example #40
0
 internal static void IsSignatureValid(TimeStampToken validator, X509Certificate certStoreX509)
 {
     validator.Validate(certStoreX509);
 }
Example #41
0
        /// <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,
            X509Certificate2 issuerCAKeyCert)
        {
            if (issuerCAKeyCert != null)
            {
                if (!issuerCAKeyCert.HasPrivateKey)
                {
                    throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
                }

                throw new NotSupportedException("Signing with an issuer CA certificate is currently unsupported.");
            }

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

            // cert generators
            SecureRandom random           = new SecureRandom();
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

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

            cg.SetSerialNumber(serialNumber);

            // build name attributes
            var nameOids = new ArrayList();

            nameOids.Add(X509Name.DC);
            nameOids.Add(X509Name.CN);

            var nameValues = new ArrayList();

            nameValues.Add(domainNames[0]);
            nameValues.Add(subjectName);

            // self signed
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

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

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

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

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            cg.SetPublicKey(subjectKeyPair.Public);

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

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

            // Authority Key identifier
            var issuerKeyPair      = subjectKeyPair;
            var issuerSerialNumber = serialNumber;

            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
                                                       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
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false,
                                new GeneralNames(new GeneralName[] {
                    new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri),
                    new GeneralName(GeneralName.DnsName, domainNames[0])
                }));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory((hashSizeInBits < 256) ? "SHA1WITHRSA" : "SHA256WITHRSA", subjectKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create pkcs12 store for cert and private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store            pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = "passcode";
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // merge into X509Certificate2
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);
            }

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

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath))
            {
                ICertificateStore store = null;
                if (storeType == CertificateStoreType.X509Store)
                {
                    store = new X509CertificateStore();
                }
                else if (storeType == CertificateStoreType.Directory)
                {
                    store = new DirectoryCertificateStore();
                }
                else
                {
                    throw new ArgumentException("Invalid store type");
                }

                store.Open(storePath);
                store.Add(certificate);
                store.Close();
                store.Dispose();
            }

            // note: this cert has a private key!
            return(certificate);
        }
Example #42
0
        public System.Security.Cryptography.X509Certificates.X509Certificate2 GenerateSelfSignedCertificate(string certificateName, List <string> subjectAlternateNames, string certificateFileName, string privateKeyFilePassword, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength)
        {
            string subjectName = string.Format("CN={0}", certificateName);

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

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

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

            // original code var issuerDN = issuerName;
            var issuerDN = new X509Name(issuerName);

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

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

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

            KeyUsage keyUsage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

            // Add the “Extended Key Usage” attribute, specifying “server authentication”.
            var usages = new[] { KeyPurposeID.IdKPServerAuth };

            certificateGenerator.AddExtension(
                X509Extensions.ExtendedKeyUsage.Id,
                false,
                new ExtendedKeyUsage(usages));

            /* DNS Name=*.fullyqualified.domainname.com */
            if (subjectAlternateNames.Count <= 1)
            {
                /* the <=1 is for the simple reason of showing an alternate syntax .. */
                foreach (string subjectAlternateName in subjectAlternateNames)
                {
                    GeneralName  altName        = new GeneralName(GeneralName.DnsName, subjectAlternateName);
                    GeneralNames subjectAltName = new GeneralNames(altName);
                    certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);
                }
            }
            else
            {
                //Asn1Encodable[] ansiEncodeSubjectAlternativeNames = new Asn1Encodable[]
                // {
                // //new GeneralName(GeneralName.DnsName, “*.fullyqualified.domainname.com”),
                // new GeneralName(GeneralName.DnsName, “*.fullyqualified.domainname.com”)
                // };

                List <Asn1Encodable> asn1EncodableList = new List <Asn1Encodable>();
                foreach (string subjectAlternateName in subjectAlternateNames)
                {
                    asn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternateName));
                }

                DerSequence subjectAlternativeNamesExtension = new DerSequence(asn1EncodableList.ToArray());
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, subjectAlternativeNamesExtension);
            }

            // 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
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

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

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

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(pinfo.ParsePrivateKey().GetDerEncoded());

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

            RsaPrivateKeyStructure     rsa       = RsaPrivateKeyStructure.GetInstance(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);

            File.WriteAllBytes(certificateFileName.Replace(".pfx", ".cer"), x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert));

            // Export Certificate with private key
            File.WriteAllBytes(certificateFileName, x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, privateKeyFilePassword));

            return(x509);
        }
Example #43
0
        private static MessageReport.Signature InspectSignature(AcroFields fields, String name, SignaturePermissions perms)
        {
            MessageReport.Signature sigInfo = new MessageReport.Signature();

            IList <AcroFields.FieldPosition> fps = fields.GetFieldPositions(name);

            if (fps != null && fps.Count > 0)
            {
                AcroFields.FieldPosition fp = fps[0];
                Rectangle pos = fp.position;
                if (pos.Width == 0 || pos.Height == 0)
                {
                    sigInfo.visible = false;
                }
                else
                {
                    sigInfo.visible = true;
                }
            }

            PdfPKCS7 pkcs7 = VerifySignature(fields, name, ref sigInfo);

            sigInfo.digestAlgorithm     = pkcs7.GetHashAlgorithm();
            sigInfo.encryptionAlgorithm = pkcs7.GetEncryptionAlgorithm();
            sigInfo.isRevocationValid   = pkcs7.IsRevocationValid();


            X509Certificate cert = pkcs7.SigningCertificate;

            sigInfo.signerName = CertificateInfo.GetSubjectFields(cert).GetField("CN");

            if (pkcs7.SignName != null)
            {
                sigInfo.signerName = pkcs7.SignName;
            }

            sigInfo.signDate = pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff");

            if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue))
            {
                sigInfo.isTimestampped = true;
                sigInfo.timestampDate  = pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff");

                TimeStampToken ts = pkcs7.TimeStampToken;
                sigInfo.timestampName = ts.TimeStampInfo.Tsa.ToString();
            }

            sigInfo.signLocation = pkcs7.Location;
            sigInfo.signReason   = pkcs7.Reason;

            PdfDictionary sigDict = fields.GetSignatureDictionary(name);
            PdfString     contact = sigDict.GetAsString(PdfName.CONTACTINFO);

            if (contact != null)
            {
                Console.WriteLine("Contact info: " + contact);
            }
            perms = new SignaturePermissions(sigDict, perms);

            sigInfo.signatureType = (perms.Certification ? "certification" : "approval");


            return(sigInfo);
        }
        /// <summary>
        /// Creates new certificate
        /// </summary>
        /// <returns></returns>
        public static void CreateSelfSignedCertificate(string subjectDirName, DateTime startDate, DateTime endDate, int signatureBits, int keyStrength, string password, string fileName)
        {
            string signatureAlgorithm;

            switch (signatureBits)
            {
            case 160:
                signatureAlgorithm = "SHA1withRSA";
                break;

            case 224:
                signatureAlgorithm = "SHA224withRSA";
                break;

            case 256:
                signatureAlgorithm = "SHA256withRSA";
                break;

            case 384:
                signatureAlgorithm = "SHA384withRSA";
                break;

            case 512:
                signatureAlgorithm = "SHA512withRSA";
                break;

            default:
                throw new ArgumentException("Invalid signature bit size.", "signatureBits");
            }

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

            // Generate public/private keys.
            AsymmetricCipherKeyPair encryptionKeys;

            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

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

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

            certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            certificateGenerator.SetIssuerDN(new X509Name(subjectDirName));
            certificateGenerator.SetSubjectDN(new X509Name(subjectDirName));
            certificateGenerator.SetNotBefore(startDate);
            certificateGenerator.SetNotAfter(endDate);
            certificateGenerator.SetPublicKey(encryptionKeys.Public);

            // self-sign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(encryptionKeys.Private, random);

            Pkcs12Store          store            = new Pkcs12Store();
            string               friendlyName     = certificate.SubjectDN.ToString();
            X509CertificateEntry certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(encryptionKeys.Private), new[] { certificateEntry });

            MemoryStream stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            //Verify that the certificate is valid.
            _ = new X509Certificate2(stream.ToArray(), password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //Write the file.
            File.WriteAllBytes(fileName, stream.ToArray());

            File.WriteAllBytes(Path.ChangeExtension(fileName, ".cer"), certificate.GetEncoded());
        }
 /// <summary>
 /// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate.
 /// </summary>
 /// <remarks>
 /// Updates the known S/MIME capabilities of the client used by the recipient that owns the specified certificate.
 /// </remarks>
 /// <param name="certificate">The certificate.</param>
 /// <param name="algorithms">The encryption algorithm capabilities of the client (in preferred order).</param>
 /// <param name="timestamp">The timestamp.</param>
 protected override void UpdateSecureMimeCapabilities(Org.BouncyCastle.X509.X509Certificate certificate, EncryptionAlgorithm[] algorithms, DateTime timestamp)
 {
     // TODO: implement this - should we add/update the X509Extension for S/MIME Capabilities?
 }
Example #46
0
        public bool validateCerKEYContent(byte[] cer, byte[] key, string password, string rfc)
        {
            try
            {
                if (String.IsNullOrEmpty(password))
                {
                    throw new DigitalSignException(5050, "5051", "Es necesario especificar la contraseña del certificado.", null);
                }

                SecureString secureString = new SecureString();
                secureString.Clear();

                foreach (char c in password)
                {
                    secureString.AppendChar(c);
                }

                RSACryptoServiceProvider lrsa = OpensslKey.DecodeEncryptedPrivateKeyInfo(key, secureString);

                if (lrsa == null)
                {
                    throw new DigitalSignException(5052, "5052", "La constraseña de los certificados proporcionada no es correcta.", null);
                }

                //validate Subject
                X509Certificate2 x509Certificate2 = new X509Certificate2(cer);

                if (!x509Certificate2.Subject.ToLower().Contains(rfc.ToLower()))
                {
                    throw new DigitalSignException(5053, "5053", "El certificado no corresponde con el RFC proporcionado.", null);
                }

                //matches cer and key
                char[] arrayOfChars = password.ToCharArray();
                AsymmetricKeyParameter privateKey = PrivateKeyFactory.DecryptKey(arrayOfChars, key);

                Org.BouncyCastle.X509.X509Certificate bouncyCastleCert = new Org.BouncyCastle.X509.X509Certificate(
                    new X509CertificateParser().ReadCertificate(x509Certificate2.GetRawCertData()).CertificateStructure);

                RsaKeyParameters publicKey = (RsaKeyParameters)bouncyCastleCert.GetPublicKey();
                byte[]           numArray  = new byte[256];
                new SecureRandom().NextBytes(numArray);
                var    signer    = new Signer();
                byte[] signature = signer.Sign(privateKey, numArray);
                var    isMatched = signer.VerifySignature(publicKey, numArray, signature);

                if (!isMatched)
                {
                    throw new DigitalSignException(5054, "5054", "El .CER no corresponde con el .KEY proporcionado.", null);
                }

                //validación de CSD / FIEL
                if (!
                    (KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.DigitalSignature) &&
                     KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.NonRepudiation) &&
                     !KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.DataEncipherment) &&
                     !KeyUsageHasUsage(x509Certificate2, X509KeyUsageFlags.KeyAgreement)
                    ))
                {
                    throw new DigitalSignException(5055, "5055", "El certificado proporcionado debe de ser un CSD válido (No debe de ser FIEL).", null);
                }

                return(true);
            }
            catch (DigitalSignException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new DigitalSignException(109, "109", "El certificado proporcionado no es correcto.", ex);
            }
        }
        /// <summary>
        /// Static method used to create a certificate and return as a .net object
        /// </summary>
        public static X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false, string exportDirectory = null)
        {
            // generate a key pair using RSA
            var generator = new RsaKeyPairGenerator();

            // keys have to be a minimum of 2048 bits for Azure
            generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            AsymmetricCipherKeyPair cerKp = generator.GenerateKeyPair();
            // get a copy of the private key
            AsymmetricKeyParameter privateKey = cerKp.Private;

            // create the CN using the name passed in and create a unique serial number for the cert
            var        certName = new X509Name("CN=" + name);
            BigInteger serialNo = BigInteger.ProbablePrime(120, new Random());

            // start the generator and set CN/DN and serial number and valid period
            var x509Generator = new X509V3CertificateGenerator();

            x509Generator.SetSerialNumber(serialNo);
            x509Generator.SetSubjectDN(certName);
            x509Generator.SetIssuerDN(certName);
            x509Generator.SetNotBefore(start);
            x509Generator.SetNotAfter(end);
            // add the server authentication key usage
            var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment);

            x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object());
            var extendedKeyUsage = new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth });

            x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object());
            // algorithm can only be SHA1 ??
            x509Generator.SetSignatureAlgorithm("sha1WithRSA");

            // Set the key pair
            x509Generator.SetPublicKey(cerKp.Public);
            X509Certificate certificate = x509Generator.Generate(cerKp.Private);

            // export the certificate bytes
            byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, userPassword);

            // build the key parameter and the certificate entry
            var keyEntry = new AsymmetricKeyEntry(privateKey);
            var entry    = new X509CertificateEntry(certificate);
            // build the PKCS#12 store to encapsulate the certificate
            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.Build();
            // create a memorystream to hold the output
            var stream = new MemoryStream(10000);
            // create the individual store and set two entries for cert and key
            var store = new Pkcs12Store();

            store.SetCertificateEntry("Created by Fluent Management", entry);
            store.SetKeyEntry("Created by Fluent Management", keyEntry, new[] { entry });
            store.Save(stream, userPassword.ToCharArray(), new SecureRandom());

            // Create the equivalent C# representation
            var cert = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable);

            // set up the PEM writer too
            if (exportDirectory != null)
            {
                var textWriter = new StringWriter();
                var pemWriter  = new PemWriter(textWriter);
                pemWriter.WriteObject(cerKp.Private, "DESEDE", userPassword.ToCharArray(), new SecureRandom());
                pemWriter.Writer.Flush();
                string privateKeyPem = textWriter.ToString();
                using (var writer = new StreamWriter(Path.Combine(exportDirectory, cert.Thumbprint + ".pem")))
                {
                    writer.WriteLine(privateKeyPem);
                }
                // also export the certs - first the .pfx
                byte[] privateKeyBytes = cert.Export(X509ContentType.Pfx, userPassword);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".pfx"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(privateKeyBytes, 0, privateKeyBytes.Length);
                }
                // also export the certs - then the .cer
                byte[] publicKeyBytes = cert.Export(X509ContentType.Cert);
                using (var writer = new FileStream(Path.Combine(exportDirectory, cert.Thumbprint + ".cer"), FileMode.OpenOrCreate, FileAccess.Write))
                {
                    writer.Write(publicKeyBytes, 0, publicKeyBytes.Length);
                }
            }

            // if specified then this add this certificate to the store
            if (addtoStore)
            {
                AddToMyStore(cert);
            }

            return(cert);
        }
        /// <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);
        }
 /// <summary>
 /// Verifica a validade da assinatura
 /// </summary>
 /// <param name="signer">Certificado da assinatura</param>
 /// <returns></returns>
 private static bool verifySignature(BCX.X509Certificate signer)
 {
     return(validateCertificate(convertCertificate(signer), true));
 }
 /// <summary>
 /// Verifica a validade da assinatura (obsoleta)
 /// </summary>
 /// <param name="pkc">Cadeia de assinaturas</param>
 /// <param name="kall">Lista de certificados</param>
 /// <param name="cal">Data/Hora da assinatura</param>
 /// <returns></returns>
 private static bool verifySignature(BCX.X509Certificate[] pkc, List <BCX.X509Certificate> kall, DateTime cal, BCX.X509Certificate signer)
 {
     Object[] fails = iTextSharp.text.pdf.security.CertificateVerification.VerifyCertificates(pkc, kall, null, cal);
     return(fails == null);
 }
Example #51
0
        public static void Write(string name, string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom            random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

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

            ArrayList nameOids = new ArrayList();

            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();

            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA              rsa       = RSA.Create();
            RSAParameters    rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    rsa.Dispose();
                    throw new CryptographicException("Could not encrypt IoTHub security token using generated public key!");
                }
            }
            rsa.Dispose();

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store            pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = "passcode";
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // Add to X509Store
                using (X509Store store = new X509Store("IoTHub", StoreLocation.CurrentUser))
                {
                    store.Open(OpenFlags.ReadWrite);

                    // remove any existing cert with our name from the store
                    foreach (X509Certificate2 cert in store.Certificates)
                    {
                        if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                        {
                            store.Remove(cert);
                        }
                    }

                    // add new one
                    store.Add(certificate);
                }
            }
        }
Example #52
0
        public static RTCDtlsFingerprint Fingerprint(X509Certificate certificate)
        {
            var certStruct = X509CertificateStructure.GetInstance(certificate.GetEncoded());

            return(Fingerprint(certStruct));
        }
Example #53
0
        public X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, out AsymmetricKeyParameter CaPrivateKey, out byte[] Android)
        {
            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
            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;
            ISignatureFactory       signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerKeyPair.Private, random);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());

            x509.FriendlyName = subjectName;
            CaPrivateKey      = issuerKeyPair.Private;

            // Now do Android...
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
            issuerKeyPair    = subjectKeyPair;
            signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerKeyPair.Private, random);
            Org.BouncyCastle.X509.X509Certificate certificateAndroid = certificateGenerator.Generate(signatureFactory);
            X509Certificate2 x509Android = new X509Certificate2(certificateAndroid.GetEncoded());

            Android = x509Android.Export(X509ContentType.Cert, "1234");

            return(x509);
        }
Example #54
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
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            //Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(issuerPrivKey, random);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);

            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);



            // 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 = ToDotNetKey(rsaparams);
            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return(x509);
        }
Example #55
0
 internal static CertificateID GenerateCertificateId(X509Certificate issuerCert, BigInteger serialNumber, String hashAlgorithm)
 {
     return(new CertificateID(hashAlgorithm, issuerCert, serialNumber));
 }
Example #56
0
        private X509Certificate2[] ValidateCertificateByOCSP(UnsignedProperties unsignedProperties, X509Certificate2 client, X509Certificate2 issuer, IEnumerable <OcspServer> ocspServers, FirmaXadesNet.Crypto.DigestMethod digestMethod, bool addCertificateOcspUrl, bool useNonce)
        {
            bool byKey = false;
            List <OcspServer> finalOcspServers = new List <OcspServer>();

            Org.BouncyCastle.X509.X509Certificate clientCert = client.ToBouncyX509Certificate();
            Org.BouncyCastle.X509.X509Certificate issuerCert = issuer.ToBouncyX509Certificate();

            OcspClient ocsp = new OcspClient();

            if (addCertificateOcspUrl)
            {
                string certOcspUrl = ocsp.GetAuthorityInformationAccessOcspUrl(issuerCert);

                if (!string.IsNullOrEmpty(certOcspUrl))
                {
                    finalOcspServers.Add(new OcspServer(certOcspUrl));
                }
            }

            foreach (var ocspServer in ocspServers)
            {
                finalOcspServers.Add(ocspServer);
            }

            foreach (var ocspServer in finalOcspServers)
            {
                byte[] resp = ocsp.QueryBinary(clientCert, issuerCert, ocspServer.Url, useNonce, ocspServer.RequestorName,
                                               ocspServer.SignCertificate);

                FirmaXadesNet.Clients.CertificateStatus status = ocsp.ProcessOcspResponse(resp, useNonce);

                if (status == FirmaXadesNet.Clients.CertificateStatus.Revoked)
                {
                    throw new Exception("Certificate revoked");
                }
                else if (status == FirmaXadesNet.Clients.CertificateStatus.Good)
                {
                    Org.BouncyCastle.Ocsp.OcspResp r = new OcspResp(resp);
                    byte[]        rEncoded           = r.GetEncoded();
                    BasicOcspResp or = (BasicOcspResp)r.GetResponseObject();

                    string guidOcsp = Guid.NewGuid().ToString();

                    OCSPRef ocspRef = new OCSPRef();
                    ocspRef.OCSPIdentifier.UriAttribute = "#OcspValue" + guidOcsp;
                    DigestUtil.SetCertDigest(rEncoded, digestMethod, ocspRef.CertDigest);

                    ResponderID rpId = or.ResponderId.ToAsn1Object();
                    ocspRef.OCSPIdentifier.ResponderID = GetResponderName(rpId, ref byKey);
                    ocspRef.OCSPIdentifier.ByKey       = byKey;

                    ocspRef.OCSPIdentifier.ProducedAt = or.ProducedAt.ToLocalTime();
                    unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs.OCSPRefs.OCSPRefCollection.Add(ocspRef);

                    OCSPValue ocspValue = new OCSPValue
                    {
                        PkiData = rEncoded,
                        Id      = "OcspValue" + guidOcsp
                    };
                    unsignedProperties.UnsignedSignatureProperties.RevocationValues.OCSPValues.OCSPValueCollection.Add(ocspValue);

                    return((from cert in or.GetCerts()
                            select new X509Certificate2(cert.GetEncoded())).ToArray());
                }
            }

            throw new Exception("The certificate could not be validated");
        }
Example #57
0
        //
        // Summary:
        //     /// Method responsible for generate certificate. ///
        //
        // Parameters:
        //   request:
        //     The request param.
        //
        public CreateCertificateResult Generate(CreateCertificateCommand request)
        {
            AsymmetricKeyParameter caPrivateKey = null;

            var caCert = GenerateCACertificate("CN=MyROOTCA", ref caPrivateKey);


            SecureRandom random = new SecureRandom();

            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(new KeyGenerationParameters(random, 2048));

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            IDictionary issuerAttrs  = FactoryIssuerAttrs();
            IDictionary subjectAttrs = FactorySubjectAttrs(request);

            BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());

            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetIssuerDN(new X509Name(new ArrayList(issuerAttrs.Keys), issuerAttrs));
            certificateGenerator.SetSubjectDN(new X509Name(new ArrayList(subjectAttrs.Keys), subjectAttrs));
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(3));
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true,
                                              new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyAgreement | KeyUsage.NonRepudiation));

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth }));

            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, "SAN"));

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);

            Asn1SignatureFactory signatureFactory =
                new Asn1SignatureFactory(HashType.SHA256WithRSA.ToString(), subjectKeyPair.Private);

            X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            X509CertificateEntry certEntry = new X509CertificateEntry(certificate);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetCertificateEntry(certificate.SubjectDN.ToString(), certEntry);
            store.SetKeyEntry(certificate.SubjectDN + "_key", new AsymmetricKeyEntry(subjectKeyPair.Private),
                              new[] { certEntry });

            MemoryStream p12Stream = new MemoryStream();

            store.Save(p12Stream, request.Pin.ToCharArray(), random);

            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(p12Stream.ToArray(), request.Pin.ToCharArray());

            X509Certificate2 x509Certificate2 =
                new X509Certificate2(pfx, request.Pin, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);


            CreateCrl(caCert, caPrivateKey, serialNumber);

            return(FactoryResponse(x509Certificate2));
        }
Example #58
0
 internal static bool IsSignatureValid(BasicOcspResp validator, X509Certificate certStoreX509)
 {
     return(validator.Verify(certStoreX509.GetPublicKey()));
 }
Example #59
0
        public async Task ValidateMergeCertificate()
        {
            string serverCertificateName = Recording.GenerateId();

            // Generate the request.
            CertificatePolicy policy = new CertificatePolicy(WellKnownIssuerNames.Unknown, "CN=Azure SDK")
            {
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(serverCertificateName, policy);

            RegisterForCleanup(serverCertificateName);
            await using IAsyncDisposable disposableOperation = EnsureDeleted(operation);

            // Read the CA.
            byte[]           caCertificateBytes = Convert.FromBase64String(CaPublicKeyBase64);
            X509Certificate2 caCertificate      = new X509Certificate2(caCertificateBytes);

            // Read CA private key since getting it from caCertificate above throws.
            AsymmetricCipherKeyPair caPrivateKey;

            using (StringReader caPrivateKeyReader = new StringReader(CaPrivateKeyPem))
            {
                Org.BouncyCastle.OpenSsl.PemReader reader = new Org.BouncyCastle.OpenSsl.PemReader(caPrivateKeyReader);
                caPrivateKey = (AsymmetricCipherKeyPair)reader.ReadObject();
            }

            // Read the CSR.
            Pkcs10CertificationRequest csr     = new Pkcs10CertificationRequest(operation.Properties.Csr);
            CertificationRequestInfo   csrInfo = csr.GetCertificationRequestInfo();

            // Parse the issuer subject name.
            Hashtable oidLookup = new Hashtable(X509Name.DefaultLookup)
            {
                { "s", new DerObjectIdentifier("2.5.4.8") },
            };

            X509Name issuerName = new X509Name(true, oidLookup, caCertificate.Subject);

            // Sign the request.
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetIssuerDN(issuerName);
            generator.SetSerialNumber(BigInteger.One);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddDays(1));
            generator.SetSubjectDN(csrInfo.Subject);
            generator.SetPublicKey(csr.GetPublicKey());

            Asn1SignatureFactory signatureFactory      = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.Private);
            X509Certificate      serverSignedPublicKey = generator.Generate(signatureFactory);

            // Merge the certificate chain.
            MergeCertificateOptions       options = new MergeCertificateOptions(serverCertificateName, new[] { serverSignedPublicKey.GetEncoded(), caCertificateBytes });
            KeyVaultCertificateWithPolicy mergedServerCertificate = await Client.MergeCertificateAsync(options);

            X509Certificate2 serverCertificate = new X509Certificate2(mergedServerCertificate.Cer);

            Assert.AreEqual(csrInfo.Subject.ToString(), serverCertificate.Subject);
            Assert.AreEqual(serverCertificateName, mergedServerCertificate.Name);

            KeyVaultCertificateWithPolicy completedServerCertificate = await WaitForCompletion(operation);

            Assert.AreEqual(mergedServerCertificate.Name, completedServerCertificate.Name);
            CollectionAssert.AreEqual(mergedServerCertificate.Cer, completedServerCertificate.Cer);
        }
Example #60
0
        internal static byte[] GetExtensionValueByOid(X509Certificate certificate, String oid)
        {
            Asn1OctetString extensionValue = certificate.GetExtensionValue(oid);

            return(extensionValue != null?extensionValue.GetDerEncoded() : null);
        }