GetPublicKey() public method

Get the public key of the subject of the certificate.
public GetPublicKey ( ) : AsymmetricKeyParameter
return AsymmetricKeyParameter
Exemplo n.º 1
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;
			}
		}
        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 ();
        }
Exemplo n.º 3
0
		public virtual bool IsSignedBy(X509Certificate potentialIssuer)
		{
			try
			{
				//return ocspResp.Verify(potentialIssuer.GetPublicKey(), "BC");
                return ocspResp.Verify(potentialIssuer.GetPublicKey());
			}
			/*catch (NoSuchProviderException e)
			{
				throw new RuntimeException(e);
			}*/
			catch (OcspException)
			{
				return false;
			}
		}
Exemplo n.º 4
0
		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;

			Fingerprint = certificate.GetFingerprint ();
		}
        public static bool IsSignedBy(this X509Certificate thisCertificate, X509Certificate signerCertificate)
        {
            X509Certificate2 c = new X509Certificate2(thisCertificate.GetTbsCertificate());
            X509Certificate2 i = new X509Certificate2(signerCertificate.GetTbsCertificate());
            X509Certificate2 c2 = new X509Certificate2(@"c:\temp\der.cer");
            X509Certificate2 i2 = new X509Certificate2(@"c:\temp\cader.cer");
            /*byte[] pvSubject = thisCertificate.GetTbsCertificate();
            byte[] pvIssuer = signerCertificate.GetTbsCertificate();
            */
            System.Text.Encoding.ASCII.GetString(c.RawData);
            IntPtr pvSubject = c.Handle;
            IntPtr pvIssuer = i.Handle;
            int res = SspiProvider.CryptVerifyCertificateSignatureEx(IntPtr.Zero, X509_ASN_ENCODING,
                                                           CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, pvSubject,
                                                           CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, pvIssuer, 0,
                                                           IntPtr.Zero);
            Marshal.GetLastWin32Error();
            CmsSigner signer = new CmsSigner(i);
            SignedCms signedMessage = new SignedCms();
            // deserialize PKCS #7 byte array

            signedMessage.Decode(thisCertificate.GetTbsCertificate());
            Log.Write("Veryfy old");
            Log.Write("EndVeryfy old");
            Log.Write("Get signer's public key");
            var publicKey = signerCertificate.GetPublicKey();
            Log.Write("Got signer's public key");
            try
            {
                Log.Write("Veryfy signature");
                //TODO: log errors
                thisCertificate.Verify(publicKey);
                Log.Write("Verified");
            }
            catch (CertificateException)
            {
                return false;
            }
            catch (InvalidKeyException)
            {
                return false;
            }
            return true;
        }
 public static bool IsSignedBy(this X509Crl thisCertificate, X509Certificate signerCertificate)
 {
     Log.Write("Get signer's public key");
     var publicKey = signerCertificate.GetPublicKey();
     Log.Write("Got signer's public key");
     try
     {
         Log.Write("Veryfy signature");
         thisCertificate.Verify(publicKey);
         Log.Write("Veryfied");
     }
     catch (CrlException)
     {
         return false;
     }
     catch(SignatureException)
     {
         return false;
     }
     return true;
 }
Exemplo n.º 7
0
        /**
         * create from an issuer certificate and the serial number of the
         * certificate it signed.
         * @exception OcspException if any problems occur creating the id fields.
         */
        public CertificateID(
			string			hashAlgorithm,
			X509Certificate	issuerCert,
			BigInteger		number)
        {
            try
            {
                IDigest digest = DigestUtilities.GetDigest(hashAlgorithm);
                AlgorithmIdentifier hashAlg = new AlgorithmIdentifier(
                    new DerObjectIdentifier(hashAlgorithm), DerNull.Instance);

                X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert);

                byte[] encodedIssuerName = issuerName.GetEncoded();
                digest.BlockUpdate(encodedIssuerName, 0, encodedIssuerName.Length);

                byte[] hash = DigestUtilities.DoFinal(digest);

                Asn1OctetString issuerNameHash = new DerOctetString(hash);
                AsymmetricKeyParameter issuerKey = issuerCert.GetPublicKey();

                SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKey);

                byte[] encodedPublicKey = info.PublicKeyData.GetBytes();
                digest.BlockUpdate(encodedPublicKey, 0, encodedPublicKey.Length);

                hash = DigestUtilities.DoFinal(digest);

                Asn1OctetString issuerKeyHash = new DerOctetString(hash);

                DerInteger serialNumber = new DerInteger(number);

                this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber);
            }
            catch (Exception e)
            {
                throw new OcspException("problem creating ID: " + e, e);
            }
        }
        public bool VerifySignature(X509Certificate attestationCertificate, byte[] signedBytes, byte[] signature)
        {
            if (attestationCertificate == null)
            {
                throw new ArgumentNullException(nameof(attestationCertificate));
            }
            if (signedBytes == null)
            {
                throw new ArgumentNullException(nameof(signedBytes));
            }
            if (signature == null)
            {
                throw new ArgumentNullException(nameof(signature));
            }

            var publicKey = attestationCertificate.GetPublicKey() as ECPublicKeyParameters;
            if (publicKey == null)
            {
                throw new U2FException("The certificate publickey isn't an Elliptic curve");
            }

            return VerifySignature(publicKey, signedBytes, signature);
        }
