public override void PerformTest()
		{
			DerUtf8String contentDescription = new DerUtf8String("Description");
			DerObjectIdentifier contentType = new DerObjectIdentifier("1.2.2.3");

			ContentHints hints = new ContentHints(contentType);

			checkConstruction(hints, contentType, null);

			hints = new ContentHints(contentType, contentDescription);

			checkConstruction(hints, contentType, contentDescription);

			hints = ContentHints.GetInstance(null);

			if (hints != null)
			{
				Fail("null GetInstance() failed.");
			}

			try
			{
				ContentHints.GetInstance(new Object());

				Fail("GetInstance() failed to detect bad object.");
			}
			catch (ArgumentException)
			{
				// expected
			}
		}
Example #2
0
		public CertBag(
            DerObjectIdentifier	certID,
            Asn1Object			certValue)
        {
            this.certID = certID;
            this.certValue = certValue;
        }
 public AttributeTypeAndValue(
     DerObjectIdentifier type,
     Asn1Encodable value)
 {
     this.type = type;
     this.value = value;
 }
Example #4
0
		public KeySpecificInfo(
            DerObjectIdentifier	algorithm,
            Asn1OctetString		counter)
        {
            this.algorithm = algorithm;
            this.counter = counter;
        }
Example #5
0
		public AlgorithmIdentifier(
            DerObjectIdentifier	objectID,
            Asn1Encodable		parameters)
        {
            this.objectID = objectID;
            this.parameters = parameters;
        }
		public EncryptedContentInfoParser(
			Asn1SequenceParser seq)
		{
			_contentType = (DerObjectIdentifier)seq.ReadObject();
			_contentEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(seq.ReadObject().ToAsn1Object());
			_encryptedContent = (Asn1TaggedObjectParser)seq.ReadObject();
		}
Example #7
0
 public ContentInfo(
     DerObjectIdentifier	contentType,
     Asn1Encodable		content)
 {
     this.contentType = contentType;
     this.content = content;
 }
		public OtherKeyAttribute(
            DerObjectIdentifier	keyAttrId,
            Asn1Encodable		keyAttr)
        {
            this.keyAttrId = keyAttrId;
            this.keyAttr = keyAttr;
        }
Example #9
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);
		}
		public SigPolicyQualifierInfo(
			DerObjectIdentifier	sigPolicyQualifierId,
			Asn1Encodable		sigQualifier)
		{
			this.sigPolicyQualifierId = sigPolicyQualifierId;
			this.sigQualifier = sigQualifier.ToAsn1Object();
		}
		public SemanticsInformation(
			Asn1Sequence seq)
        {
            if (seq.Count < 1)
            {
                throw new ArgumentException("no objects in SemanticsInformation");
            }

			IEnumerator e = seq.GetEnumerator();
			e.MoveNext();
            object obj = e.Current;
            if (obj is DerObjectIdentifier)
            {
                semanticsIdentifier = DerObjectIdentifier.GetInstance(obj);
                if (e.MoveNext())
                {
                    obj  = e.Current;
                }
                else
                {
                    obj  = null;
                }
            }

			if (obj  != null)
            {
                Asn1Sequence generalNameSeq = Asn1Sequence.GetInstance(obj );
                nameRegistrationAuthorities = new GeneralName[generalNameSeq.Count];
                for (int i= 0; i < generalNameSeq.Count; i++)
                {
                    nameRegistrationAuthorities[i] = GeneralName.GetInstance(generalNameSeq[i]);
                }
            }
        }
 public InfoTypeAndValue(
     DerObjectIdentifier infoType,
     Asn1Encodable       optionalValue)
 {
     this.infoType = infoType;
     this.infoValue = optionalValue;
 }
		public SemanticsInformation(
            DerObjectIdentifier semanticsIdentifier,
            GeneralName[] generalNames)
        {
            this.semanticsIdentifier = semanticsIdentifier;
            this.nameRegistrationAuthorities = generalNames;
        }
 public PolicyInformation(
     DerObjectIdentifier	policyIdentifier,
     Asn1Sequence		policyQualifiers)
 {
     this.policyIdentifier = policyIdentifier;
     this.policyQualifiers = policyQualifiers;
 }
Example #15
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);
		}
 public OtherRecipientInfo(
     DerObjectIdentifier	oriType,
     Asn1Encodable		oriValue)
 {
     this.oriType = oriType;
     this.oriValue = oriValue;
 }
		/**
		 * create an AccessDescription with the oid and location provided.
		 */
		public AccessDescription(
			DerObjectIdentifier	oid,
			GeneralName			location)
		{
			accessMethod = oid;
			accessLocation = location;
		}
