public SigPolicyQualifierInfo(
			DerObjectIdentifier	sigPolicyQualifierId,
			Asn1Encodable		sigQualifier)
		{
			this.sigPolicyQualifierId = sigPolicyQualifierId;
			this.sigQualifier = sigQualifier.ToAsn1Object();
		}
Esempio n. 2
0
		/**
		 * Constructor for elliptic curves over binary fields
		 * <code>F<sub>2<sup>m</sup></sub></code>.
		 * @param m  The exponent <code>m</code> of
		 * <code>F<sub>2<sup>m</sup></sub></code>.
		 * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
		 * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
		 * represents the reduction polynomial <code>f(z)</code>.
		 * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
		 * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
		 * represents the reduction polynomial <code>f(z)</code>.
		 * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
		 * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
		 * represents the reduction polynomial <code>f(z)</code>..
		 */
		public X9FieldID(
			int m,
			int k1,
			int k2,
			int k3)
		{
			this.id = X9ObjectIdentifiers.CharacteristicTwoField;

			Asn1EncodableVector fieldIdParams = new Asn1EncodableVector(new DerInteger(m));

			if (k2 == 0)
			{
				fieldIdParams.Add(
					X9ObjectIdentifiers.TPBasis,
					new DerInteger(k1));
			}
			else
			{
				fieldIdParams.Add(
					X9ObjectIdentifiers.PPBasis,
					new DerSequence(
						new DerInteger(k1),
						new DerInteger(k2),
						new DerInteger(k3)));
			}

			this.parameters = new DerSequence(fieldIdParams);
		}
        private PrivateKeyInfo(
            Asn1Sequence seq)
        {
            IEnumerator e = seq.GetEnumerator();

            e.MoveNext();
            IBigInteger version = ((DerInteger) e.Current).Value;
            if (version.IntValue != 0)
            {
                throw new ArgumentException("wrong version for private key info");
            }

            e.MoveNext();
            algID = AlgorithmIdentifier.GetInstance(e.Current);

            try
            {
                e.MoveNext();
                Asn1OctetString data = (Asn1OctetString) e.Current;

                privKey = Asn1Object.FromByteArray(data.GetOctets());
            }
            catch (IOException)
            {
                throw new ArgumentException("Error recoverying private key from sequence");
            }

            if (e.MoveNext())
            {
                attributes = Asn1Set.GetInstance((Asn1TaggedObject) e.Current, false);
            }
        }
Esempio n. 4
0
		/**
         * When the subjectAltName extension contains an Internet mail address,
         * the address MUST be included as an rfc822Name. The format of an
         * rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
         *
         * When the subjectAltName extension contains a domain name service
         * label, the domain name MUST be stored in the dNSName (an IA5String).
         * The name MUST be in the "preferred name syntax," as specified by RFC
         * 1034 [RFC 1034].
         *
         * When the subjectAltName extension contains a URI, the name MUST be
         * stored in the uniformResourceIdentifier (an IA5String). The name MUST
         * be a non-relative URL, and MUST follow the URL syntax and encoding
         * rules specified in [RFC 1738].  The name must include both a scheme
         * (e.g., "http" or "ftp") and a scheme-specific-part.  The scheme-
         * specific-part must include a fully qualified domain name or IP
         * address as the host.
         *
         * When the subjectAltName extension contains a iPAddress, the address
         * MUST be stored in the octet string in "network byte order," as
         * specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
         * each octet is the LSB of the corresponding byte in the network
         * address. For IP Version 4, as specified in RFC 791, the octet string
         * MUST contain exactly four octets.  For IP Version 6, as specified in
         * RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
         * 1883].
         */
        public GeneralName(
            Asn1Object	name,
			int			tag)
        {
            this.obj = name;
            this.tag = tag;
        }
Esempio n. 5
0
		public CertBag(
            DerObjectIdentifier	certID,
            Asn1Object			certValue)
        {
            this.certID = certID;
            this.certValue = certValue;
        }
 public PrivateKeyInfo(
     AlgorithmIdentifier	algID,
     Asn1Object			privateKey,
     Asn1Set				attributes)
 {
     this.algID = algID;
     this.privKey = new DerOctetString(privateKey.GetEncoded(Asn1Encodable.Der));
     this.attributes = attributes;
 }
        public PrivateKeyInfo(
			AlgorithmIdentifier	algID,
			Asn1Object			privateKey,
			Asn1Set				attributes)
        {
            this.privKey = privateKey;
            this.algID = algID;
            this.attributes = attributes;
        }
Esempio n. 8
0
		private ServiceLocator(
			Asn1Sequence seq)
		{
			this.issuer = X509Name.GetInstance(seq[0]);

			if (seq.Count > 1)
			{
				this.locator = seq[1].ToAsn1Object();
			}
		}
Esempio n. 9
0
		public ServiceLocator(
			X509Name	issuer,
			Asn1Object	locator)
		{
			if (issuer == null)
				throw new ArgumentNullException("issuer");

			this.issuer = issuer;
			this.locator = locator;
		}
Esempio n. 10
0
        public Time(
            Asn1Object time)
        {
            if (time == null)
                throw new ArgumentNullException("time");
            if (!(time is DerUtcTime) && !(time is DerGeneralizedTime))
                throw new ArgumentException("unknown object passed to Time");

            this.time = time;
        }
Esempio n. 11
0
		public CertBag(
            Asn1Sequence seq)
        {
			if (seq.Count != 2)
				throw new ArgumentException("Wrong number of elements in sequence", "seq");

//			this.seq = seq;
            this.certID = DerObjectIdentifier.GetInstance(seq[0]);
            this.certValue = DerTaggedObject.GetInstance(seq[1]).GetObject();
        }
		private SigPolicyQualifierInfo(
			Asn1Sequence seq)
		{
			if (seq == null)
				throw new ArgumentNullException("seq");
			if (seq.Count != 2)
				throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");

			this.sigPolicyQualifierId = (DerObjectIdentifier) seq[0].ToAsn1Object();
			this.sigQualifier = seq[1].ToAsn1Object();
		}
Esempio n. 13
0
		private OtherRevRefs(
			Asn1Sequence seq)
		{
			if (seq == null)
				throw new ArgumentNullException("seq");
			if (seq.Count != 2)
				throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");

			this.otherRevRefType = (DerObjectIdentifier) seq[0].ToAsn1Object();
			this.otherRevRefs = seq[1].ToAsn1Object();
		}
Esempio n. 14
0
		public OtherRevRefs(
			DerObjectIdentifier	otherRevRefType,
			Asn1Encodable		otherRevRefs)
		{
			if (otherRevRefType == null)
				throw new ArgumentNullException("otherRevRefType");
			if (otherRevRefs == null)
				throw new ArgumentNullException("otherRevRefs");

			this.otherRevRefType = otherRevRefType;
			this.otherRevRefs = otherRevRefs.ToAsn1Object();
		}
    /**
        * Creates a new <code>CommitmentTypeQualifier</code> instance.
        *
        * @param commitmentTypeIdentifier a <code>CommitmentTypeIdentifier</code> value
        * @param qualifier the qualifier, defined by the above field.
        */
        public CommitmentTypeQualifier(
            DerObjectIdentifier	commitmentTypeIdentifier,
            Asn1Encodable		qualifier)
        {
			if (commitmentTypeIdentifier == null)
				throw new ArgumentNullException("commitmentTypeIdentifier");

			this.commitmentTypeIdentifier = commitmentTypeIdentifier;

			if (qualifier != null)
			{
				this.qualifier = qualifier.ToAsn1Object();
			}
        }
        /**
        * Creates a new <code>CommitmentTypeQualifier</code> instance.
        *
        * @param as <code>CommitmentTypeQualifier</code> structure
        * encoded as an Asn1Sequence.
        */
        public CommitmentTypeQualifier(
            Asn1Sequence seq)
        {
			if (seq == null)
				throw new ArgumentNullException("seq");
			if (seq.Count < 1 || seq.Count > 2)
				throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");

			commitmentTypeIdentifier = (DerObjectIdentifier) seq[0].ToAsn1Object();

			if (seq.Count > 1)
            {
                qualifier = seq[1].ToAsn1Object();
            }
        }
Esempio n. 17
0
        /**
         * creates a time object from a given date - if the date is between 1950
         * and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
         * is used.
         */
        public Time(
            DateTime date)
        {
            string d = date.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z";

            int year = int.Parse(d.Substring(0, 4));

            if (year < 1950 || year > 2049)
            {
                time = new DerGeneralizedTime(d);
            }
            else
            {
                time = new DerUtcTime(d.Substring(2));
            }
        }
Esempio n. 18
0
		/**
         * creates a time object from a given date - if the date is between 1950
         * and 2049 a UTCTime object is Generated, otherwise a GeneralizedTime
         * is used.
         */
        public Time(
            DateTime date)
        {
            string d = date.ToString("yyyyMMddHHmmss") + "Z";

			int year = Int32.Parse(d.Substring(0, 4));

			if (year < 1950 || year > 2049)
            {
                time = new DerGeneralizedTime(d);
            }
            else
            {
                time = new DerUtcTime(d.Substring(2));
            }
        }
        public static X509Name GetIssuerX509Principal(X509Certificate cert)
        {
            X509Name issuer;

            try
            {
                TbsCertificateStructure instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetTbsCertificate()));
                issuer = instance.Issuer;
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Could not extract issuer", e);
            }
            return(issuer);
        }