Exemplo n.º 9
0
 private void ValidateResponse(BasicOcspResp or, X509Certificate issuerCert)
 {
     ValidateResponseSignature(or, issuerCert.GetPublicKey());
     ValidateSignerAuthorization(issuerCert, or.GetCerts()[0]);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Verify signature
        /// </summary>
        /// <returns>Boolean indicating success</returns>
        public bool VerifySignature(byte[] data, byte[] expectedSignature, X509Certificate cert)
        {
            /* Init alg */
            ISigner signer = SignerUtilities.GetSigner("SHA256withRSA");

            /* Populate key */
            signer.Init(false, cert.GetPublicKey());

            /* Calculate the signature and see if it matches */
            signer.BlockUpdate(data, 0, data.Length);
            return signer.VerifySignature(expectedSignature);
        }
Exemplo n.º 11
0
	    /**
	     * Verifies if an OCSP response is genuine
	     * @param ocspResp	the OCSP response
	     * @param issuerCert	the issuer certificate
	     * @throws GeneralSecurityException
	     * @throws IOException
	     */
	    public void IsValidResponse(BasicOcspResp ocspResp, X509Certificate issuerCert) {
		    // by default the OCSP responder certificate is the issuer certificate
		    X509Certificate responderCert = issuerCert;
		    // check if there's a responder certificate
		    X509Certificate[] certs = ocspResp.GetCerts();
		    if (certs.Length > 0) {
			    responderCert = certs[0];
			    try {
				    responderCert.Verify(issuerCert.GetPublicKey());
			    }
			    catch (GeneralSecurityException) {
				    if (base.Verify(responderCert, issuerCert, DateTime.MaxValue).Count == 0)
                        throw new VerificationException(responderCert, String.Format("{0} Responder certificate couldn't be verified", responderCert));
			    }
		    }
		    // verify if the signature of the response is valid
		    if (!VerifyResponse(ocspResp, responderCert))
                throw new VerificationException(responderCert, String.Format("{0} OCSP response could not be verified", responderCert));
	    }
Exemplo n.º 12
0
		/**
		* verify that the given certificate successfully handles and confirms
		* the signature associated with this signer and, if a signingTime
		* attribute is available, that the certificate was valid at the time the
		* signature was generated.
		*/
		public bool Verify(
			X509Certificate cert)
		{
			Asn1.Cms.Time signingTime = GetSigningTime();
			if (signingTime != null)
			{
				cert.CheckValidity(signingTime.Date);
			}

			return DoVerify(cert.GetPublicKey());
		}
Exemplo n.º 13
0
        private static CertID CreateCertID(
			AlgorithmIdentifier	hashAlg,
			X509Certificate		issuerCert,
			DerInteger			serialNumber)
		{
			try
			{
				String hashAlgorithm = hashAlg.ObjectID.Id;

				X509Name issuerName = PrincipalUtilities.GetSubjectX509Principal(issuerCert);
				byte[] issuerNameHash = DigestUtilities.CalculateDigest(
					hashAlgorithm, issuerName.GetEncoded());

				AsymmetricKeyParameter issuerKey = issuerCert.GetPublicKey();
				SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKey);
				byte[] issuerKeyHash = DigestUtilities.CalculateDigest(
					hashAlgorithm, info.PublicKeyData.GetBytes());

				return new CertID(hashAlg, new DerOctetString(issuerNameHash),
					new DerOctetString(issuerKeyHash), serialNumber);
			}
			catch (Exception e)
			{
				throw new OcspException("problem creating ID: " + e, e);
			}
		}