Example #18
0
 public QCStatement(
     DerObjectIdentifier qcStatementId,
     Asn1Encodable       qcStatementInfo)
 {
     this.qcStatementId = qcStatementId;
     this.qcStatementInfo = qcStatementInfo;
 }
        /**
         * Creates a new <code>PolicyQualifierInfo</code> instance.
         *
         * @param policyQualifierId a <code>PolicyQualifierId</code> value
         * @param qualifier the qualifier, defined by the above field.
         */
        public PolicyQualifierInfo(
			DerObjectIdentifier	policyQualifierId,
			Asn1Encodable		qualifier)
        {
            this.policyQualifierId = policyQualifierId;
            this.qualifier = qualifier;
        }
        /**
         * Apply default conversion for the given value depending on the oid
         * and the character range of the value.
         *
         * @param oid the object identifier for the DN entry
         * @param value the value associated with it
         * @return the ASN.1 equivalent for the string value.
         */
        public override Asn1Object GetConvertedValue(
            DerObjectIdentifier	oid,
            string				value)
        {
            if (value.Length != 0 && value[0] == '#')
            {
                try
                {
                    return ConvertHexEncoded(value, 1);
                }
                catch (IOException)
                {
                    throw new Exception("can't recode value for oid " + oid.Id);
                }
            }

            if (oid.Equals(X509Name.EmailAddress) || oid.Equals(X509Name.DC))
            {
                return new DerIA5String(value);
            }

            if (oid.Equals(X509Name.DateOfBirth)) // accept time string as well as # (for compatibility)
            {
                return new DerGeneralizedTime(value);
            }

            if (oid.Equals(X509Name.C)
                || oid.Equals(X509Name.SerialNumber)
                || oid.Equals(X509Name.DnQualifier))
            {
                return new DerPrintableString(value);
            }

            return new DerUtf8String(value);
        }
Example #21
0
		public ContentHints(
			DerObjectIdentifier	contentType,
			DerUtf8String		contentDescription)
		{
			this.contentType = contentType;
			this.contentDescription = contentDescription;
		}
 public AlgorithmIdentifier(
     DerObjectIdentifier algorithm,
     Asn1Encodable		parameters)
 {
     this.algorithm = algorithm;
     this.parameters = parameters;
 }
Example #23
0
		public Attribute(
            DerObjectIdentifier attrType,
            Asn1Set             attrValues)
        {
            this.attrType = attrType;
            this.attrValues = attrValues;
        }
        /**
        * return the X9ECParameters object for the named curve represented by
        * the passed in object identifier. Null if the curve isn't present.
        *
        * @param oid an object identifier representing a named curve, if present.
        */
        public static X9ECParameters GetByOid(
			DerObjectIdentifier oid)
        {
            X9ECParametersHolder holder = (X9ECParametersHolder) curves[oid];

            return holder == null ? null : holder.Parameters;
        }
 public OtherRevocationInfoFormat(
     DerObjectIdentifier otherRevInfoFormat,
     Asn1Encodable otherRevInfo)
 {
     this.otherRevInfoFormat = otherRevInfoFormat;
     this.otherRevInfo = otherRevInfo;
 }
		private void checkValues(
			ContentHints		hints,
			DerObjectIdentifier	contentType,
			DerUtf8String		description)
		{
			checkMandatoryField("contentType", contentType, hints.ContentType);
			checkOptionalField("description", description, hints.ContentDescription);
		}
Example #27
0
		private ResponseBytes(
            Asn1Sequence seq)
        {
			if (seq.Count != 2)
				throw new ArgumentException("Wrong number of elements in sequence", "seq");

			this.responseType = DerObjectIdentifier.GetInstance(seq[0]);
            this.response = Asn1OctetString.GetInstance(seq[1]);
        }
        /**
         * Creates a new <code>PolicyQualifierInfo</code> instance.
         *
         * @param as <code>PolicyQualifierInfo</code> X509 structure
         * encoded as an Asn1Sequence.
         */
        private PolicyQualifierInfo(
			Asn1Sequence seq)
        {
            if (seq.Count != 2)
                throw new ArgumentException("Bad sequence size: " + seq.Count, "seq");

            policyQualifierId = DerObjectIdentifier.GetInstance(seq[0]);
            qualifier = seq[1];
        }
        private InfoTypeAndValue(Asn1Sequence seq)
        {
            infoType = DerObjectIdentifier.GetInstance(seq[0]);

            if (seq.Count > 1)
            {
                infoValue = (Asn1Encodable)seq[1];
            }
        }
		private AccessDescription(
			Asn1Sequence seq)
		{
			if (seq.Count != 2)
				throw new ArgumentException("wrong number of elements in sequence");

			accessMethod = DerObjectIdentifier.GetInstance(seq[0]);
			accessLocation = GeneralName.GetInstance(seq[1]);
		}