Esempio n. 20
0
 /// <summary>
 /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the
 /// provided.
 /// </summary>
 /// <remarks>
 /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the
 /// provided. The hashing is performed by the method using the specified algorithm and a BouncyCastle provider.
 /// </remarks>
 /// <param name="signedData"></param>
 /// <exception cref="System.Exception">System.Exception</exception>
 protected internal virtual BcCms.Attribute GetTimeStampAttribute(DerObjectIdentifier oid
                                                                  , ITspSource tsa, AlgorithmIdentifier digestAlgorithm, byte[] messageImprint)
 {
     try
     {
         //jbonilla Hack para obtener el digest del TSA
         IDigest digest        = null;
         string  algorithmName = null;
         digest        = DigestUtilities.GetDigest(DigestAlgorithm.SHA1.GetName());
         algorithmName = DigestAlgorithm.SHA1.GetName();
         digest.BlockUpdate(messageImprint, 0, messageImprint.Length);
         byte[] r = new byte[digest.GetDigestSize()];
         digest.DoFinal(r, 0);
         byte[]            toTimeStamp = r;
         TimeStampResponse tsresp      = tsa.GetTimeStampResponse(DigestAlgorithm.GetByName(algorithmName)
                                                                  , toTimeStamp);
         TimeStampToken tstoken = tsresp.TimeStampToken;
         if (tstoken == null)
         {
             throw new ArgumentNullException("The TimeStampToken returned for the signature time stamp was empty."
                                             );
         }
         BcCms.Attribute signatureTimeStamp = new BcCms.Attribute(oid, new DerSet(Asn1Object.FromByteArray
                                                                                      (tstoken.GetEncoded())));
         return(signatureTimeStamp);
     }
     catch (IOException e)
     {
         throw new RuntimeException(e);
     }
     catch (NoSuchAlgorithmException e)
     {
         throw new RuntimeException(e);
     }
 }
Esempio n. 21
0
        /**
         * Gets a String from an ASN1Primitive
         * @param names the ASN1Primitive
         * @return  a human-readable String
         * @throws IOException
         */
        private static String GetStringFromGeneralName(Asn1Object names)
        {
            Asn1TaggedObject taggedObject = (Asn1TaggedObject)names;

            return(Encoding.GetEncoding(1252).GetString(Asn1OctetString.GetInstance(taggedObject, false).GetOctets()));
        }
 public SubstringFilter_substrings_element(long?choiceIndex, Asn1Object obj)
     : base(choiceIndex, obj)
 {
 }
 public PrivateKeyInfo(
     AlgorithmIdentifier	algID,
     Asn1Object			privateKey)
     : this(algID, privateKey, null)
 {
 }
		public RecipientIdentifier(
            Asn1Object id)
        {
            this.id = id;
        }
        /**
         * Fetches delta CRLs according to RFC 3280 section 5.2.4.
         *
         * @param currentDate The date for which the delta CRLs must be valid.
         * @param paramsPKIX The extended PKIX parameters.
         * @param completeCRL The complete CRL the delta CRL is for.
         * @return A <code>Set</code> of <code>X509CRL</code>s with delta CRLs.
         * @throws Exception if an exception occurs while picking the delta
         *             CRLs.
         */
        internal static ISet GetDeltaCrls(
            DateTime currentDate,
            PkixParameters paramsPKIX,
            X509Crl completeCRL)
        {
            X509CrlStoreSelector deltaSelect = new X509CrlStoreSelector();

            // 5.2.4 (a)
            try
            {
                IList deltaSelectIssuer = Platform.CreateArrayList();
                deltaSelectIssuer.Add(completeCRL.IssuerDN);
                deltaSelect.Issuers = deltaSelectIssuer;
            }
            catch (IOException e)
            {
                throw new Exception("Cannot extract issuer from CRL.", e);
            }

            BigInteger completeCRLNumber = null;

            try
            {
                Asn1Object asn1Object = GetExtensionValue(completeCRL, X509Extensions.CrlNumber);
                if (asn1Object != null)
                {
                    completeCRLNumber = CrlNumber.GetInstance(asn1Object).PositiveValue;
                }
            }
            catch (Exception e)
            {
                throw new Exception(
                          "CRL number extension could not be extracted from CRL.", e);
            }

            // 5.2.4 (b)
            byte[] idp = null;

            try
            {
                Asn1Object obj = GetExtensionValue(completeCRL, X509Extensions.IssuingDistributionPoint);
                if (obj != null)
                {
                    idp = obj.GetDerEncoded();
                }
            }
            catch (Exception e)
            {
                throw new Exception(
                          "Issuing distribution point extension value could not be read.",
                          e);
            }

            // 5.2.4 (d)

            deltaSelect.MinCrlNumber = (completeCRLNumber == null)
                                ?       null
                                :       completeCRLNumber.Add(BigInteger.One);

            deltaSelect.IssuingDistributionPoint        = idp;
            deltaSelect.IssuingDistributionPointEnabled = true;

            // 5.2.4 (c)
            deltaSelect.MaxBaseCrlNumber = completeCRLNumber;

            // find delta CRLs
            ISet temp = CrlUtilities.FindCrls(deltaSelect, paramsPKIX, currentDate);

            ISet result = new HashSet();

            foreach (X509Crl crl in temp)
            {
                if (isDeltaCrl(crl))
                {
                    result.Add(crl);
                }
            }

            return(result);
        }
Esempio n. 26
0
        private bool DoVerify(
            AsymmetricKeyParameter key)
        {
            string  digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
            IDigest digest     = Helper.GetDigestInstance(digestName);

            DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID;
            Asn1Encodable       sigParams = this.encryptionAlgorithm.Parameters;
            ISigner             sig;

            if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
            {
                // RFC 4056 2.2
                // When the id-RSASSA-PSS algorithm identifier is used for a signature,
                // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
                if (sigParams == null)
                {
                    throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
                }

                try
                {
                    // TODO Provide abstract configuration mechanism
                    // (via alternate SignerUtilities.GetSigner method taking ASN.1 params)

                    Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
                        sigParams.ToAsn1Object());

                    if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
                    }
                    if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
                    }

                    IDigest pssDigest    = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID);
                    int     saltLength   = pss.SaltLength.Value.IntValue;
                    byte    trailerField = (byte)pss.TrailerField.Value.IntValue;

                    // RFC 4055 3.1
                    // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
                    if (trailerField != 1)
                    {
                        throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
                    }

                    sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
                }
                catch (Exception e)
                {
                    throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
                }
            }
            else
            {
                // TODO Probably too strong a check at the moment
//				if (sigParams != null)
//					throw new CmsException("unrecognised signature parameters provided");

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

                sig = Helper.GetSignatureInstance(signatureName);

                //sig = Helper.GetSignatureInstance(this.EncryptionAlgOid);
                //sig = SignerUtilities.GetSigner(sigAlgOid);
            }

            try
            {
                if (digestCalculator != null)
                {
                    resultDigest = digestCalculator.GetDigest();
                }
                else
                {
                    if (content != null)
                    {
                        content.Write(new DigOutputStream(digest));
                    }
                    else if (signedAttributeSet == null)
                    {
                        // TODO Get rid of this exception and just treat content==null as empty not missing?
                        throw new CmsException("data not encapsulated in signature - use detached constructor.");
                    }

                    resultDigest = DigestUtilities.DoFinal(digest);
                }
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }

            // RFC 3852 11.1 Check the content-type attribute is correct
            {
                Asn1Object validContentType = GetSingleValuedSignedAttribute(
                    CmsAttributes.ContentType, "content-type");
                if (validContentType == null)
                {
                    if (!isCounterSignature && signedAttributeSet != null)
                    {
                        throw new CmsException("The content-type attribute type MUST be present whenever signed attributes are present in signed-data");
                    }
                }
                else
                {
                    if (isCounterSignature)
                    {
                        throw new CmsException("[For counter signatures,] the signedAttributes field MUST NOT contain a content-type attribute");
                    }

                    if (!(validContentType is DerObjectIdentifier))
                    {
                        throw new CmsException("content-type attribute value not of ASN.1 type 'OBJECT IDENTIFIER'");
                    }

                    DerObjectIdentifier signedContentType = (DerObjectIdentifier)validContentType;

                    if (!signedContentType.Equals(contentType))
                    {
                        throw new CmsException("content-type attribute value does not match eContentType");
                    }
                }
            }

            // RFC 3852 11.2 Check the message-digest attribute is correct
            {
                Asn1Object validMessageDigest = GetSingleValuedSignedAttribute(
                    CmsAttributes.MessageDigest, "message-digest");
                if (validMessageDigest == null)
                {
                    if (signedAttributeSet != null)
                    {
                        throw new CmsException("the message-digest signed attribute type MUST be present when there are any signed attributes present");
                    }
                }
                else
                {
                    if (!(validMessageDigest is Asn1OctetString))
                    {
                        throw new CmsException("message-digest attribute value not of ASN.1 type 'OCTET STRING'");
                    }

                    Asn1OctetString signedMessageDigest = (Asn1OctetString)validMessageDigest;

                    if (!Arrays.AreEqual(resultDigest, signedMessageDigest.GetOctets()))
                    {
                        throw new CmsException("message-digest attribute value does not match calculated value");
                    }
                }
            }

            // RFC 3852 11.4 Validate countersignature attribute(s)
            {
                Asn1.Cms.AttributeTable signedAttrTable = this.SignedAttributes;
                if (signedAttrTable != null &&
                    signedAttrTable.GetAll(CmsAttributes.CounterSignature).Count > 0)
                {
                    throw new CmsException("A countersignature attribute MUST NOT be a signed attribute");
                }

                Asn1.Cms.AttributeTable unsignedAttrTable = this.UnsignedAttributes;
                if (unsignedAttrTable != null)
                {
                    foreach (Asn1.Cms.Attribute csAttr in unsignedAttrTable.GetAll(CmsAttributes.CounterSignature))
                    {
                        if (csAttr.AttrValues.Count < 1)
                        {
                            throw new CmsException("A countersignature attribute MUST contain at least one AttributeValue");
                        }

                        // Note: We don't recursively validate the countersignature value
                    }
                }
            }

            try
            {
                sig.Init(false, key);

                if (signedAttributeSet == null)
                {
                    if (digestCalculator != null)
                    {
                        // need to decrypt signature and check message bytes
                        return(VerifyDigest(resultDigest, key, this.GetSignature()));
                    }
                    else if (content != null)
                    {
                        // TODO Use raw signature of the hash value instead
                        content.Write(new SigOutputStream(sig));
                    }
                }
                else
                {
                    byte[] tmp = this.GetEncodedSignedAttributes();
                    sig.BlockUpdate(tmp, 0, tmp.Length);
                }

                return(sig.VerifySignature(this.GetSignature()));
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException("invalid signature format in message: " + e.Message, e);
            }
        }