Exemplo n.º 14
0
        /**
        * verify that the given certificate succesfully handles and confirms
        * the signature associated with this signer and, if a signingTime
        * attribute is available, that the certificate was valid at the time the
        * signature was generated.
        */
        public bool Verify(
			X509Certificate cert)
        {
            Asn1.Cms.AttributeTable attr = this.SignedAttributes;

            if (attr != null)
            {
                Asn1.Cms.Attribute t = attr[CmsAttributes.SigningTime];

                if (t != null)
                {
                    Asn1.Cms.Time time = Asn1.Cms.Time.GetInstance(
                        t.AttrValues[0].ToAsn1Object());

                    cert.CheckValidity(time.Date);
                }
            }

            return DoVerify(cert.GetPublicKey(), attr);
        }
Exemplo n.º 15
0
 private void ValidateResponse(BasicOcspResp in_OcspResp, X509Certificate in_CertificadoEmisor)
 {
     ValidarResponseSignature(in_OcspResp, in_CertificadoEmisor.GetPublicKey());
     ValidarSignerAuthorization(in_CertificadoEmisor, in_OcspResp.GetCerts()[0]);
 }
 private static bool IsSelfSigned(X509Certificate certificate)
 {
     if (!certificate.SubjectDN.Equivalent(certificate.IssuerDN))
         return false;
     try
     {
         certificate.Verify(certificate.GetPublicKey());
         return true;
     }
     catch (SignatureException)
     {
         return false;
     }
     catch (InvalidKeyException)
     {
         return false;
     }
 }
Exemplo n.º 17
0
		private void VerifySigner(SignerInformation signer, X509Certificate cert)
		{
			if (cert.GetPublicKey() is DsaPublicKeyParameters)
			{
				DsaPublicKeyParameters key = (DsaPublicKeyParameters)cert.GetPublicKey();

				if (key.Parameters == null)
				{
					Assert.IsTrue(signer.Verify(GetInheritedKey(key)));
				}
				else
				{
					Assert.IsTrue(signer.Verify(cert));
				}
			}
			else
			{
				Assert.IsTrue(signer.Verify(cert));
			}
		}
Exemplo n.º 18
0
        private bool IsRequestSignatureValid(X509Certificate cert, string signature, HttpRequestBase request)
        {
            byte[] requestBytes;
            using (MemoryStream mem = new MemoryStream())
            {
                request.InputStream.CopyTo(mem);
                request.InputStream.Position = 0;
                requestBytes = mem.ToArray();
            }

            byte[] signatureBytes = null;
            try
            {
                signatureBytes = Convert.FromBase64String(signature);
            }
            catch (FormatException)
            {
                return false;
            }

            var publicKey = (RsaKeyParameters)cert.GetPublicKey();
            var signer = SignerUtilities.GetSigner("SHA1withRSA");
            signer.Init(false, publicKey);
            signer.BlockUpdate(requestBytes, 0, requestBytes.Length);

            return signer.VerifySignature(signatureBytes);
        }
 static Asn1OctetString CreateIssuerKeyHash(X509Certificate rootCertificate)
 {
     var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCertificate.GetPublicKey());
     byte[] bytes = publicKeyInfo.PublicKeyData.GetBytes();
     return CreateDigestFromBytes(bytes);
 }
Exemplo n.º 20
0
		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;
		}
Exemplo n.º 21
0
	    /**
	     * Checks the validity of the certificate, and calls the next
	     * verifier in the chain, if any.
	     * @param signCert	the certificate that needs to be checked
	     * @param issuerCert	its issuer
	     * @param signDate		the date the certificate needs to be valid
	     * @return a list of <code>VerificationOK</code> objects.
	     * The list will be empty if the certificate couldn't be verified.
	     * @throws GeneralSecurityException
	     * @throws IOException
	     */
	    virtual public List<VerificationOK> Verify(X509Certificate signCert, X509Certificate issuerCert, DateTime signDate) {
		    // Check if the certificate is valid on the signDate
		    //if (signDate != null)
			    signCert.CheckValidity(signDate);
		    // Check if the signature is valid
		    if (issuerCert != null) {
			    signCert.Verify(issuerCert.GetPublicKey());
		    }
		    // Also in case, the certificate is self-signed
		    else {
			    signCert.Verify(signCert.GetPublicKey());
		    }
		    List<VerificationOK> result = new List<VerificationOK>();
		    if (verifier != null)
			    result.AddRange(verifier.Verify(signCert, issuerCert, signDate));
		    return result;
	    }