Example #31
0
 public static KeyParameter CreateKeyParameter(
     DerObjectIdentifier algOid,
     byte[]                              keyBytes)
 {
     return(CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length));
 }
Example #32
0
 internal static int GetDefaultKeySize(
     DerObjectIdentifier oid)
 {
     return(GetDefaultKeySize(oid.Id));
 }
Example #33
0
        public static AsymmetricKeyParameter CreateKey(
            PrivateKeyInfo keyInfo)
        {
            AlgorithmIdentifier algID  = keyInfo.PrivateKeyAlgorithm;
            DerObjectIdentifier algOid = algID.Algorithm;

            // TODO See RSAUtil.isRsaOid in Java build
            if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) ||
                algOid.Equals(X509ObjectIdentifiers.IdEARsa) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) ||
                algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep))
            {
                RsaPrivateKeyStructure keyStructure = RsaPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());

                return(new RsaPrivateCrtKeyParameters(
                           keyStructure.Modulus,
                           keyStructure.PublicExponent,
                           keyStructure.PrivateExponent,
                           keyStructure.Prime1,
                           keyStructure.Prime2,
                           keyStructure.Exponent1,
                           keyStructure.Exponent2,
                           keyStructure.Coefficient));
            }
            // TODO?
            //			else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber))
            else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement))
            {
                DHParameter para = new DHParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                BigInteger   lVal     = para.L;
                int          l        = lVal == null ? 0 : lVal.IntValue;
                DHParameters dhParams = new DHParameters(para.P, para.G, null, l);

                return(new DHPrivateKeyParameters(derX.Value, dhParams, algOid));
            }
            else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm))
            {
                ElGamalParameter para = new ElGamalParameter(
                    Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()));
                DerInteger derX = (DerInteger)keyInfo.ParsePrivateKey();

                return(new ElGamalPrivateKeyParameters(
                           derX.Value,
                           new ElGamalParameters(para.P, para.G)));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdDsa))
            {
                DerInteger    derX = (DerInteger)keyInfo.ParsePrivateKey();
                Asn1Encodable ae   = algID.Parameters;

                DsaParameters parameters = null;
                if (ae != null)
                {
                    DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object());
                    parameters = new DsaParameters(para.P, para.Q, para.G);
                }

                return(new DsaPrivateKeyParameters(derX.Value, parameters));
            }
            else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey))
            {
                X962Parameters para = X962Parameters.GetInstance(algID.Parameters.ToAsn1Object());

                X9ECParameters x9;
                if (para.IsNamedCurve)
                {
                    x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters);
                }
                else
                {
                    x9 = new X9ECParameters((Asn1Sequence)para.Parameters);
                }

                ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(keyInfo.ParsePrivateKey());
                BigInteger            d  = ec.GetKey();

                if (para.IsNamedCurve)
                {
                    return(new ECPrivateKeyParameters("EC", d, (DerObjectIdentifier)para.Parameters));
                }

                ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed());
                return(new ECPrivateKeyParameters(d, dParams));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(
                    algID.Parameters.ToAsn1Object());

                ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                if (ecP == null)
                {
                    throw new ArgumentException("Unrecognized curve OID for GostR3410x2001 private key");
                }

                Asn1Object            privKey = keyInfo.ParsePrivateKey();
                ECPrivateKeyStructure ec;

                if (privKey is DerInteger)
                {
                    ec = new ECPrivateKeyStructure(ecP.N.BitLength, ((DerInteger)privKey).PositiveValue);
                }
                else
                {
                    ec = ECPrivateKeyStructure.GetInstance(privKey);
                }

                return(new ECPrivateKeyParameters("ECGOST3410", ec.GetKey(), gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(algID.Parameters);

                Asn1Object privKey = keyInfo.ParsePrivateKey();
                BigInteger x;

                if (privKey is DerInteger)
                {
                    x = DerInteger.GetInstance(privKey).PositiveValue;
                }
                else
                {
                    x = new BigInteger(1, Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets()));
                }

                return(new Gost3410PrivateKeyParameters(x, gostParams.PublicKeyParamSet));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X25519))
            {
                return(new X25519PrivateKeyParameters(GetRawKey(keyInfo, X25519PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_X448))
            {
                return(new X448PrivateKeyParameters(GetRawKey(keyInfo, X448PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed25519))
            {
                return(new Ed25519PrivateKeyParameters(GetRawKey(keyInfo, Ed25519PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(EdECObjectIdentifiers.id_Ed448))
            {
                return(new Ed448PrivateKeyParameters(GetRawKey(keyInfo, Ed448PrivateKeyParameters.KeySize), 0));
            }
            else if (algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512) ||
                     algOid.Equals(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256))
            {
                Gost3410PublicKeyAlgParameters gostParams = Gost3410PublicKeyAlgParameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters);
                ECGost3410Parameters           ecSpec     = null;
                BigInteger d = null;
                Asn1Object p = keyInfo.PrivateKeyAlgorithm.Parameters.ToAsn1Object();
                if (p is Asn1Sequence && (Asn1Sequence.GetInstance(p).Count == 2 || Asn1Sequence.GetInstance(p).Count == 3))
                {
                    ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet);

                    ecSpec = new ECGost3410Parameters(
                        new ECNamedDomainParameters(
                            gostParams.PublicKeyParamSet, ecP),
                        gostParams.PublicKeyParamSet,
                        gostParams.DigestParamSet,
                        gostParams.EncryptionParamSet);
                    Asn1Encodable privKey = keyInfo.ParsePrivateKey();
                    if (privKey is DerInteger)
                    {
                        d = DerInteger.GetInstance(privKey).PositiveValue;
                    }
                    else
                    {
                        byte[] dVal = Arrays.Reverse(Asn1OctetString.GetInstance(privKey).GetOctets());
                        d = new BigInteger(1, dVal);
                    }
                }
                else
                {
                    X962Parameters parameters = X962Parameters.GetInstance(keyInfo.PrivateKeyAlgorithm.Parameters);

                    if (parameters.IsNamedCurve)
                    {
                        DerObjectIdentifier oid = DerObjectIdentifier.GetInstance(parameters.Parameters);
                        X9ECParameters      ecP = ECNamedCurveTable.GetByOid(oid);
                        if (ecP == null)
                        {
                            ECDomainParameters gParam = ECGost3410NamedCurves.GetByOid(oid);
                            ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(
                                                                  oid,
                                                                  gParam.Curve,
                                                                  gParam.G,
                                                                  gParam.N,
                                                                  gParam.H,
                                                                  gParam.GetSeed()), gostParams.PublicKeyParamSet, gostParams.DigestParamSet,
                                                              gostParams.EncryptionParamSet);
                        }
                        else
                        {
                            ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(
                                                                  oid,
                                                                  ecP.Curve,
                                                                  ecP.G,
                                                                  ecP.N,
                                                                  ecP.H,
                                                                  ecP.GetSeed()), gostParams.PublicKeyParamSet, gostParams.DigestParamSet,
                                                              gostParams.EncryptionParamSet);
                        }
                    }
                    else if (parameters.IsImplicitlyCA)
                    {
                        ecSpec = null;
                    }
                    else
                    {
                        X9ECParameters ecP = X9ECParameters.GetInstance(parameters.Parameters);
                        ecSpec = new ECGost3410Parameters(new ECNamedDomainParameters(
                                                              algOid,
                                                              ecP.Curve,
                                                              ecP.G,
                                                              ecP.N,
                                                              ecP.H,
                                                              ecP.GetSeed()),
                                                          gostParams.PublicKeyParamSet,
                                                          gostParams.DigestParamSet,
                                                          gostParams.EncryptionParamSet);
                    }

                    Asn1Encodable privKey = keyInfo.ParsePrivateKey();
                    if (privKey is DerInteger)
                    {
                        DerInteger derD = DerInteger.GetInstance(privKey);
                        d = derD.Value;
                    }
                    else
                    {
                        ECPrivateKeyStructure ec = ECPrivateKeyStructure.GetInstance(privKey);
                        d = ec.GetKey();
                    }
                }

                return(new ECPrivateKeyParameters(
                           d,
                           new ECGost3410Parameters(
                               ecSpec,
                               gostParams.PublicKeyParamSet,
                               gostParams.DigestParamSet,
                               gostParams.EncryptionParamSet)));
            }
            else
            {
                throw new SecurityUtilityException("algorithm identifier in private key not recognised");
            }
        }
Example #34
0
        /**
         * base constructor
         *
         * @param signedContent the content that was signed.
         * @param sigData the signature object.
         */
        public CmsSignedDataParser(
            CmsTypedStream signedContent,
            Stream sigData)
            : base(sigData)
        {
            try
            {
                this._signedContent = signedContent;
                this._signedData    = SignedDataParser.GetInstance(this.contentInfo.GetContent(Asn1Tags.Sequence));
                this._digests       = Platform.CreateHashtable();
                this._digestOids    = new HashSet();

                Asn1SetParser    digAlgs = _signedData.GetDigestAlgorithms();
                IAsn1Convertible o;

                while ((o = digAlgs.ReadObject()) != null)
                {
                    AlgorithmIdentifier id = AlgorithmIdentifier.GetInstance(o.ToAsn1Object());

                    try
                    {
                        string digestOid  = id.ObjectID.Id;
                        string digestName = Helper.GetDigestAlgName(digestOid);

                        if (!this._digests.Contains(digestName))
                        {
                            this._digests[digestName] = Helper.GetDigestInstance(digestName);
                            this._digestOids.Add(digestOid);
                        }
                    }
                    catch (SecurityUtilityException)
                    {
                        // TODO Should do something other than ignore it
                    }
                }

                //
                // If the message is simply a certificate chain message GetContent() may return null.
                //
                ContentInfoParser     cont = _signedData.GetEncapContentInfo();
                Asn1OctetStringParser octs = (Asn1OctetStringParser)
                                             cont.GetContent(Asn1Tags.OctetString);

                if (octs != null)
                {
                    CmsTypedStream ctStr = new CmsTypedStream(
                        cont.ContentType.Id, octs.GetOctetStream());

                    if (_signedContent == null)
                    {
                        this._signedContent = ctStr;
                    }
                    else
                    {
                        //
                        // content passed in, need to read past empty encapsulated content info object if present
                        //
                        ctStr.Drain();
                    }
                }

                _signedContentType = _signedContent == null
                                        ?       cont.ContentType
                                        :       new DerObjectIdentifier(_signedContent.ContentType);
            }
            catch (IOException e)
            {
                throw new CmsException("io exception: " + e.Message, e);
            }
        }
 /**
  * return the GOST3410ParamSetParameters object for the given OID, null if it
  * isn't present.
  *
  * @param oid an object identifier representing a named parameters, if present.
  */
 public static Gost3410ParamSetParameters GetByOid(
     DerObjectIdentifier oid)
 {
     return((Gost3410ParamSetParameters)parameters[oid]);
 }
Example #36
0
 public override string OidToDisplayName(DerObjectIdentifier oid)
 {
     return((string)DefaultSymbols[oid]);
 }
 public static IBufferedCipher GetCipher(
     DerObjectIdentifier oid)
 {
     return(GetCipher(oid.Id));
 }
Example #38
0
 public void AddCapability(
     DerObjectIdentifier capability,
     int value)
 {
     capabilities.Add(new DerSequence(capability, new DerInteger(value)));
 }
Example #39
0
 public void AddCapability(
     DerObjectIdentifier capability,
     Asn1Encodable parameters)
 {
     capabilities.Add(new DerSequence(capability, parameters));
 }
Example #40
0
 public static Asn1Encodable GenerateParameters(
     DerObjectIdentifier algID,
     SecureRandom random)
 {
     return(GenerateParameters(algID.Id, random));
 }
 /**
  * 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);
 }
Example #42
0
 /**
  * return the named curve name represented by the given object identifier.
  */
 public static string GetName(
     DerObjectIdentifier oid)
 {
     return((string)names[oid]);
 }
        public TimeStampToken Generate(TimeStampRequest request, BigInteger serialNumber, global::System.DateTime genTime)
        {
            //IL_01a0: Expected O, but got Unknown
            DerObjectIdentifier algorithm      = new DerObjectIdentifier(request.MessageImprintAlgOid);
            AlgorithmIdentifier hashAlgorithm  = new AlgorithmIdentifier(algorithm, DerNull.Instance);
            MessageImprint      messageImprint = new MessageImprint(hashAlgorithm, request.GetMessageImprintDigest());
            Accuracy            accuracy       = null;

            if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0)
            {
                DerInteger seconds = null;
                if (accuracySeconds > 0)
                {
                    seconds = new DerInteger(accuracySeconds);
                }
                DerInteger millis = null;
                if (accuracyMillis > 0)
                {
                    millis = new DerInteger(accuracyMillis);
                }
                DerInteger micros = null;
                if (accuracyMicros > 0)
                {
                    micros = new DerInteger(accuracyMicros);
                }
                accuracy = new Accuracy(seconds, millis, micros);
            }
            DerBoolean derBoolean = null;

            if (ordering)
            {
                derBoolean = DerBoolean.GetInstance(ordering);
            }
            DerInteger nonce = null;

            if (request.Nonce != null)
            {
                nonce = new DerInteger(request.Nonce);
            }
            DerObjectIdentifier tsaPolicyId = new DerObjectIdentifier(tsaPolicyOID);

            if (request.ReqPolicy != null)
            {
                tsaPolicyId = new DerObjectIdentifier(request.ReqPolicy);
            }
            TstInfo tstInfo = new TstInfo(tsaPolicyId, messageImprint, new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy, derBoolean, nonce, tsa, request.Extensions);

            try
            {
                CmsSignedDataGenerator cmsSignedDataGenerator = new CmsSignedDataGenerator();
                byte[] derEncoded = tstInfo.GetDerEncoded();
                if (request.CertReq)
                {
                    cmsSignedDataGenerator.AddCertificates(x509Certs);
                }
                cmsSignedDataGenerator.AddCrls(x509Crls);
                cmsSignedDataGenerator.AddSigner(key, cert, digestOID, signedAttr, unsignedAttr);
                CmsSignedData signedData = cmsSignedDataGenerator.Generate(PkcsObjectIdentifiers.IdCTTstInfo.Id, new CmsProcessableByteArray(derEncoded), encapsulate: true);
                return(new TimeStampToken(signedData));
            }
            catch (CmsException e)
            {
                throw new TspException("Error generating time-stamp token", e);
            }
            catch (IOException val)
            {
                IOException e2 = val;
                throw new TspException("Exception encoding info", (global::System.Exception)(object) e2);
            }
            catch (X509StoreException e3)
            {
                throw new TspException("Exception handling CertStore", e3);
            }
        }
 public KeySpecificInfo(DerObjectIdentifier algorithm, Asn1OctetString counter)
 {
     this.algorithm = algorithm;
     this.counter   = counter;
 }