Esempio n. 27
0
        private bool DoVerify(
            AsymmetricKeyParameter key,
            Asn1.Cms.AttributeTable signedAttrTable)
        {
            string  digestName = Helper.GetDigestAlgName(this.DigestAlgOid);
            IDigest digest     = Helper.GetDigestInstance(digestName);

            DerObjectIdentifier sigAlgOid = this.encryptionAlgorithm.ObjectID;
            Asn1Encodable       sigParams = this.encryptionAlgorithm.Parameters;
            ISigner             sig;

            if (sigAlgOid.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdRsassaPss))
            {
                // RFC 4056 2.2
                // When the id-RSASSA-PSS algorithm identifier is used for a signature,
                // the AlgorithmIdentifier parameters field MUST contain RSASSA-PSS-params.
                if (sigParams == null)
                {
                    throw new CmsException("RSASSA-PSS signature must specify algorithm parameters");
                }

                try
                {
                    // TODO Provide abstract configuration mechanism

                    Asn1.Pkcs.RsassaPssParameters pss = Asn1.Pkcs.RsassaPssParameters.GetInstance(
                        sigParams.ToAsn1Object());

                    if (!pss.HashAlgorithm.ObjectID.Equals(this.digestAlgorithm.ObjectID))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified incorrect hash algorithm");
                    }
                    if (!pss.MaskGenAlgorithm.ObjectID.Equals(Asn1.Pkcs.PkcsObjectIdentifiers.IdMgf1))
                    {
                        throw new CmsException("RSASSA-PSS signature parameters specified unknown MGF");
                    }

                    IDigest pssDigest    = DigestUtilities.GetDigest(pss.HashAlgorithm.ObjectID);
                    int     saltLength   = pss.SaltLength.Value.IntValue;
                    byte    trailerField = (byte)pss.TrailerField.Value.IntValue;

                    // RFC 4055 3.1
                    // The value MUST be 1, which represents the trailer field with hexadecimal value 0xBC
                    if (trailerField != 1)
                    {
                        throw new CmsException("RSASSA-PSS signature parameters must have trailerField of 1");
                    }

                    sig = new PssSigner(new RsaBlindedEngine(), pssDigest, saltLength);
                }
                catch (Exception e)
                {
                    throw new CmsException("failed to set RSASSA-PSS signature parameters", e);
                }
            }
            else
            {
                // TODO Probably too strong a check at the moment
//				if (sigParams != null)
//					throw new CmsException("unrecognised signature parameters provided");

                string signatureName = digestName + "with" + Helper.GetEncryptionAlgName(this.EncryptionAlgOid);

                sig = Helper.GetSignatureInstance(signatureName);
            }

            try
            {
                sig.Init(false, key);

                if (signedAttributes == null)
                {
                    if (content != null)
                    {
                        content.Write(new CmsSignedDataGenerator.SigOutputStream(sig));
                        content.Write(new CmsSignedDataGenerator.DigOutputStream(digest));

                        resultDigest = DigestUtilities.DoFinal(digest);
                    }
                    else
                    {
                        resultDigest = digestCalculator.GetDigest();

                        // need to decrypt signature and check message bytes
                        return(VerifyDigest(resultDigest, key, this.GetSignature()));
                    }
                }
                else
                {
                    byte[] hash;
                    if (content != null)
                    {
                        content.Write(
                            new CmsSignedDataGenerator.DigOutputStream(digest));

                        hash = DigestUtilities.DoFinal(digest);
                    }
                    else if (digestCalculator != null)
                    {
                        hash = digestCalculator.GetDigest();
                    }
                    else
                    {
                        hash = null;
                    }

                    resultDigest = hash;

                    Asn1.Cms.Attribute dig  = signedAttrTable[Asn1.Cms.CmsAttributes.MessageDigest];
                    Asn1.Cms.Attribute type = signedAttrTable[Asn1.Cms.CmsAttributes.ContentType];

                    if (dig == null)
                    {
                        throw new SignatureException("no hash for content found in signed attributes");
                    }

                    if (type == null && !contentType.Equals(CmsAttributes.CounterSignature))
                    {
                        throw new SignatureException("no content type id found in signed attributes");
                    }

                    Asn1Object hashObj = dig.AttrValues[0].ToAsn1Object();

                    if (hashObj is Asn1OctetString)
                    {
                        byte[] signedHash = ((Asn1OctetString)hashObj).GetOctets();

                        if (!Arrays.AreEqual(hash, signedHash))
                        {
                            throw new SignatureException("content hash found in signed attributes different");
                        }
                    }
                    else if (hashObj is DerNull)
                    {
                        if (hash != null)
                        {
                            throw new SignatureException("NULL hash found in signed attributes when one expected");
                        }
                    }

                    if (type != null)
                    {
                        DerObjectIdentifier typeOID = (DerObjectIdentifier)type.AttrValues[0];

                        if (!typeOID.Equals(contentType))
                        {
                            throw new SignatureException("contentType in signed attributes different");
                        }
                    }

                    byte[] tmp = this.GetEncodedSignedAttributes();
                    sig.BlockUpdate(tmp, 0, tmp.Length);
                }

                return(sig.VerifySignature(this.GetSignature()));
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException(
                          "key not appropriate to signature in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException(
                          "can't process mime object to create signature.", e);
            }
            catch (SignatureException e)
            {
                throw new CmsException(
                          "invalid signature format in message: " + e.Message, e);
            }
        }
Esempio n. 28
0
        private void doTestParams(
            byte[]  ecParameterEncoded,
            bool compress)
        {
//			string keyStorePass = "******";
            Asn1Sequence            seq = (Asn1Sequence)Asn1Object.FromByteArray(ecParameterEncoded);
            X9ECParameters          x9  = new X9ECParameters(seq);
            AsymmetricCipherKeyPair kp  = null;
            bool success = false;

            while (!success)
            {
                IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ECDSA");
//				kpg.Init(new ECParameterSpec(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()));
                ECDomainParameters ecParams = new ECDomainParameters(
                    x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                kpg.Init(new ECKeyGenerationParameters(ecParams, new SecureRandom()));
                kp = kpg.GenerateKeyPair();
                // The very old Problem... we need a certificate chain to
                // save a private key...
                ECPublicKeyParameters pubKey = (ECPublicKeyParameters)kp.Public;

                if (!compress)
                {
                    //pubKey.setPointFormat("UNCOMPRESSED");
                    pubKey = SetPublicUncompressed(pubKey);
                }

                byte[] x = pubKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned();
                byte[] y = pubKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned();
                if (x.Length == y.Length)
                {
                    success = true;
                }
            }

            // The very old Problem... we need a certificate chain to
            // save a private key...

            X509CertificateEntry[] chain = new X509CertificateEntry[] {
                new X509CertificateEntry(GenerateSelfSignedSoftECCert(kp, compress))
            };

//			KeyStore keyStore = KeyStore.getInstance("BKS");
//			keyStore.load(null, keyStorePass.ToCharArray());
            Pkcs12Store keyStore = new Pkcs12StoreBuilder().Build();

            keyStore.SetCertificateEntry("ECCert", chain[0]);

            ECPrivateKeyParameters privateECKey = (ECPrivateKeyParameters)kp.Private;

            keyStore.SetKeyEntry("ECPrivKey", new AsymmetricKeyEntry(privateECKey), chain);

            // Test ec sign / verify
            ECPublicKeyParameters pub = (ECPublicKeyParameters)kp.Public;

//			string oldPrivateKey = new string(Hex.encode(privateECKey.getEncoded()));
            byte[] oldPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateECKey).GetDerEncoded();
            string oldPrivateKey      = Hex.ToHexString(oldPrivateKeyBytes);

//			string oldPublicKey = new string(Hex.encode(pub.getEncoded()));
            byte[] oldPublicKeyBytes      = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub).GetDerEncoded();
            string oldPublicKey           = Hex.ToHexString(oldPublicKeyBytes);
            ECPrivateKeyParameters newKey = (ECPrivateKeyParameters)
                                            keyStore.GetKey("ECPrivKey").Key;
            ECPublicKeyParameters newPubKey = (ECPublicKeyParameters)
                                              keyStore.GetCertificate("ECCert").Certificate.GetPublicKey();

            if (!compress)
            {
                // TODO Private key compression?
                //newKey.setPointFormat("UNCOMPRESSED");
                //newPubKey.setPointFormat("UNCOMPRESSED");
                newPubKey = SetPublicUncompressed(newPubKey);
            }