Exemplo n.º 22
0
 /**
  * Checks if a CRL verifies against the issuer certificate or a trusted anchor.
  * @param crl	the CRL
  * @param crlIssuer	the trusted anchor
  * @return	true if the CRL can be trusted
  */
 public bool IsSignatureValid(X509Crl crl, X509Certificate crlIssuer)
 {
     // check if the CRL was issued by the issuer
     if (crlIssuer != null) {
         try {
             crl.Verify(crlIssuer.GetPublicKey());
             return true;
         } catch (GeneralSecurityException) {
             LOGGER.Warn("CRL not issued by the same authority as the certificate that is being checked");
         }
     }
     // check the CRL against trusted anchors
     if (certificates == null)
         return false;
     try {
         // loop over the certificate in the key store
         foreach (X509Certificate anchor in certificates) {
             try {
                 crl.Verify(anchor.GetPublicKey());
                 return true;
             } catch (GeneralSecurityException) {}
         }
     }
     catch (GeneralSecurityException) {
         return false;
     }
     return false;
 }
        private void SubjectKeyIDTest(
			IAsymmetricCipherKeyPair	signaturePair,
			X509Certificate			signatureCert,
			string					digestAlgorithm)
        {
            IList certList = new ArrayList();
            IList crlList = new ArrayList();
            CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes("Hello World!"));

            certList.Add(signatureCert);
            certList.Add(OrigCert);

            crlList.Add(SignCrl);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));
            IX509Store x509Crls = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

            gen.AddSigner(signaturePair.Private,
                CmsTestUtil.CreateSubjectKeyId(signatureCert.GetPublicKey()).GetKeyIdentifier(),
                digestAlgorithm);

            gen.AddCertificates(x509Certs);
            gen.AddCrls(x509Crls);

            CmsSignedData s = gen.Generate(msg, true);

            Assert.AreEqual(3, s.Version);

            MemoryStream bIn = new MemoryStream(s.GetEncoded(), false);
            Asn1InputStream aIn = new Asn1InputStream(bIn);

            s = new CmsSignedData(ContentInfo.GetInstance(aIn.ReadObject()));

            x509Certs = s.GetCertificates("Collection");
            x509Crls = s.GetCrls("Collection");

            SignerInformationStore signers = s.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();

                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate) certEnum.Current;

                Assert.IsTrue(signer.Verify(cert));
            }

            //
            // check for CRLs
            //
            ArrayList crls = new ArrayList(x509Crls.GetMatches(null));

            Assert.AreEqual(1, crls.Count);

            Assert.IsTrue(crls.Contains(SignCrl));

            //
            // try using existing signer
            //

            gen = new CmsSignedDataGenerator();

            gen.AddSigners(s.GetSignerInfos());

            gen.AddCertificates(s.GetCertificates("Collection"));
            gen.AddCrls(s.GetCrls("Collection"));

            s = gen.Generate(msg, true);

            bIn = new MemoryStream(s.GetEncoded(), false);
            aIn = new Asn1InputStream(bIn);

            s = new CmsSignedData(ContentInfo.GetInstance(aIn.ReadObject()));

            x509Certs = s.GetCertificates("Collection");
            x509Crls = s.GetCrls("Collection");

            signers = s.GetSignerInfos();

            foreach (SignerInformation signer in signers.GetSigners())
            {
                ICollection certCollection = x509Certs.GetMatches(signer.SignerID);

                IEnumerator certEnum = certCollection.GetEnumerator();

                certEnum.MoveNext();
                X509Certificate cert = (X509Certificate) certEnum.Current;

                Assert.IsTrue(signer.Verify(cert));
            }

            CheckSignerStoreReplacement(s, signers);
        }
