public virtual void ProcessServerCertificate(Certificate serverCertificate)
		{
			X509CertificateStructure x509Cert = serverCertificate.certs[0];
			SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;

			try
			{
				this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
			}
//			catch (RuntimeException)
			catch (Exception)
			{
				throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
			}

			// Sanity check the PublicKeyFactory
			if (this.serverPublicKey.IsPrivate)
			{
				throw new TlsFatalAlert(AlertDescription.internal_error);
			}

			this.rsaServerPublicKey = ValidateRsaPublicKey((RsaKeyParameters)this.serverPublicKey);

			TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.KeyEncipherment);

			// TODO
			/*
			* Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
			* signing algorithm for the certificate must be the same as the algorithm for the
			* certificate key."
			*/
		}
		/**
		* Constructor for an encrypted private key PEM object.
		*
		* @param key       private key to be encoded
		* @param algorithm encryption algorithm to use
		* @param provider  provider to use
		* @throws NoSuchAlgorithmException if algorithm/mode cannot be found
		*/
		public Pkcs8Generator(AsymmetricKeyParameter privKey, string algorithm)
		{
			// TODO Check privKey.IsPrivate
			this.privKey = privKey;
			this.algorithm = algorithm;
			this.iterationCount = 2048;
		}
		public virtual void ProcessServerCertificate(Certificate serverCertificate)
		{
			if (tlsSigner == null)
			{
				throw new TlsFatalAlert(AlertDescription.unexpected_message);
			}

			X509CertificateStructure x509Cert = serverCertificate.certs[0];
			SubjectPublicKeyInfo keyInfo = x509Cert.SubjectPublicKeyInfo;

			try
			{
				this.serverPublicKey = PublicKeyFactory.CreateKey(keyInfo);
			}
//			catch (RuntimeException)
			catch (Exception)
			{
				throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
			}

	        if (!tlsSigner.IsValidPublicKey(this.serverPublicKey))
	        {
	            throw new TlsFatalAlert(AlertDescription.certificate_unknown);
	        }

			TlsUtilities.ValidateKeyUsage(x509Cert, KeyUsage.DigitalSignature);

			// TODO
			/*
			* Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the
			* signing algorithm for the certificate must be the same as the algorithm for the
			* certificate key."
			*/
		}
		private AsymmetricKeyParameter GetSenderPublicKey(
			AsymmetricKeyParameter		receiverPrivateKey,
			OriginatorIdentifierOrKey	originator)
		{
			OriginatorPublicKey opk = originator.OriginatorPublicKey;
			if (opk != null)
			{
				return GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, opk);
			}
			
			OriginatorID origID = new OriginatorID();
			
			Asn1.Cms.IssuerAndSerialNumber iAndSN = originator.IssuerAndSerialNumber;
			if (iAndSN != null)
			{
				origID.Issuer = iAndSN.Name;
				origID.SerialNumber = iAndSN.SerialNumber.Value;
			}
			else
			{
				SubjectKeyIdentifier ski = originator.SubjectKeyIdentifier;

				origID.SubjectKeyIdentifier = ski.GetKeyIdentifier();
			}

			return GetPublicKeyFromOriginatorID(origID);
		}
		/**
		 * 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)
		{
		}
Beispiel #6
0
		public PgpKeyPair(
            PublicKeyAlgorithmTag	algorithm,
            AsymmetricKeyParameter	pubKey,
            AsymmetricKeyParameter	privKey,
            DateTime				time)
        {
            this.pub = new PgpPublicKey(algorithm, pubKey, time);
			this.priv = new PgpPrivateKey(privKey, pub.KeyId);
        }
		public Pkcs10CertificationRequestDelaySigned(
			string					signatureAlgorithm,
			X509Name				subject,
			AsymmetricKeyParameter	publicKey,
			Asn1Set					attributes,
			AsymmetricKeyParameter	signingKey)
			: base(signatureAlgorithm, subject, publicKey, attributes, signingKey)
		{
		}
		/// <summary>
		/// Create a PgpPrivateKey from a regular private key and the ID of its
		/// associated public key.
		/// </summary>
		/// <param name="privateKey">Private key to use.</param>
		/// <param name="keyId">ID of the corresponding public key.</param>
		public PgpPrivateKey(
            AsymmetricKeyParameter	privateKey,
            long					keyId)
        {
			if (!privateKey.IsPrivate)
				throw new ArgumentException("Expected a private key", "privateKey");

			this.privateKey = privateKey;
            this.keyId = keyId;
        }
		public static EncryptedPrivateKeyInfo CreateEncryptedPrivateKeyInfo(
			string					algorithm,
			char[]					passPhrase,
			byte[]					salt,
			int						iterationCount,
			AsymmetricKeyParameter	key)
		{
			return CreateEncryptedPrivateKeyInfo(
				algorithm, passPhrase, salt, iterationCount,
				PrivateKeyInfoFactory.CreatePrivateKeyInfo(key));
		}
		public PkixCertPathBuilderResult(
			PkixCertPath			certPath,
			TrustAnchor				trustAnchor,
			PkixPolicyNode			policyTree,
			AsymmetricKeyParameter	subjectPublicKey)
			: base(trustAnchor, policyTree, subjectPublicKey)
		{			
			if (certPath == null)
				throw new ArgumentNullException("certPath");

			this.certPath = certPath;
		}
		/**
         * basic constructor.
         *
         * @param publicParam a public key parameters object.
         * @param privateParam the corresponding private key parameters.
         */
        public AsymmetricCipherKeyPair(
            AsymmetricKeyParameter    publicParameter,
            AsymmetricKeyParameter    privateParameter)
        {
			if (publicParameter.IsPrivate)
				throw new ArgumentException("Expected a public key", "publicParameter");
			if (!privateParameter.IsPrivate)
				throw new ArgumentException("Expected a private key", "privateParameter");

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

			TspUtil.ValidateCertificate(cert);

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

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

				EssCertID essCertid = new EssCertID(hash);

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

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

			this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
		}