//			string newPrivateKey = new string(Hex.encode(newKey.getEncoded()));
            byte[] newPrivateKeyBytes = PrivateKeyInfoFactory.CreatePrivateKeyInfo(newKey).GetDerEncoded();
            string newPrivateKey      = Hex.ToHexString(newPrivateKeyBytes);

//			string newPublicKey = new string(Hex.encode(newPubKey.getEncoded()));
            byte[] newPublicKeyBytes = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(newPubKey).GetDerEncoded();
            string newPublicKey      = Hex.ToHexString(newPublicKeyBytes);

            if (!oldPrivateKey.Equals(newPrivateKey))
//			if (!privateECKey.Equals(newKey))
            {
                Fail("failed private key comparison");
            }

            if (!oldPublicKey.Equals(newPublicKey))
//			if (!pub.Equals(newPubKey))
            {
                Fail("failed public key comparison");
            }
        }
 private static AsymmetricKeyParameter DecryptKey(
     char[]          passPhrase,
     Asn1Object asn1Object)
 {
     return(DecryptKey(passPhrase, EncryptedPrivateKeyInfo.GetInstance(asn1Object)));
 }
 public static AsymmetricKeyParameter DecryptKey(
     char[]  passPhrase,
     Stream encryptedPrivateKeyInfoStream)
 {
     return(DecryptKey(passPhrase, Asn1Object.FromStream(encryptedPrivateKeyInfoStream)));
 }
 public static AsymmetricKeyParameter DecryptKey(
     char[]  passPhrase,
     byte[]  encryptedPrivateKeyInfoData)
 {
     return(DecryptKey(passPhrase, Asn1Object.FromByteArray(encryptedPrivateKeyInfoData)));
 }
Esempio n. 32
0
        /**
         * dump a Der object as a formatted string with indentation
         *
         * @param obj the Asn1Object to be dumped out.
         */
        private static string AsString(
            string		indent,
            bool		verbose,
            Asn1Object	obj)
        {
            if (obj is Asn1Sequence)
            {
                StringBuilder buf = new StringBuilder(indent);

				string tab = indent + Tab;

                if (obj is BerSequence)
                {
                    buf.Append("BER Sequence");
                }
                else if (obj is DerSequence)
                {
                    buf.Append("DER Sequence");
                }
                else
                {
                    buf.Append("Sequence");
                }

                buf.Append(NewLine);

				foreach (Asn1Encodable o in ((Asn1Sequence)obj))
				{
                    if (o == null || o is Asn1Null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        buf.Append(AsString(tab, verbose, o.ToAsn1Object()));
                    }
                }
                return buf.ToString();
            }
            else if (obj is DerTaggedObject)
            {
                StringBuilder buf = new StringBuilder();
                string tab = indent + Tab;

				buf.Append(indent);
                if (obj is BerTaggedObject)
                {
                    buf.Append("BER Tagged [");
                }
                else
                {
                    buf.Append("Tagged [");
                }

				DerTaggedObject o = (DerTaggedObject)obj;

				buf.Append(((int)o.TagNo).ToString());
                buf.Append(']');

				if (!o.IsExplicit())
                {
                    buf.Append(" IMPLICIT ");
                }

				buf.Append(NewLine);

				if (o.IsEmpty())
                {
                    buf.Append(tab);
                    buf.Append("EMPTY");
                    buf.Append(NewLine);
                }
                else
                {
                    buf.Append(AsString(tab, verbose, o.GetObject()));
                }

				return buf.ToString();
            }
            else if (obj is BerSet)
            {
                StringBuilder buf = new StringBuilder();
                string tab = indent + Tab;

				buf.Append(indent);
                buf.Append("BER Set");
                buf.Append(NewLine);

				foreach (Asn1Encodable o in ((Asn1Set)obj))
				{
                    if (o == null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        buf.Append(AsString(tab, verbose, o.ToAsn1Object()));
                    }
                }

				return buf.ToString();
            }
            else if (obj is DerSet)
            {
                StringBuilder buf = new StringBuilder();
                string tab = indent + Tab;

				buf.Append(indent);
                buf.Append("DER Set");
                buf.Append(NewLine);

				foreach (Asn1Encodable o in ((Asn1Set)obj))
				{
                    if (o == null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        buf.Append(AsString(tab, verbose, o.ToAsn1Object()));
                    }
                }

				return buf.ToString();
            }
            else if (obj is DerObjectIdentifier)
            {
                return indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine;
            }
            else if (obj is DerBoolean)
            {
                return indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine;
            }
            else if (obj is DerInteger)
            {
                return indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine;
            }
			else if (obj is BerOctetString)
			{
				byte[] octets = ((Asn1OctetString)obj).GetOctets();
				string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
				return indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine;
			}
            else if (obj is DerOctetString)
            {
				byte[] octets = ((Asn1OctetString)obj).GetOctets();
				string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
				return indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine;
			}
			else if (obj is DerBitString)
			{
				DerBitString bt = (DerBitString)obj; 
				byte[] bytes = bt.GetBytes();
				string extra = verbose ? dumpBinaryDataAsString(indent, bytes) : "";
				return indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine;
			}
            else if (obj is DerIA5String)
            {
                return indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine;
            }
			else if (obj is DerUtf8String)
			{
				return indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine;
			}
            else if (obj is DerPrintableString)
            {
                return indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine;
            }
            else if (obj is DerVisibleString)
            {
                return indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine;
            }
            else if (obj is DerBmpString)
            {
                return indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine;
            }
            else if (obj is DerT61String)
            {
                return indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine;
            }
            else if (obj is DerUtcTime)
            {
                return indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine;
            }
			else if (obj is DerGeneralizedTime)
			{
				return indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine;
			}
            else if (obj is DerUnknownTag)
            {
				byte[] hex = Hex.Encode(((DerUnknownTag)obj).GetData());
                return indent + "Unknown " + ((int)((DerUnknownTag)obj).Tag).ToString("X") + " "
                    + Encoding.ASCII.GetString(hex, 0, hex.Length) + NewLine;
            }
            else if (obj is BerApplicationSpecific)
            {
                return outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj);
            }
            else if (obj is DerApplicationSpecific)
            {
                return outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj);
            }
            else
            {
                return indent + obj.ToString() + NewLine;
            }
        }
Esempio n. 33
0
 public PrivateKeyInfo(
     AlgorithmIdentifier algID,
     Asn1Object privateKey)
     : this(algID, privateKey, null)
 {
 }
Esempio n. 34
0
 public SignerIdentifier(
     Asn1Object id)
 {
     this.id = id;
 }
        public override void PerformTest()
        {
            byte[] data = { 0, 1, 0, 1, 0, 0, 1 };

            Asn1Object[] values =
            {
                new BerOctetString(data),
                new BerSequence(new DerPrintableString("hello world")),
                new BerSet(new DerPrintableString("hello world")),
                new BerTaggedObject(0,                                 new DerPrintableString("hello world")),
                new DerApplicationSpecific(0,                          data),
                new DerBitString(data),
                new DerBmpString("hello world"),
                DerBoolean.True,
                DerBoolean.False,
                new DerEnumerated(100),
                new DerGeneralizedTime("20070315173729Z"),
                new DerGeneralString("hello world"),
                new DerIA5String("hello"),
                new DerInteger(1000),
                DerNull.Instance,
                new DerNumericString("123456"),
                new DerObjectIdentifier("1.1.1.10000.1"),
                new DerOctetString(data),
                new DerPrintableString("hello world"),
                new DerSequence(new DerPrintableString("hello world")),
                new DerSet(new DerPrintableString("hello world")),
                new DerT61String("hello world"),
                new DerTaggedObject(0,                                 new DerPrintableString("hello world")),
                new DerUniversalString(data),
                new DerUtcTime(new DateTime()),
                new DerUtf8String("hello world"),
                new DerVisibleString("hello world"),
                new DerGraphicString(Hex.Decode("deadbeef")),
                new DerVideotexString(Strings.ToByteArray("Hello World"))
            };

            MemoryStream     bOut = new MemoryStream();
            Asn1OutputStream aOut = new Asn1OutputStream(bOut);

            for (int i = 0; i != values.Length; i++)
            {
                aOut.WriteObject(values[i]);
            }

            Asn1InputStream aIn = new Asn1InputStream(bOut.ToArray());

            for (int i = 0; i != values.Length; i++)
            {
                Asn1Object o = aIn.ReadObject();
                if (!o.Equals(values[i]))
                {
                    Fail("Failed equality test for " + o.GetType().Name);
                }

                if (o.GetHashCode() != values[i].GetHashCode())
                {
                    Fail("Failed hashCode test for " + o.GetType().Name);
                }
            }
        }