Example #45
0
        public void Load(
            Stream input,
            char[]      password)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            Asn1Sequence obj             = (Asn1Sequence)Asn1Object.FromStream(input);
            Pfx          bag             = new Pfx(obj);
            ContentInfo  info            = bag.AuthSafe;
            bool         wrongPkcs12Zero = false;

            if (password != null && bag.MacData != null) // check the mac code
            {
                MacData             mData = bag.MacData;
                DigestInfo          dInfo = mData.Mac;
                AlgorithmIdentifier algId = dInfo.AlgorithmID;
                byte[] salt    = mData.GetSalt();
                int    itCount = mData.IterationCount.IntValue;

                byte[] data = ((Asn1OctetString)info.Content).GetOctets();

                byte[] mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, false, data);
                byte[] dig = dInfo.GetDigest();

                if (!Arrays.ConstantTimeAreEqual(mac, dig))
                {
                    if (password.Length > 0)
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    // Try with incorrect zero length password
                    mac = CalculatePbeMac(algId.ObjectID, salt, itCount, password, true, data);

                    if (!Arrays.ConstantTimeAreEqual(mac, dig))
                    {
                        throw new IOException("PKCS12 key store MAC invalid - wrong password or corrupted file.");
                    }

                    wrongPkcs12Zero = true;
                }
            }

            keys.Clear();
            localIds.Clear();
            unmarkedKeyEntry = null;

            IList certBags = Platform.CreateArrayList();

            if (info.ContentType.Equals(PkcsObjectIdentifiers.Data))
            {
                byte[]            octs     = ((Asn1OctetString)info.Content).GetOctets();
                AuthenticatedSafe authSafe = new AuthenticatedSafe(
                    (Asn1Sequence)Asn1OctetString.FromByteArray(octs));
                ContentInfo[] cis = authSafe.GetContentInfo();

                foreach (ContentInfo ci in cis)
                {
                    DerObjectIdentifier oid = ci.ContentType;

                    byte[] octets = null;
                    if (oid.Equals(PkcsObjectIdentifiers.Data))
                    {
                        octets = ((Asn1OctetString)ci.Content).GetOctets();
                    }
                    else if (oid.Equals(PkcsObjectIdentifiers.EncryptedData))
                    {
                        if (password != null)
                        {
                            EncryptedData d = EncryptedData.GetInstance(ci.Content);
                            octets = CryptPbeData(false, d.EncryptionAlgorithm,
                                                  password, wrongPkcs12Zero, d.Content.GetOctets());
                        }
                    }
                    else
                    {
                        // TODO Other data types
                    }

                    if (octets != null)
                    {
                        Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(octets);

                        foreach (Asn1Sequence subSeq in seq)
                        {
                            SafeBag b = new SafeBag(subSeq);

                            if (b.BagID.Equals(PkcsObjectIdentifiers.CertBag))
                            {
                                certBags.Add(b);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag))
                            {
                                LoadPkcs8ShroudedKeyBag(EncryptedPrivateKeyInfo.GetInstance(b.BagValue),
                                                        b.BagAttributes, password, wrongPkcs12Zero);
                            }
                            else if (b.BagID.Equals(PkcsObjectIdentifiers.KeyBag))
                            {
                                LoadKeyBag(PrivateKeyInfo.GetInstance(b.BagValue), b.BagAttributes);
                            }
                            else
                            {
                                // TODO Other bag types
                            }
                        }
                    }
                }
            }

            certs.Clear();
            chainCerts.Clear();
            keyCerts.Clear();

            foreach (SafeBag b in certBags)
            {
                CertBag         certBag = new CertBag((Asn1Sequence)b.BagValue);
                byte[]          octets  = ((Asn1OctetString)certBag.CertValue).GetOctets();
                X509Certificate cert    = new X509CertificateParser().ReadCertificate(octets);

                //
                // set the attributes
                //
                IDictionary     attributes = Platform.CreateHashtable();
                Asn1OctetString localId    = null;
                string          alias      = null;

                if (b.BagAttributes != null)
                {
                    foreach (Asn1Sequence sq in b.BagAttributes)
                    {
                        DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                        Asn1Set             attrSet = Asn1Set.GetInstance(sq[1]);

                        if (attrSet.Count > 0)
                        {
                            // TODO We should be adding all attributes in the set
                            Asn1Encodable attr = attrSet[0];

                            // TODO We might want to "merge" attribute sets with
                            // the same OID - currently, differing values give an error
                            if (attributes.Contains(aOid.Id))
                            {
                                // OK, but the value has to be the same
                                if (!attributes[aOid.Id].Equals(attr))
                                {
                                    throw new IOException("attempt to add existing attribute with different value");
                                }
                            }
                            else
                            {
                                attributes.Add(aOid.Id, attr);
                            }

                            if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                            {
                                alias = ((DerBmpString)attr).GetString();
                            }
                            else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                            {
                                localId = (Asn1OctetString)attr;
                            }
                        }
                    }
                }

                CertId certId = new CertId(cert.GetPublicKey());
                X509CertificateEntry certEntry = new X509CertificateEntry(cert, attributes);

                chainCerts[certId] = certEntry;

                if (unmarkedKeyEntry != null)
                {
                    if (keyCerts.Count == 0)
                    {
                        string name = Hex.ToHexString(certId.Id);

                        keyCerts[name] = certEntry;
                        keys[name]     = unmarkedKeyEntry;
                    }
                }
                else
                {
                    if (localId != null)
                    {
                        string name = Hex.ToHexString(localId.GetOctets());

                        keyCerts[name] = certEntry;
                    }

                    if (alias != null)
                    {
                        // TODO There may have been more than one alias
                        certs[alias] = certEntry;
                    }
                }
            }
        }