Beispiel #13
0
		/// <summary>
		/// Creates an instance of TrustAnchor with the specified X509Certificate and
	    /// optional name constraints, which are intended to be used as additional
	    /// constraints when validating an X.509 certification path.
	    ///	The name constraints are specified as a byte array. This byte array
	    ///	should contain the DER encoded form of the name constraints, as they
	    ///	would appear in the NameConstraints structure defined in RFC 2459 and
	    ///	X.509. The ASN.1 definition of this structure appears below.
	    ///	
	    ///	<pre>
	    ///	NameConstraints ::= SEQUENCE {
	    ///		permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
	    ///		excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
	    ///	   
        /// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
        /// 
        ///		GeneralSubtree ::= SEQUENCE {
        ///		base                    GeneralName,
        ///		minimum         [0]     BaseDistance DEFAULT 0,
        ///		maximum         [1]     BaseDistance OPTIONAL }
        ///		
        ///		BaseDistance ::= INTEGER (0..MAX)
		///
		///		GeneralName ::= CHOICE {
		///		otherName                       [0]     OtherName,
		///		rfc822Name                      [1]     IA5String,
		///		dNSName                         [2]     IA5String,
		///		x400Address                     [3]     ORAddress,
		///		directoryName                   [4]     Name,
		///		ediPartyName                    [5]     EDIPartyName,
		///		uniformResourceIdentifier       [6]     IA5String,
		///		iPAddress                       [7]     OCTET STRING,
		///		registeredID                    [8]     OBJECT IDENTIFIER}
		///	</pre>
		///	
		///	Note that the name constraints byte array supplied is cloned to protect
		///	against subsequent modifications.
		/// </summary>
		/// <param name="trustedCert">a trusted X509Certificate</param>
		/// <param name="nameConstraints">a byte array containing the ASN.1 DER encoding of a
		/// NameConstraints extension to be used for checking name
		/// constraints. Only the value of the extension is included, not
		/// the OID or criticality flag. Specify null to omit the
		/// parameter.</param>
		/// <exception cref="ArgumentNullException">if the specified X509Certificate is null</exception>
		public TrustAnchor(
			X509Certificate	trustedCert,
			byte[]			nameConstraints)
		{
			if (trustedCert == null)
				throw new ArgumentNullException("trustedCert");

			this.trustedCert = trustedCert;
			this.pubKey = null;
			this.caName = null;
			this.caPrincipal = null;
			setNameConstraints(nameConstraints);
		}
		private static Asn1OctetString FromPublicKey(
			AsymmetricKeyParameter pubKey)
		{
			try
			{
				SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey);

				return (Asn1OctetString) new SubjectKeyIdentifier(info).ToAsn1Object();
			}
			catch (Exception e)
			{
				throw new CertificateParsingException("Exception extracting certificate details: " + e.ToString());
			}
		}
		private static Asn1Sequence FromKey(
			AsymmetricKeyParameter pubKey)
		{
			try
			{
				SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey);

				return (Asn1Sequence) new AuthorityKeyIdentifier(info).ToAsn1Object();
			}
			catch (Exception e)
			{
				throw new InvalidKeyException("can't process key: " + e);
			}
		}