Esempio n. 36
0
 /**
  * Constructor for elliptic curves over prime fields
  * <code>F<sub>2</sub></code>.
  * @param primeP The prime <code>p</code> defining the prime field.
  */
 public X9FieldID(
     BigInteger primeP)
 {
     this.id         = X9ObjectIdentifiers.PrimeField;
     this.parameters = new DerInteger(primeP);
 }
 public OriginatorIdentifierOrKey(
     Asn1Object id)
 {
     this.id = id;
 }
Esempio n. 38
0
 internal X9FieldID(
     Asn1Sequence seq)
 {
     this.id         = (DerObjectIdentifier)seq[0];
     this.parameters = (Asn1Object)seq[1];
 }
Esempio n. 39
0
 public static AsymmetricKeyParameter CreateKey(byte[] keyInfoData)
 {
     return(CreateKey(SubjectPublicKeyInfo.GetInstance(Asn1Object.FromByteArray(keyInfoData))));
 }
Esempio n. 40
0
 public static Key FromCurveName(Asn1Object obj)
 {
     return(new Key(Native.ExpectNonNull(Native.EC_KEY_new_by_curve_name(obj.NID)), true));
 }
Esempio n. 41
0
        public TimeStampToken(
            CmsSignedData signedData)
        {
            this.tsToken = signedData;

            if (!this.tsToken.SignedContentType.Equals(PkcsObjectIdentifiers.IdCTTstInfo))
            {
                throw new TspValidationException("ContentInfo object not for a time stamp.");
            }

            ICollection signers = tsToken.GetSignerInfos().GetSigners();

            if (signers.Count != 1)
            {
                throw new ArgumentException("Time-stamp token signed by "
                                            + signers.Count
                                            + " signers, but it must contain just the TSA signature.");
            }


            IEnumerator signerEnum = signers.GetEnumerator();

            signerEnum.MoveNext();
            tsaSignerInfo = (SignerInformation)signerEnum.Current;

            try
            {
                CmsProcessable content = tsToken.SignedContent;
                MemoryStream   bOut    = new MemoryStream();

                content.Write(bOut);

                this.tstInfo = new TimeStampTokenInfo(
                    TstInfo.GetInstance(
                        Asn1Object.FromByteArray(bOut.ToArray())));

                Asn1.Cms.Attribute attr = tsaSignerInfo.SignedAttributes[
                    PkcsObjectIdentifiers.IdAASigningCertificate];

//				if (attr == null)
//				{
//					throw new TspValidationException(
//						"no signing certificate attribute found, time stamp invalid.");
//				}
//
//				SigningCertificate signCert = SigningCertificate.GetInstance(
//					attr.AttrValues[0]);
//
//				this.certID = EssCertID.GetInstance(signCert.GetCerts()[0]);

                if (attr != null)
                {
                    SigningCertificate signCert = SigningCertificate.GetInstance(attr.AttrValues[0]);

                    this.certID = new CertID(EssCertID.GetInstance(signCert.GetCerts()[0]));
                }
                else
                {
                    attr = tsaSignerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2];

                    if (attr == null)
                    {
                        throw new TspValidationException("no signing certificate attribute found, time stamp invalid.");
                    }

                    SigningCertificateV2 signCertV2 = SigningCertificateV2.GetInstance(attr.AttrValues[0]);

                    this.certID = new CertID(EssCertIDv2.GetInstance(signCertV2.GetCerts()[0]));
                }
            }
            catch (CmsException e)
            {
                throw new TspException(e.Message, e.InnerException);
            }
        }
Esempio n. 42
0
		/**
		 * Constructor for elliptic curves over prime fields
		 * <code>F<sub>2</sub></code>.
		 * @param primeP The prime <code>p</code> defining the prime field.
		 */
		public X9FieldID(
			BigInteger primeP)
		{
			this.id = X9ObjectIdentifiers.PrimeField;
			this.parameters = new DerInteger(primeP);
		}
 /// <summary>
 ///     Return an Asn1 representation of this delete request
 ///     #return an Asn1 representation of this object.
 /// </summary>
 public override string ToString()
 {
     return(Asn1Object.ToString());
 }
Esempio n. 44
0
		internal X9FieldID(
			Asn1Sequence seq)
		{
			this.id = (DerObjectIdentifier) seq[0];
			this.parameters = (Asn1Object) seq[1];
		}
Esempio n. 45
0
 private BuiltinCurve(int nid, string comment)
 {
     this.obj     = new Asn1Object(nid);
     this.comment = comment;
 }
Esempio n. 46
0
 public static AsymmetricKeyParameter CreateKey(Stream inStr)
 {
     return(CreateKey(SubjectPublicKeyInfo.GetInstance(Asn1Object.FromStream(inStr))));
 }