Exemplo n.º 24
0
		/**
		* we generate an intermediate certificate signed by our CA
		*/
		public static X509CertificateEntry CreateIntermediateCert(
			AsymmetricKeyParameter	pubKey,
			AsymmetricKeyParameter	caPrivKey,
			X509Certificate			caCert)
		{
			//
			// subject name table.
			//
			IDictionary attrs = new Hashtable();
			IList order = new ArrayList();

			attrs.Add(X509Name.C, "AU");
			attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
			attrs.Add(X509Name.OU, "Bouncy Intermediate Certificate");
			attrs.Add(X509Name.EmailAddress, "*****@*****.**");

			order.Add(X509Name.C);
			order.Add(X509Name.O);
			order.Add(X509Name.OU);
			order.Add(X509Name.EmailAddress);

			//
			// create the certificate - version 3
			//
			v3CertGen.Reset();

			v3CertGen.SetSerialNumber(BigInteger.Two);
			v3CertGen.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(caCert));
			v3CertGen.SetNotBefore(DateTime.UtcNow.AddMonths(-1));
			v3CertGen.SetNotAfter(DateTime.UtcNow.AddMonths(1));
			v3CertGen.SetSubjectDN(new X509Name(order, attrs));
			v3CertGen.SetPublicKey(pubKey);
			v3CertGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

			//
			// extensions
			//
			v3CertGen.AddExtension(
				X509Extensions.SubjectKeyIdentifier,
				false,
				new SubjectKeyIdentifierStructure(pubKey));

			v3CertGen.AddExtension(
				X509Extensions.AuthorityKeyIdentifier,
				false,
				new AuthorityKeyIdentifierStructure(caCert));

			v3CertGen.AddExtension(
				X509Extensions.BasicConstraints,
				true,
				new BasicConstraints(0));

			X509Certificate cert = v3CertGen.Generate(caPrivKey);

			cert.CheckValidity(DateTime.UtcNow);

			cert.Verify(caCert.GetPublicKey());

//			PKCS12BagAttributeCarrier   bagAttr = (PKCS12BagAttributeCarrier)cert;
			IDictionary bagAttr = new Hashtable();

			//
			// this is actually optional - but if you want to have control
			// over setting the friendly name this is the way to do it...
			//
//			bagAttr.setBagAttribute(
//				PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
//				new DERBMPString("Bouncy Intermediate Certificate"));
			bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id,
				new DerBmpString("Bouncy Intermediate Certificate"));

			return new X509CertificateEntry(cert, bagAttr);
		}
 private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) {
     Asn1InputStream asn1inputstream = 
         new Asn1InputStream(new MemoryStream(x509certificate.GetTbsCertificate()));
     TbsCertificateStructure tbscertificatestructure = 
         TbsCertificateStructure.GetInstance(asn1inputstream.ReadObject());
     AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.SubjectPublicKeyInfo.AlgorithmID;
     Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerandserialnumber = 
         new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(
             tbscertificatestructure.Issuer, 
             tbscertificatestructure.SerialNumber.Value);
     IBufferedCipher cipher = CipherUtilities.GetCipher(algorithmidentifier.ObjectID);
     cipher.Init(true, x509certificate.GetPublicKey());
     byte[] outp = new byte[10000];
     int len = cipher.DoFinal(abyte0, outp, 0);
     byte[] abyte1 = new byte[len];
     System.Array.Copy(outp, 0, abyte1, 0, len);
     DerOctetString deroctetstring = new DerOctetString(abyte1);
     RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
     return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring);
 }        
Exemplo n.º 26
0
			internal RecipientInf(
				X509Certificate cert)
			{
				this.cert = cert;
				this.pubKey = cert.GetPublicKey();

				try
				{
					TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
						Asn1Object.FromByteArray(cert.GetTbsCertificate()));

					keyEncAlg = tbs.SubjectPublicKeyInfo.AlgorithmID;
				}
//				catch (IOException e)
				catch (Exception)
				{
					throw new ArgumentException("can't extract key algorithm from this cert");
				}
//				catch (CertificateEncodingException)
//				{
//					throw new ArgumentException("can't extract tbs structure from this cert");
//				}
			}