Beispiel #16
0
		public RespID(
			AsymmetricKeyParameter publicKey)
		{
			try
			{
				SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

				byte[] keyHash = DigestUtilities.CalculateDigest("SHA1", info.PublicKeyData.GetBytes());

				this.id = new ResponderID(new DerOctetString(keyHash));
			}
			catch (Exception e)
			{
				throw new OcspException("problem creating ID: " + e, e);
			}
		}
		public PkixCertPathValidatorResult(
			TrustAnchor				trustAnchor,
			PkixPolicyNode			policyTree,
			AsymmetricKeyParameter	subjectPublicKey)
		{
			if (subjectPublicKey == null)
			{
				throw new NullReferenceException("subjectPublicKey must be non-null");
			}
			if (trustAnchor == null)
			{
				throw new NullReferenceException("trustAnchor must be non-null");
			}
			
			this.trustAnchor = trustAnchor;
			this.policyTree = policyTree;
			this.subjectPublicKey = subjectPublicKey;
		}
Beispiel #18
0
		public virtual void Verify(
			AsymmetricKeyParameter publicKey)
		{
			if (!c.SignatureAlgorithm.Equals(c.TbsCertList.Signature))
			{
				throw new CrlException("Signature algorithm on CertificateList does not match TbsCertList.");
			}

			ISigner sig = SignerUtilities.GetSigner(SigAlgName);
			sig.Init(false, publicKey);

			byte[] encoded = this.GetTbsCertList();
			sig.BlockUpdate(encoded, 0, encoded.Length);

			if (!sig.VerifySignature(this.GetSignature()))
			{
				throw new SignatureException("CRL does not verify with supplied public key.");
			}
		}
		/// <summary>
		/// Generate a new X509Certificate.
		/// </summary>
		/// <param name="privateKey">The private key of the issuer used to sign this certificate.</param>
		/// <returns>An X509Certificate.</returns>
		public X509Certificate Generate(
			AsymmetricKeyParameter privateKey)
		{
			return Generate(privateKey, null);
		}
		/// <summary>
		/// Verify the signature against the tbsResponseData object we contain.
		/// </summary>
		public bool Verify(
			AsymmetricKeyParameter publicKey)
		{
			try
			{
				ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgName);
				signature.Init(false, publicKey);
				byte[] bs = data.GetDerEncoded();
				signature.BlockUpdate(bs, 0, bs.Length);

				return signature.VerifySignature(this.GetSignature());
			}
			catch (Exception e)
			{
				throw new OcspException("exception processing sig: " + e, e);
			}
		}