Example #46
0
 public static IAsymmetricCipherKeyPairGenerator GetKeyPairGenerator(
     DerObjectIdentifier oid)
 {
     return(GetKeyPairGenerator(oid.Id));
 }
Example #47
0
 public static IWrapper GetWrapper(
     DerObjectIdentifier oid)
 {
     return(GetWrapper(oid.Id));
 }
Example #48
0
 public static string GetAlgorithmName(
     DerObjectIdentifier oid)
 {
     return((string)algorithms[oid.Id]);
 }
Example #49
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);
            }

            try
            {
                if (digestCalculator != null)
                {
                    resultDigest = digestCalculator.GetDigest();
                }
                else
                {
                    if (content != null)
                    {
                        content.Write(new CmsSignedGenerator.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);
            }

            // TODO Shouldn't be using attribute OID as contentType (should be null)
            bool isCounterSignature = contentType.Equals(CmsAttributes.CounterSignature);

            // 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 CmsSignedGenerator.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);
            }
        }
Example #50
0
 public void AddCapability(
     DerObjectIdentifier capability)
 {
     capabilities.Add(new DerSequence(capability));
 }
Example #51
0
 public SignaturePolicyId(
     DerObjectIdentifier sigPolicyIdentifier,
     OtherHashAlgAndValue sigPolicyHash)
     : this(sigPolicyIdentifier, sigPolicyHash, null)
 {
 }