Exemplo n.º 27
0
        /**
        * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
        * @param contentsKey the /Contents key
        * @param certsKey the /Cert key
        * @param provider the provider or <code>null</code> for the default provider
        */    
        public PdfPKCS7(byte[] contentsKey, byte[] certsKey) {

            X509CertificateParser cf = new X509CertificateParser();
            certs = new ArrayList();
            foreach (X509Certificate cc in cf.ReadCertificates(certsKey)) {
                certs.Add(cc);
            }
            signCerts = certs;
            signCert = (X509Certificate)certs[0];
            crls = new ArrayList();
            Asn1InputStream inp = new Asn1InputStream(new MemoryStream(contentsKey));
            digest = ((DerOctetString)inp.ReadObject()).GetOctets();
            sig = SignerUtilities.GetSigner("SHA1withRSA");
            sig.Init(false, signCert.GetPublicKey());
        }
Exemplo n.º 28
0
		/**
		* Add a key agreement based recipient.
		*
		* @param agreementAlgorithm key agreement algorithm to use.
		* @param senderPrivateKey private key to initialise sender side of agreement with.
		* @param senderPublicKey sender public key to include with message.
		* @param recipientCert recipient's public key certificate.
		* @param cekWrapAlgorithm OID for key wrapping algorithm to use.
		* @exception SecurityUtilityException if the algorithm requested cannot be found
		* @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
		*/
		public void AddKeyAgreementRecipient(
			string					agreementAlgorithm,
			AsymmetricKeyParameter	senderPrivateKey,
			AsymmetricKeyParameter	senderPublicKey,
			X509Certificate			recipientCert,
			string					cekWrapAlgorithm)
		{
			if (!senderPrivateKey.IsPrivate)
				throw new ArgumentException("Expected private key", "senderPrivateKey");
			if (senderPublicKey.IsPrivate)
				throw new ArgumentException("Expected public key", "senderPublicKey");

			IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
				agreementAlgorithm, cekWrapAlgorithm);

			agreement.Init(new ParametersWithRandom(senderPrivateKey, rand));

			BigInteger secretNum = agreement.CalculateAgreement(recipientCert.GetPublicKey());

			try
			{
				SubjectPublicKeyInfo oPubKeyInfo =
					SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(senderPublicKey);

				OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
					new OriginatorPublicKey(
						new AlgorithmIdentifier(oPubKeyInfo.AlgorithmID.ObjectID, DerNull.Instance),
						oPubKeyInfo.PublicKeyData.GetBytes()));

				// TODO Fix the way bytes are derived from the secret
				byte[] secretBytes = secretNum.ToByteArrayUnsigned();
				KeyParameter secret = ParameterUtilities.CreateKeyParameter(
					cekWrapAlgorithm, secretBytes);

				recipientInfs.Add(
					new RecipientInf(cekWrapAlgorithm, secret, agreementAlgorithm,
						cekWrapAlgorithm, originator, recipientCert));
			}
			catch (IOException e)
			{
				throw new InvalidKeyException("cannot extract originator public key: " + e);
			}
		}
Exemplo n.º 29
0
	    /**
	     * Checks if an OCSP response is genuine
	     * @param ocspResp	the OCSP response
	     * @param responderCert	the responder certificate
	     * @return	true if the OCSP response verifies against the responder certificate
	     */
        public bool IsSignatureValid(BasicOcspResp ocspResp, X509Certificate responderCert) {
		    try {
			    return ocspResp.Verify(responderCert.GetPublicKey());
		    } catch (OcspException) {
			    return false;
		    }
	    }
Exemplo n.º 30
0
		/**
		* verify that the given certificate successfully handles and confirms
		* the signature associated with this signer and, if a signingTime
		* attribute is available, that the certificate was valid at the time the
		* signature was generated.
		*/
		public bool Verify(
			X509Certificate cert)
		{
			Asn1.Cms.AttributeTable attr = this.SignedAttributes;

			if (attr != null)
			{
				Asn1EncodableVector v = attr.GetAll(CmsAttributes.SigningTime);
				switch (v.Count)
				{
					case 0:
						break;
					case 1:
					{
						Asn1.Cms.Attribute t = (Asn1.Cms.Attribute) v[0];
						Debug.Assert(t != null);

						Asn1Set attrValues = t.AttrValues;
						if (attrValues.Count != 1)
							throw new CmsException("A signing-time attribute MUST have a single attribute value");

						Asn1.Cms.Time time = Asn1.Cms.Time.GetInstance(attrValues[0].ToAsn1Object());

						cert.CheckValidity(time.Date);
						break;
					}
					default:
						throw new CmsException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the signing-time attribute");
				}
			}

			return DoVerify(cert.GetPublicKey(), attr);
		}