Beispiel #21
0
		/**
		 * Verify the signature against the TBSRequest object we contain.
		 */
		public bool Verify(
			AsymmetricKeyParameter publicKey)
		{
			if (!this.IsSigned)
				throw new OcspException("attempt to Verify signature on unsigned object");

			try
			{
				ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgOid);

				signature.Init(false, publicKey);

				byte[] encoded = req.TbsRequest.GetEncoded();

				signature.BlockUpdate(encoded, 0, encoded.Length);

				return signature.VerifySignature(this.GetSignature());
			}
			catch (Exception e)
			{
				throw new OcspException("exception processing sig: " + e, e);
			}
		}
		private static OriginatorPublicKey CreateOriginatorPublicKey(
			AsymmetricKeyParameter publicKey)
		{
			SubjectPublicKeyInfo spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
			return new OriginatorPublicKey(
				new AlgorithmIdentifier(spki.AlgorithmID.ObjectID, DerNull.Instance),
				spki.PublicKeyData.GetBytes());
		}
		/**
		 * Create an AuthorityKeyIdentifier using just the hash of the
		 * public key.
		 *
		 * @param pubKey the key to generate the hash from.
		 * @throws InvalidKeyException if there is a problem using the key.
		 */
		public AuthorityKeyIdentifierStructure(
			AsymmetricKeyParameter pubKey)
			: base(FromKey(pubKey))
		{
		}
		internal KeyParameter GetSessionKey(
			AsymmetricKeyParameter receiverPrivateKey)
		{
			try
			{
				string wrapAlg = DerObjectIdentifier.GetInstance(
					Asn1Sequence.GetInstance(keyEncAlg.Parameters)[0]).Id;

				AsymmetricKeyParameter senderPublicKey = GetSenderPublicKey(
					receiverPrivateKey, info.Originator);

				KeyParameter agreedWrapKey = CalculateAgreedWrapKey(wrapAlg,
					senderPublicKey, receiverPrivateKey);

				return UnwrapSessionKey(wrapAlg, agreedWrapKey);
			}
			catch (SecurityUtilityException e)
			{
				throw new CmsException("couldn't create cipher.", e);
			}
			catch (InvalidKeyException e)
			{
				throw new CmsException("key invalid in message.", e);
			}
			catch (Exception e)
			{
				throw new CmsException("originator key invalid.", e);
			}
		}
        /// <summary>
        /// Generate a new X509Certificate specifying a SecureRandom instance that you would like to use.
        /// </summary>
        /// <param name="privateKey">The private key of the issuer used to sign this certificate.</param>
        /// <param name="random">The Secure Random you want to use.</param>
        /// <returns>An X509Certificate.</returns>
		public X509Certificate Generate(
			AsymmetricKeyParameter	privateKey,
			SecureRandom			random)
		{
			TbsCertificateStructure tbsCert = tbsGen.GenerateTbsCertificate();
			byte[] signature;

			try
			{
				signature = X509Utilities.GetSignatureForObject(
					sigOID, signatureAlgorithm, privateKey, random, tbsCert);
			}
			catch (Exception e)
			{
				// TODO
//				throw new ExtCertificateEncodingException("exception encoding TBS cert", e);
				throw new CertificateEncodingException("exception encoding TBS cert", e);
			}

			try
			{
				return GenerateJcaObject(tbsCert, signature);
			}
			catch (CertificateParsingException e)
			{
				// TODO
				// throw new ExtCertificateEncodingException("exception producing certificate object", e);
				throw new CertificateEncodingException("exception producing certificate object", e);
			}
		}
		private KeyParameter CalculateAgreedWrapKey(
			string					wrapAlg,
			AsymmetricKeyParameter	senderPublicKey,
			AsymmetricKeyParameter	receiverPrivateKey)
		{
			DerObjectIdentifier agreeAlgID = keyEncAlg.ObjectID;

			ICipherParameters senderPublicParams = senderPublicKey;
			ICipherParameters receiverPrivateParams = receiverPrivateKey;

			if (agreeAlgID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
			{
				byte[] ukmEncoding = info.UserKeyingMaterial.GetOctets();
				MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.GetInstance(
					Asn1Object.FromByteArray(ukmEncoding));

				AsymmetricKeyParameter ephemeralKey = GetPublicKeyFromOriginatorPublicKey(
					receiverPrivateKey, ukm.EphemeralPublicKey);

				senderPublicParams = new MqvPublicParameters(
					(ECPublicKeyParameters)senderPublicParams,
					(ECPublicKeyParameters)ephemeralKey);
				receiverPrivateParams = new MqvPrivateParameters(
					(ECPrivateKeyParameters)receiverPrivateParams,
					(ECPrivateKeyParameters)receiverPrivateParams);
			}

			IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
				agreeAlgID, wrapAlg);
			agreement.Init(receiverPrivateParams);
			BigInteger agreedValue = agreement.CalculateAgreement(senderPublicParams);

			int wrapKeySize = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;
			byte[] wrapKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, wrapKeySize);
			return ParameterUtilities.CreateKeyParameter(wrapAlg, wrapKeyBytes);
		}
        /// <summary>
        /// Set the public key that this certificate identifies.
        /// </summary>
        /// <param name="publicKey"/>
		public void SetPublicKey(
			AsymmetricKeyParameter publicKey)
		{
			try
			{
				tbsGen.SetSubjectPublicKeyInfo(
					SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey));
			}
			catch (Exception e)
			{
				throw new ArgumentException("unable to process key - " + e.ToString());
			}
		}