Esempio n. 47
0
 private X9FieldID(Asn1Sequence seq)
 {
     this.id = DerObjectIdentifier.GetInstance(seq[0]);
     this.parameters = seq[1].ToAsn1Object();
 }
    public static ICipherParameters GenerateCipherParameters(string algorithm, char[] password, bool wrongPkcs12Zero, Asn1Encodable pbeParameters)
    {
        string text = (string)algorithms[Platform.ToUpperInvariant(algorithm)];

        byte[] array          = null;
        byte[] salt           = null;
        int    iterationCount = 0;

        if (IsPkcs12(text))
        {
            Pkcs12PbeParams instance = Pkcs12PbeParams.GetInstance(pbeParameters);
            salt           = instance.GetIV();
            iterationCount = instance.Iterations.IntValue;
            array          = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
        }
        else if (!IsPkcs5Scheme2(text))
        {
            PbeParameter instance2 = PbeParameter.GetInstance(pbeParameters);
            salt           = instance2.GetSalt();
            iterationCount = instance2.IterationCount.IntValue;
            array          = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
        }
        ICipherParameters parameters = null;

        if (IsPkcs5Scheme2(text))
        {
            PbeS2Parameters     instance3        = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
            AlgorithmIdentifier encryptionScheme = instance3.EncryptionScheme;
            DerObjectIdentifier algorithm2       = encryptionScheme.Algorithm;
            Asn1Object          obj       = encryptionScheme.Parameters.ToAsn1Object();
            Pbkdf2Params        instance4 = Pbkdf2Params.GetInstance(instance3.KeyDerivationFunc.Parameters.ToAsn1Object());
            byte[] array2;
            if (algorithm2.Equals(PkcsObjectIdentifiers.RC2Cbc))
            {
                RC2CbcParameter instance5 = RC2CbcParameter.GetInstance(obj);
                array2 = instance5.GetIV();
            }
            else
            {
                array2 = Asn1OctetString.GetInstance(obj).GetOctets();
            }
            salt           = instance4.GetSalt();
            iterationCount = instance4.IterationCount.IntValue;
            array          = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            int keySize = (instance4.KeyLength != null) ? (instance4.KeyLength.IntValue * 8) : GeneratorUtilities.GetDefaultKeySize(algorithm2);
            PbeParametersGenerator pbeParametersGenerator = MakePbeGenerator((string)algorithmType[text], null, array, salt, iterationCount);
            parameters = pbeParametersGenerator.GenerateDerivedParameters(algorithm2.Id, keySize);
            if (array2 != null && !Arrays.AreEqual(array2, new byte[array2.Length]))
            {
                parameters = new ParametersWithIV(parameters, array2);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithSHA-1"))
        {
            PbeParametersGenerator pbeParametersGenerator2 = MakePbeGenerator((string)algorithmType[text], new Sha1Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 128, 128);
            }
            else if (text.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 192, 128);
            }
            else if (text.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("AES", 256, 128);
            }
            else if (text.Equals("PBEwithSHA-1and128bitRC4"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 128);
            }
            else if (text.Equals("PBEwithSHA-1and40bitRC4"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC4", 40);
            }
            else if (text.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 192, 64);
            }
            else if (text.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("DESEDE", 128, 64);
            }
            else if (text.Equals("PBEwithSHA-1and128bitRC2-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 128, 64);
            }
            else if (text.Equals("PBEwithSHA-1and40bitRC2-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 40, 64);
            }
            else if (text.Equals("PBEwithSHA-1andDES-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("DES", 64, 64);
            }
            else if (text.Equals("PBEwithSHA-1andRC2-CBC"))
            {
                parameters = pbeParametersGenerator2.GenerateDerivedParameters("RC2", 64, 64);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithSHA-256"))
        {
            PbeParametersGenerator pbeParametersGenerator3 = MakePbeGenerator((string)algorithmType[text], new Sha256Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 128, 128);
            }
            else if (text.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 192, 128);
            }
            else if (text.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
            {
                parameters = pbeParametersGenerator3.GenerateDerivedParameters("AES", 256, 128);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithMD5"))
        {
            PbeParametersGenerator pbeParametersGenerator4 = MakePbeGenerator((string)algorithmType[text], new MD5Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithMD5andDES-CBC"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("DES", 64, 64);
            }
            else if (text.Equals("PBEwithMD5andRC2-CBC"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("RC2", 64, 64);
            }
            else if (text.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 128, 128);
            }
            else if (text.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 192, 128);
            }
            else if (text.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
            {
                parameters = pbeParametersGenerator4.GenerateDerivedParameters("AES", 256, 128);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithMD2"))
        {
            PbeParametersGenerator pbeParametersGenerator5 = MakePbeGenerator((string)algorithmType[text], new MD2Digest(), array, salt, iterationCount);
            if (text.Equals("PBEwithMD2andDES-CBC"))
            {
                parameters = pbeParametersGenerator5.GenerateDerivedParameters("DES", 64, 64);
            }
            else if (text.Equals("PBEwithMD2andRC2-CBC"))
            {
                parameters = pbeParametersGenerator5.GenerateDerivedParameters("RC2", 64, 64);
            }
        }
        else if (Platform.StartsWith(text, "PBEwithHmac"))
        {
            string  algorithm3 = text.Substring("PBEwithHmac".Length);
            IDigest digest     = DigestUtilities.GetDigest(algorithm3);
            PbeParametersGenerator pbeParametersGenerator6 = MakePbeGenerator((string)algorithmType[text], digest, array, salt, iterationCount);
            int keySize2 = digest.GetDigestSize() * 8;
            parameters = pbeParametersGenerator6.GenerateDerivedMacParameters(keySize2);
        }
        Array.Clear(array, 0, array.Length);
        return(FixDesParity(text, parameters));
    }
Esempio n. 49
0
		/**
         * Constructor for elliptic curves over binary fields
         * <code>F<sub>2<sup>m</sup></sub></code>.
         * @param m  The exponent <code>m</code> of
         * <code>F<sub>2<sup>m</sup></sub></code>.
         * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>.
         * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>.
         * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
         * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
         * represents the reduction polynomial <code>f(z)</code>..
         */
		public X9FieldID(
			int m,
			int k1,
			int k2,
			int k3)
		{
			this.id = X9ObjectIdentifiers.CharacteristicTwoField;

			Asn1EncodableVector fieldIdParams = new Asn1EncodableVector(new DerInteger(m));

			if(k2 == 0)
			{
				if(k3 != 0)
					throw new ArgumentException("inconsistent k values");

				fieldIdParams.Add(
					X9ObjectIdentifiers.TPBasis,
					new DerInteger(k1));
			}
			else
			{
				if(k2 <= k1 || k3 <= k2)
					throw new ArgumentException("inconsistent k values");

				fieldIdParams.Add(
					X9ObjectIdentifiers.PPBasis,
					new DerSequence(
						new DerInteger(k1),
						new DerInteger(k2),
						new DerInteger(k3)));
			}

			this.parameters = new DerSequence(fieldIdParams);
		}
Esempio n. 50
0
		/// <summary>
		/// Don't use this one if you are trying to be RFC 3281 compliant.
		/// Use it for v1 attribute certificates only.
		/// </summary>
		/// <param name="names">Our GeneralNames structure</param>
		public AttCertIssuer(
			GeneralNames names)
		{
			obj = names;
			choiceObj = obj.ToAsn1Object();
		}
        public static X509Name GetSubjectX509Principal(X509Certificate cert)
        {
            X509Name subject;

            try
            {
                TbsCertificateStructure instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetTbsCertificate()));
                subject = instance.Subject;
            }
            catch (Exception e)
            {
                throw new CertificateEncodingException("Could not extract subject", e);
            }
            return(subject);
        }
Esempio n. 52
0
		public AttCertIssuer(
            V2Form v2Form)
        {
            obj = v2Form;
            choiceObj = new DerTaggedObject(false, 0, obj);
        }
Esempio n. 53
0
        /**
         * dump a Der object as a formatted string with indentation
         *
         * @param obj the Asn1Object to be dumped out.
         */
        private static void AsString(
            string			indent,
            bool			verbose,
            Asn1Object		obj,
            StringBuilder	buf)
        {
            if (obj is Asn1Sequence)
            {
                string tab = indent + Tab;
                buf.Append(indent);
                if (obj is BerSequence)
                {
                    buf.Append("BER Sequence");
                }
                else if (obj is DerSequence)
                {
                    buf.Append("DER Sequence");
                }
                else
                {
                    buf.Append("Sequence");
                }

                buf.Append(NewLine);

                foreach (Asn1Encodable o in ((Asn1Sequence)obj))
                {
                    if (o == null || o is Asn1Null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        AsString(tab, verbose, o.ToAsn1Object(), buf);
                    }
                }
            }
            else if (obj is DerTaggedObject)
            {
                string tab = indent + Tab;
                buf.Append(indent);
                if (obj is BerTaggedObject)
                {
                    buf.Append("BER Tagged [");
                }
                else
                {
                    buf.Append("Tagged [");
                }

                DerTaggedObject o = (DerTaggedObject)obj;

                buf.Append(((int)o.TagNo).ToString());
                buf.Append(']');

                if (!o.IsExplicit())
                {
                    buf.Append(" IMPLICIT ");
                }

                buf.Append(NewLine);

                if (o.IsEmpty())
                {
                    buf.Append(tab);
                    buf.Append("EMPTY");
                    buf.Append(NewLine);
                }
                else
                {
                    AsString(tab, verbose, o.GetObject(), buf);
                }
            }
            else if (obj is BerSet)
            {
                string tab = indent + Tab;

                buf.Append(indent);
                buf.Append("BER Set");
                buf.Append(NewLine);

                foreach (Asn1Encodable o in ((Asn1Set)obj))
                {
                    if (o == null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        AsString(tab, verbose, o.ToAsn1Object(), buf);
                    }
                }
            }
            else if (obj is DerSet)
            {
                string tab = indent + Tab;

                buf.Append(indent);
                buf.Append("DER Set");
                buf.Append(NewLine);

                foreach (Asn1Encodable o in ((Asn1Set)obj))
                {
                    if (o == null)
                    {
                        buf.Append(tab);
                        buf.Append("NULL");
                        buf.Append(NewLine);
                    }
                    else
                    {
                        AsString(tab, verbose, o.ToAsn1Object(), buf);
                    }
                }
            }
            else if (obj is DerObjectIdentifier)
            {
                buf.Append(indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" + NewLine);
            }
            else if (obj is DerBoolean)
            {
                buf.Append(indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" + NewLine);
            }
            else if (obj is DerInteger)
            {
                buf.Append(indent + "Integer(" + ((DerInteger)obj).Value + ")" + NewLine);
            }
            else if (obj is BerOctetString)
            {
                byte[] octets = ((Asn1OctetString)obj).GetOctets();
                string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
                buf.Append(indent + "BER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
            }
            else if (obj is DerOctetString)
            {
                byte[] octets = ((Asn1OctetString)obj).GetOctets();
                string extra = verbose ? dumpBinaryDataAsString(indent, octets) : "";
                buf.Append(indent + "DER Octet String" + "[" + octets.Length + "] " + extra + NewLine);
            }
            else if (obj is DerBitString)
            {
                DerBitString bt = (DerBitString)obj;
                byte[] bytes = bt.GetBytes();
                string extra = verbose ? dumpBinaryDataAsString(indent, bytes) : "";
                buf.Append(indent + "DER Bit String" + "[" + bytes.Length + ", " + bt.PadBits + "] " + extra + NewLine);
            }
            else if (obj is DerIA5String)
            {
                buf.Append(indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerUtf8String)
            {
                buf.Append(indent + "UTF8String(" + ((DerUtf8String)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerPrintableString)
            {
                buf.Append(indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerVisibleString)
            {
                buf.Append(indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerBmpString)
            {
                buf.Append(indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerT61String)
            {
                buf.Append(indent + "T61String(" + ((DerT61String)obj).GetString() + ") " + NewLine);
            }
            else if (obj is DerUtcTime)
            {
                buf.Append(indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " + NewLine);
            }
            else if (obj is DerGeneralizedTime)
            {
                buf.Append(indent + "GeneralizedTime(" + ((DerGeneralizedTime)obj).GetTime() + ") " + NewLine);
            }
            else if (obj is BerApplicationSpecific)
            {
                buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj));
            }
            else if (obj is DerApplicationSpecific)
            {
                buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj));
            }
            else if (obj is DerEnumerated)
            {
                DerEnumerated en = (DerEnumerated)obj;
                buf.Append(indent + "DER Enumerated(" + en.Value + ")" + NewLine);
            }
            else if (obj is DerExternal)
            {
                DerExternal ext = (DerExternal)obj;
                buf.Append(indent + "External " + NewLine);
                string tab = indent + Tab;

                if (ext.DirectReference != null)
                {
                    buf.Append(tab + "Direct Reference: " + ext.DirectReference.Id + NewLine);
                }
                if (ext.IndirectReference != null)
                {
                    buf.Append(tab + "Indirect Reference: " + ext.IndirectReference.ToString() + NewLine);
                }
                if (ext.DataValueDescriptor != null)
                {
                    AsString(tab, verbose, ext.DataValueDescriptor, buf);
                }
                buf.Append(tab + "Encoding: " + ext.Encoding + NewLine);
                AsString(tab, verbose, ext.ExternalContent, buf);
            }
            else
            {
                buf.Append(indent + obj.ToString() + NewLine);
            }
        }
 internal static void CheckCrls(IX509AttributeCertificate attrCert, PkixParameters paramsPKIX, X509Certificate issuerCert, global::System.DateTime validDate, global::System.Collections.IList certPathCerts)
 {
     if (!paramsPKIX.IsRevocationEnabled)
     {
         return;
     }
     if (attrCert.GetExtensionValue(X509Extensions.NoRevAvail) == null)
     {
         CrlDistPoint crlDistPoint = null;
         try
         {
             crlDistPoint = CrlDistPoint.GetInstance(PkixCertPathValidatorUtilities.GetExtensionValue(attrCert, X509Extensions.CrlDistributionPoints));
         }
         catch (global::System.Exception cause)
         {
             throw new PkixCertPathValidatorException("CRL distribution point extension could not be read.", cause);
         }
         try
         {
             PkixCertPathValidatorUtilities.AddAdditionalStoresFromCrlDistributionPoint(crlDistPoint, paramsPKIX);
         }
         catch (global::System.Exception cause2)
         {
             throw new PkixCertPathValidatorException("No additional CRL locations could be decoded from CRL distribution point extension.", cause2);
         }
         CertStatus  certStatus          = new CertStatus();
         ReasonsMask reasonsMask         = new ReasonsMask();
         global::System.Exception cause3 = null;
         bool flag = false;
         if (crlDistPoint != null)
         {
             DistributionPoint[] array = null;
             try
             {
                 array = crlDistPoint.GetDistributionPoints();
             }
             catch (global::System.Exception cause4)
             {
                 throw new PkixCertPathValidatorException("Distribution points could not be read.", cause4);
             }
             try
             {
                 for (int i = 0; i < array.Length; i++)
                 {
                     if (certStatus.Status != 11)
                     {
                         break;
                     }
                     if (reasonsMask.IsAllReasons)
                     {
                         break;
                     }
                     PkixParameters paramsPKIX2 = (PkixParameters)paramsPKIX.Clone();
                     CheckCrl(array[i], attrCert, paramsPKIX2, validDate, issuerCert, certStatus, reasonsMask, certPathCerts);
                     flag = true;
                 }
             }
             catch (global::System.Exception ex)
             {
                 cause3 = new global::System.Exception("No valid CRL for distribution point found.", ex);
             }
         }
         if (certStatus.Status == 11 && !reasonsMask.IsAllReasons)
         {
             try
             {
                 Asn1Object asn1Object = null;
                 try
                 {
                     asn1Object = new Asn1InputStream(attrCert.Issuer.GetPrincipals()[0].GetEncoded()).ReadObject();
                 }
                 catch (global::System.Exception ex2)
                 {
                     throw new global::System.Exception("Issuer from certificate for CRL could not be reencoded.", ex2);
                 }
                 DistributionPoint dp          = new DistributionPoint(new DistributionPointName(0, new GeneralNames(new GeneralName(4, asn1Object))), null, null);
                 PkixParameters    paramsPKIX3 = (PkixParameters)paramsPKIX.Clone();
                 CheckCrl(dp, attrCert, paramsPKIX3, validDate, issuerCert, certStatus, reasonsMask, certPathCerts);
                 flag = true;
             }
             catch (global::System.Exception ex3)
             {
                 cause3 = new global::System.Exception("No valid CRL for distribution point found.", ex3);
             }
         }
         if (!flag)
         {
             throw new PkixCertPathValidatorException("No valid CRL found.", cause3);
         }
         if (certStatus.Status != 11)
         {
             string text  = certStatus.RevocationDate.Value.ToString("ddd MMM dd HH:mm:ss K yyyy");
             string text2 = "Attribute certificate revocation after " + text;
             text2 = text2 + ", reason: " + Rfc3280CertPathUtilities.CrlReasons[certStatus.Status];
             throw new PkixCertPathValidatorException(text2);
         }
         if (!reasonsMask.IsAllReasons && certStatus.Status == 11)
         {
             certStatus.Status = 12;
         }
         if (certStatus.Status == 12)
         {
             throw new PkixCertPathValidatorException("Attribute certificate status could not be determined.");
         }
     }
     else if (attrCert.GetExtensionValue(X509Extensions.CrlDistributionPoints) != null || attrCert.GetExtensionValue(X509Extensions.AuthorityInfoAccess) != null)
     {
         throw new PkixCertPathValidatorException("No rev avail extension is set, but also an AC revocation pointer.");
     }
 }
Esempio n. 55
0
 public RecipientIdentifier(
     Asn1Object id)
 {
     this.id = id;
 }
Esempio n. 56
0
 public Pkcs10CertificationRequest(
     byte[] encoded)
     : base((Asn1Sequence)Asn1Object.FromByteArray(encoded))
 {
 }
Esempio n. 57
0
 public Pkcs10CertificationRequest(
     Stream input)
     : base((Asn1Sequence)Asn1Object.FromStream(input))
 {
 }
Esempio n. 58
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[Platform.ToUpperInvariant(algorithm)];

            byte[] keyBytes       = null;
            byte[] salt           = null;
            int    iterationCount = 0;

            if (IsPkcs12(mechanism))
            {
                Pkcs12PbeParams pbeParams = Pkcs12PbeParams.GetInstance(pbeParameters);
                salt           = pbeParams.GetIV();
                iterationCount = pbeParams.Iterations.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs12PasswordToBytes(password, wrongPkcs12Zero);
            }
            else if (IsPkcs5Scheme2(mechanism))
            {
                // See below
            }
            else
            {
                PbeParameter pbeParams = PbeParameter.GetInstance(pbeParameters);
                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);
            }

            ICipherParameters parameters = null;

            if (IsPkcs5Scheme2(mechanism))
            {
                PbeS2Parameters     s2p       = PbeS2Parameters.GetInstance(pbeParameters.ToAsn1Object());
                AlgorithmIdentifier encScheme = s2p.EncryptionScheme;
                DerObjectIdentifier encOid    = encScheme.Algorithm;
                Asn1Object          encParams = encScheme.Parameters.ToAsn1Object();

                Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object());
                IDigest      digest    = DigestUtilities.GetDigest(pbeParams.Prf.Algorithm);

                byte[] iv;
                if (encOid.Equals(PkcsObjectIdentifiers.RC2Cbc)) // PKCS5.B.2.3
                {
                    RC2CbcParameter rc2Params = RC2CbcParameter.GetInstance(encParams);
                    iv = rc2Params.GetIV();
                }
                else
                {
                    iv = Asn1OctetString.GetInstance(encParams).GetOctets();
                }

                salt           = pbeParams.GetSalt();
                iterationCount = pbeParams.IterationCount.IntValue;
                keyBytes       = PbeParametersGenerator.Pkcs5PasswordToBytes(password);

                int keyLength = pbeParams.KeyLength != null
                    ?   pbeParams.KeyLength.IntValue * 8
                    :   GeneratorUtilities.GetDefaultKeySize(encOid);

                PbeParametersGenerator gen = MakePbeGenerator(
                    (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount);

                parameters = gen.GenerateDerivedParameters(encOid.Id, keyLength);

                if (iv != null)
                {
                    // FIXME? OpenSSL weirdness with IV of zeros (for ECB keys?)
                    if (Arrays.AreEqual(iv, new byte[iv.Length]))
                    {
                        //Console.Error.Write("***** IV all 0 (length " + iv.Length + ") *****");
                    }
                    else
                    {
                        parameters = new ParametersWithIV(parameters, iv);
                    }
                }
            }
            else if (Platform.StartsWith(mechanism, "PBEwithSHA-1"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-1and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 128);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC4"))
                {
                    parameters = generator.GenerateDerivedParameters("RC4", 40);
                }
                else if (mechanism.Equals("PBEwithSHA-1and3-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 192, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and2-keyDESEDE-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DESEDE", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and128bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 128, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1and40bitRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 40, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithSHA-1andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (Platform.StartsWith(mechanism, "PBEwithSHA-256"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha256Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithSHA-256and128bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and192bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithSHA-256and256bitAES-CBC-BC"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (Platform.StartsWith(mechanism, "PBEwithMD5"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD5Digest(), keyBytes, salt, iterationCount);

                if (mechanism.Equals("PBEwithMD5andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD5and128bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 128, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and192bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 192, 128);
                }
                else if (mechanism.Equals("PBEwithMD5and256bitAES-CBC-OpenSSL"))
                {
                    parameters = generator.GenerateDerivedParameters("AES", 256, 128);
                }
            }
            else if (Platform.StartsWith(mechanism, "PBEwithMD2"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new MD2Digest(), keyBytes, salt, iterationCount);
                if (mechanism.Equals("PBEwithMD2andDES-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("DES", 64, 64);
                }
                else if (mechanism.Equals("PBEwithMD2andRC2-CBC"))
                {
                    parameters = generator.GenerateDerivedParameters("RC2", 64, 64);
                }
            }
            else if (Platform.StartsWith(mechanism, "PBEwithHmac"))
            {
                string  digestName = mechanism.Substring("PBEwithHmac".Length);
                IDigest digest     = DigestUtilities.GetDigest(digestName);

                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], digest, keyBytes, salt, iterationCount);

                int bitLen = digest.GetDigestSize() * 8;
                parameters = generator.GenerateDerivedMacParameters(bitLen);
            }

            Array.Clear(keyBytes, 0, keyBytes.Length);

            return(FixDesParity(mechanism, parameters));
        }
        /// <summary>
        ///     Generates the certificate.
        /// </summary>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="issuerName">Name of the issuer.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="keyStrength">The key strength.</param>
        /// <param name="signatureAlgorithm">The signature algorithm.</param>
        /// <param name="issuerPrivateKey">The issuer private key.</param>
        /// <param name="hostName">The host name</param>
        /// <returns>X509Certificate2 instance.</returns>
        /// <exception cref="PemException">Malformed sequence in RSA private key</exception>
        private static X509Certificate2 generateCertificate(string hostName,
                                                            string subjectName,
                                                            string issuerName, DateTime validFrom,
                                                            DateTime validTo, int keyStrength       = 2048,
                                                            string signatureAlgorithm               = "SHA256WithRSA",
                                                            AsymmetricKeyParameter issuerPrivateKey = null)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

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

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

            certificateGenerator.SetNotBefore(validFrom);
            certificateGenerator.SetNotAfter(validTo);

            if (hostName != null)
            {
                // add subject alternative names
                var subjectAlternativeNames = new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, hostName) };

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

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

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Set certificate intended purposes to only Server Authentication
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));
            if (issuerPrivateKey == null)
            {
                certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true));
            }

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm,
                                                            issuerPrivateKey ?? subjectKeyPair.Private, secureRandom);

            // Self-sign the certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // Corresponding private key
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

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

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

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

#if NET45
            // Set private key onto certificate instance
            var x509Certificate = new X509Certificate2(certificate.GetEncoded());
            x509Certificate.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
#else
            var x509Certificate = withPrivateKey(certificate, rsaparams);
#endif

            if (!doNotSetFriendlyName)
            {
                try
                {
                    x509Certificate.FriendlyName = ProxyConstants.CNRemoverRegex.Replace(subjectName, string.Empty);
                }
                catch (PlatformNotSupportedException)
                {
                    doNotSetFriendlyName = true;
                }
            }

            return(x509Certificate);
        }
Esempio n. 60
0
        /**
         * dump a Der object as a formatted string with indentation
         *
         * @param obj the Asn1Object to be dumped out.
         */
        private static string AsString(
            string		indent,
            Asn1Object	obj)
        {
            if (obj is Asn1Sequence)
            {
                StringBuilder    Buffer = new StringBuilder();
                string          tab = indent + TAB;

                Buffer.Append(indent);
                if (obj is DerSequence)
                {
                    Buffer.Append("DER Sequence");
                }
                else if (obj is BerSequence)
                {
                    Buffer.Append("BER Sequence");
                }
                else
                {
                    Buffer.Append("Sequence");
                }

                Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                );

                foreach (object o in ((Asn1Sequence)obj))
                {
                    if (o == null || o.Equals(DerNull.Instance))
                    {
                        Buffer.Append(tab);
                        Buffer.Append("Null");
                        Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                            Environment.NewLine
            #else
                            EnvironmentEx.NewLine
            #endif
                        );
                    }
                    else if (o is Asn1Object)
                    {
                        Buffer.Append(AsString(tab, (Asn1Object)o));
                    }
                    else
                    {
                        Buffer.Append(AsString(tab, ((Asn1Encodable)o).ToAsn1Object()));
                    }
                }
                return Buffer.ToString();
            }
            else if (obj is DerTaggedObject)
            {
                StringBuilder Buffer = new StringBuilder();
                string tab = indent + TAB;

                Buffer.Append(indent);
                if (obj is BerTaggedObject)
                {
                    Buffer.Append("BER Tagged [");
                }
                else
                {
                    Buffer.Append("Tagged [");
                }

                DerTaggedObject o = (DerTaggedObject)obj;

                Buffer.Append(((int)o.TagNo).ToString());
                Buffer.Append(']');

                if (!o.IsExplicit())
                {
                    Buffer.Append(" IMPLICIT ");
                }

                Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                );

                if (o.IsEmpty())
                {
                    Buffer.Append(tab);
                    Buffer.Append("EMPTY");
                    Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                        Environment.NewLine
            #else
                        EnvironmentEx.NewLine
            #endif
                    );
                }
                else
                {
                    Buffer.Append(AsString(tab, o.GetObject()));
                }

                return Buffer.ToString();
            }
            else if (obj is BerSet)
            {
                StringBuilder Buffer = new StringBuilder();
                string tab = indent + TAB;

                Buffer.Append(indent);
                Buffer.Append("BER Set");
                Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                );

                foreach (object o in ((Asn1Set)obj))
                {
                    if (o == null)
                    {
                        Buffer.Append(tab);
                        Buffer.Append("Null");
                        Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                            Environment.NewLine
            #else
                            EnvironmentEx.NewLine
            #endif
                        );
                    }
                    else if (o is Asn1Object)
                    {
                        Buffer.Append(AsString(tab, (Asn1Object)o));
                    }
                    else
                    {
                        Buffer.Append(AsString(tab, ((Asn1Encodable)o).ToAsn1Object()));
                    }
                }
                return Buffer.ToString();
            }
            else if (obj is DerSet)
            {
                StringBuilder Buffer = new StringBuilder();
                string tab = indent + TAB;

                Buffer.Append(indent);
                Buffer.Append("DER Set");
                Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                );

                foreach (object o in ((Asn1Set)obj))
                {
                    if (o == null)
                    {
                        Buffer.Append(tab);
                        Buffer.Append("Null");
                        Buffer.Append(
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                            Environment.NewLine
            #else
                            EnvironmentEx.NewLine
            #endif
                        );
                    }
                    else if (o is Asn1Object)
                    {
                        Buffer.Append(AsString(tab, (Asn1Object)o));
                    }
                    else
                    {
                        Buffer.Append(AsString(tab, ((Asn1Encodable)o).ToAsn1Object()));
                    }
                }

                return Buffer.ToString();
            }
            else if (obj is DerObjectIdentifier)
            {
                return indent + "ObjectIdentifier(" + ((DerObjectIdentifier)obj).Id + ")" +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerBoolean)
            {
                return indent + "Boolean(" + ((DerBoolean)obj).IsTrue + ")" +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerInteger)
            {
                return indent + "Integer(" + ((DerInteger)obj).Value + ")" +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerOctetString)
            {
                return indent + obj.ToString() + "[" + ((Asn1OctetString)obj).GetOctets().Length + "] " +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerIA5String)
            {
                return indent + "IA5String(" + ((DerIA5String)obj).GetString() + ") " +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerPrintableString)
            {
                return indent + "PrintableString(" + ((DerPrintableString)obj).GetString() + ") " +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerVisibleString)
            {
                return indent + "VisibleString(" + ((DerVisibleString)obj).GetString() + ") " +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerBmpString)
            {
                return indent + "BMPString(" + ((DerBmpString)obj).GetString() + ") " +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerT61String)
            {
                return indent + "T61String(" + ((DerT61String)obj).GetString() + ") " +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerUtcTime)
            {
                return indent + "UTCTime(" + ((DerUtcTime)obj).TimeString + ") " +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
            else if (obj is DerUnknownTag)
            {
                // MASC 20070308. CF compatibility patch
                byte[] hex = Hex.Encode(((DerUnknownTag)obj).GetData());
                return indent + "Unknown " + ((int)((DerUnknownTag)obj).Tag).ToString("X") + " "
                    + Encoding.ASCII.GetString(hex,0,hex.Length) +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                        Environment.NewLine
            #else
                        EnvironmentEx.NewLine
            #endif
                ;
            }
            else
            {
                return indent + obj.ToString() +
            // MASC 20070308. CF compatibility patch
            #if !NETCF
                    Environment.NewLine
            #else
                    EnvironmentEx.NewLine
            #endif
                ;
            }
        }