Example #52
0
 public override string[] OidToAttrNames(DerObjectIdentifier oid)
 {
     return(IetfUtils.FindAttrNamesForOID(oid, defaultLookUp));
 }
Example #53
0
        /**
         * Returns a string representation of this CRL.
         *
         * @return a string representation of this CRL.
         */
        public override string ToString()
        {
            StringBuilder buf = new StringBuilder();
            string        nl  = Platform.NewLine;

            buf.Append("              Version: ").Append(this.Version).Append(nl);
            buf.Append("             IssuerDN: ").Append(this.IssuerDN).Append(nl);
            buf.Append("          This update: ").Append(this.ThisUpdate).Append(nl);
            buf.Append("          Next update: ").Append(this.NextUpdate).Append(nl);
            buf.Append("  Signature Algorithm: ").Append(this.SigAlgName).Append(nl);

            byte[] sig = this.GetSignature();

            buf.Append("            Signature: ");
            buf.Append(Hex.ToHexString(sig, 0, 20)).Append(nl);

            for (int i = 20; i < sig.Length; i += 20)
            {
                int count = System.Math.Min(20, sig.Length - i);
                buf.Append("                       ");
                buf.Append(Hex.ToHexString(sig, i, count)).Append(nl);
            }

            X509Extensions extensions = c.TbsCertList.Extensions;

            if (extensions != null)
            {
                IEnumerator e = extensions.ExtensionOids.GetEnumerator();

                if (e.MoveNext())
                {
                    buf.Append("           Extensions: ").Append(nl);
                }

                do
                {
                    DerObjectIdentifier oid = (DerObjectIdentifier)e.Current;
                    X509Extension       ext = extensions.GetExtension(oid);

                    if (ext.Value != null)
                    {
                        Asn1Object asn1Value = X509ExtensionUtilities.FromExtensionValue(ext.Value);

                        buf.Append("                       critical(").Append(ext.IsCritical).Append(") ");
                        try
                        {
                            if (oid.Equals(X509Extensions.CrlNumber))
                            {
                                buf.Append(new CrlNumber(DerInteger.GetInstance(asn1Value).PositiveValue)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.DeltaCrlIndicator))
                            {
                                buf.Append(
                                    "Base CRL: "
                                    + new CrlNumber(DerInteger.GetInstance(
                                                        asn1Value).PositiveValue))
                                .Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.IssuingDistributionPoint))
                            {
                                buf.Append(IssuingDistributionPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.CrlDistributionPoints))
                            {
                                buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else if (oid.Equals(X509Extensions.FreshestCrl))
                            {
                                buf.Append(CrlDistPoint.GetInstance((Asn1Sequence)asn1Value)).Append(nl);
                            }
                            else
                            {
                                buf.Append(oid.Id);
                                buf.Append(" value = ").Append(
                                    Asn1Dump.DumpAsString(asn1Value))
                                .Append(nl);
                            }
                        }
                        catch (Exception)
                        {
                            buf.Append(oid.Id);
                            buf.Append(" value = ").Append("*****").Append(nl);
                        }
                    }
                    else
                    {
                        buf.Append(nl);
                    }
                }while (e.MoveNext());
            }

            ISet certSet = GetRevokedCertificates();

            if (certSet != null)
            {
                foreach (X509CrlEntry entry in certSet)
                {
                    buf.Append(entry);
                    buf.Append(nl);
                }
            }

            return(buf.ToString());
        }