Beispiel #28
0
		/// <summary>
		/// Creates an instance of <code>TrustAnchor</code> where the most-trusted
		/// CA is specified as a distinguished name and public key. Name constraints
		/// are an optional parameter, and are intended to be used as additional
		/// constraints when validating an X.509 certification path.
		/// <br/>
		/// The name constraints are specified as a byte array. This byte array
		/// contains the DER encoded form of the name constraints, as they would
		/// appear in the NameConstraints structure defined in RFC 2459 and X.509.
		/// </summary>
		/// <param name="caName">the X.500 distinguished name of the most-trusted CA in RFC
		/// 2253 string format</param>
		/// <param name="pubKey">the public key of the most-trusted CA</param>
		/// <param name="nameConstraints">a byte array containing the ASN.1 DER encoding of a
		/// NameConstraints extension to be used for checking name
		/// constraints. Only the value of the extension is included, not 
		/// the OID or criticality flag. Specify null to omit the 
		/// parameter.</param>
		/// throws NullPointerException, IllegalArgumentException
		public TrustAnchor(
			string					caName,
			AsymmetricKeyParameter	pubKey,
			byte[]					nameConstraints)
		{
			if (caName == null)
				throw new ArgumentNullException("caName");
			if (pubKey == null)
				throw new ArgumentNullException("pubKey");
			if (caName.Length == 0)
				throw new ArgumentException("caName can not be an empty string");

			this.caPrincipal = new X509Name(caName);
			this.pubKey = pubKey;
			this.caName = caName;
			this.trustedCert = null;
			setNameConstraints(nameConstraints);
		}
		public SubjectKeyIdentifierStructure(
			AsymmetricKeyParameter pubKey)
			: base(FromPublicKey(pubKey))
		{
		}
Beispiel #30
0
		/// <summary>
		/// Creates an instance of <c>TrustAnchor</c> where the
		/// most-trusted CA is specified as an X500Principal and public key.
		/// </summary>
		/// <remarks>
		/// <p>
		/// Name constraints are an optional parameter, and are intended to be used
		/// as additional constraints when validating an X.509 certification path.
		/// </p><p>
		/// The name constraints are specified as a byte array. This byte array
		/// contains the DER encoded form of the name constraints, as they
		/// would appear in the NameConstraints structure defined in RFC 2459
		/// and X.509. The ASN.1 notation for this structure is supplied in the
		/// documentation for the other constructors.
		/// </p><p>
		/// Note that the name constraints byte array supplied here is cloned to
		/// protect against subsequent modifications.
		/// </p>
		/// </remarks>
		/// <param name="caPrincipal">the name of the most-trusted CA as X509Name</param>
		/// <param name="pubKey">the public key of the most-trusted CA</param>
		/// <param name="nameConstraints">
		/// a byte array containing the ASN.1 DER encoding of a NameConstraints extension to
		/// be used for checking name constraints. Only the value of the extension is included,
		/// not the OID or criticality flag. Specify <c>null</c> to omit the parameter.
		/// </param>
		/// <exception cref="ArgumentNullException">
		/// if <c>caPrincipal</c> or <c>pubKey</c> is null
		/// </exception>
		public TrustAnchor(
			X509Name				caPrincipal,
			AsymmetricKeyParameter	pubKey,
			byte[]					nameConstraints) 
		{
			if (caPrincipal == null)
				throw new ArgumentNullException("caPrincipal");
			if (pubKey == null)
				throw new ArgumentNullException("pubKey");

			this.trustedCert = null;
			this.caPrincipal = caPrincipal;
			this.caName = caPrincipal.ToString();
			this.pubKey = pubKey;
			setNameConstraints(nameConstraints);
		}