Example #54
0
 public SemanticsInformation(
     DerObjectIdentifier semanticsIdentifier)
 {
     this.semanticsIdentifier = semanticsIdentifier;
 }
Example #55
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();

                // TODO What about s2p.KeyDerivationFunc.Algorithm?
                Pbkdf2Params pbeParams = Pbkdf2Params.GetInstance(s2p.KeyDerivationFunc.Parameters.ToAsn1Object());

                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], null, 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));
        }
Example #56
0
 public SignatureCommitmentType(DerObjectIdentifier identifier)
 {
     _oid = identifier;
 }
Example #57
0
        protected virtual void LoadKeyBag(PrivateKeyInfo privKeyInfo, Asn1Set bagAttributes)
        {
            AsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyInfo);

            IDictionary        attributes = Platform.CreateHashtable();
            AsymmetricKeyEntry keyEntry   = new AsymmetricKeyEntry(privKey, attributes);

            string          alias   = null;
            Asn1OctetString localId = null;

            if (bagAttributes != null)
            {
                foreach (Asn1Sequence sq in bagAttributes)
                {
                    DerObjectIdentifier aOid    = DerObjectIdentifier.GetInstance(sq[0]);
                    Asn1Set             attrSet = Asn1Set.GetInstance(sq[1]);
                    Asn1Encodable       attr    = null;

                    if (attrSet.Count > 0)
                    {
                        // TODO We should be adding all attributes in the set
                        attr = attrSet[0];

                        // TODO We might want to "merge" attribute sets with
                        // the same OID - currently, differing values give an error
                        if (attributes.Contains(aOid.Id))
                        {
                            // OK, but the value has to be the same
                            if (!attributes[aOid.Id].Equals(attr))
                            {
                                throw new IOException("attempt to add existing attribute with different value");
                            }
                        }
                        else
                        {
                            attributes.Add(aOid.Id, attr);
                        }

                        if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName))
                        {
                            alias = ((DerBmpString)attr).GetString();
                            // TODO Do these in a separate loop, just collect aliases here
                            keys[alias] = keyEntry;
                        }
                        else if (aOid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID))
                        {
                            localId = (Asn1OctetString)attr;
                        }
                    }
                }
            }

            if (localId != null)
            {
                string name = Hex.ToHexString(localId.GetOctets());

                if (alias == null)
                {
                    keys[name] = keyEntry;
                }
                else
                {
                    // TODO There may have been more than one alias
                    localIds[alias] = name;
                }
            }
            else
            {
                unmarkedKeyEntry = keyEntry;
            }
        }