public AuthEnvelopedData(
            OriginatorInfo			originatorInfo,
            Asn1Set					recipientInfos,
            EncryptedContentInfo	authEncryptedContentInfo,
            Asn1Set					authAttrs,
            Asn1OctetString			mac,
            Asn1Set					unauthAttrs)
        {
            // "It MUST be set to 0."
            this.version = new DerInteger(0);

            this.originatorInfo = originatorInfo;

            // TODO
            // "There MUST be at least one element in the collection."
            this.recipientInfos = recipientInfos;

            this.authEncryptedContentInfo = authEncryptedContentInfo;

            // TODO
            // "The authAttrs MUST be present if the content type carried in
            // EncryptedContentInfo is not id-data."
            this.authAttrs = authAttrs;

            this.mac = mac;

            this.unauthAttrs = unauthAttrs;
        }
Ejemplo n.º 2
0
		public KekIdentifier(
            Asn1Sequence seq)
        {
            keyIdentifier = (Asn1OctetString) seq[0];

			switch (seq.Count)
            {
            case 1:
				break;
            case 2:
				if (seq[1] is DerGeneralizedTime)
				{
					date = (DerGeneralizedTime) seq[1];
				}
				else
				{
					other = OtherKeyAttribute.GetInstance(seq[2]);
				}
				break;
            case 3:
				date  = (DerGeneralizedTime) seq[1];
				other = OtherKeyAttribute.GetInstance(seq[2]);
				break;
            default:
				throw new ArgumentException("Invalid KekIdentifier");
            }
        }
Ejemplo n.º 3
0
		public Pkcs12PbeParams(
            byte[]	salt,
            int		iterations)
        {
            this.iv = new DerOctetString(salt);
            this.iterations = new DerInteger(iterations);
        }
 public EncryptedPrivateKeyInfo(
     AlgorithmIdentifier	algId,
     byte[]				encoding)
 {
     this.algId = algId;
     this.data = new DerOctetString(encoding);
 }
Ejemplo n.º 5
0
 private PbmParameter(Asn1Sequence seq)
 {
     salt = Asn1OctetString.GetInstance(seq[0]);
     owf = AlgorithmIdentifier.GetInstance(seq[1]);
     iterationCount = DerInteger.GetInstance(seq[2]);
     mac = AlgorithmIdentifier.GetInstance(seq[3]);
 }
Ejemplo n.º 6
0
		private CertResponse(Asn1Sequence seq)
		{
			certReqId = DerInteger.GetInstance(seq[0]);
			status = PkiStatusInfo.GetInstance(seq[1]);

			if (seq.Count >= 3)
			{
				if (seq.Count == 3)
				{
					Asn1Encodable o = seq[2];
					if (o is Asn1OctetString)
					{
						rspInfo = Asn1OctetString.GetInstance(o);
					}
					else
					{
						certifiedKeyPair = CertifiedKeyPair.GetInstance(o);
					}
				}
				else
				{
					certifiedKeyPair = CertifiedKeyPair.GetInstance(seq[2]);
					rspInfo = Asn1OctetString.GetInstance(seq[3]);
				}
			}
		}
Ejemplo n.º 7
0
        public EssCertID(
			byte[]			hash,
			IssuerSerial	issuerSerial)
        {
            this.certHash = new DerOctetString(hash);
            this.issuerSerial = issuerSerial;
        }
Ejemplo n.º 8
0
		public X509Extension(
            bool			critical,
            Asn1OctetString	value)
        {
            this.critical = critical;
            this.value = value;
        }
Ejemplo n.º 9
0
		public AuthenticatedData(
			OriginatorInfo		originatorInfo,
			Asn1Set				recipientInfos,
			AlgorithmIdentifier	macAlgorithm,
			AlgorithmIdentifier	digestAlgorithm,
			ContentInfo			encapsulatedContent,
			Asn1Set				authAttrs,
			Asn1OctetString		mac,
			Asn1Set				unauthAttrs)
		{
			if (digestAlgorithm != null || authAttrs != null)
			{
				if (digestAlgorithm == null || authAttrs == null)
				{
					throw new ArgumentException("digestAlgorithm and authAttrs must be set together");
				}
			}

			version = new DerInteger(CalculateVersion(originatorInfo));

			this.originatorInfo = originatorInfo;
			this.macAlgorithm = macAlgorithm;
			this.digestAlgorithm = digestAlgorithm;
			this.recipientInfos = recipientInfos;
			this.encapsulatedContentInfo = encapsulatedContent;
			this.authAttrs = authAttrs;
			this.mac = mac;
			this.unauthAttrs = unauthAttrs;
		}
 public RecipientEncryptedKey(
     KeyAgreeRecipientIdentifier	id,
     Asn1OctetString				encryptedKey)
 {
     this.identifier = id;
     this.encryptedKey = encryptedKey;
 }
Ejemplo n.º 11
0
        private EncryptedValue(Asn1Sequence seq)
        {
            int index = 0;
            while (seq[index] is Asn1TaggedObject)
            {
                Asn1TaggedObject tObj = (Asn1TaggedObject)seq[index];

                switch (tObj.TagNo)
                {
                    case 0:
                        intendedAlg = AlgorithmIdentifier.GetInstance(tObj, false);
                        break;
                    case 1:
                        symmAlg = AlgorithmIdentifier.GetInstance(tObj, false);
                        break;
                    case 2:
                        encSymmKey = DerBitString.GetInstance(tObj, false);
                        break;
                    case 3:
                        keyAlg = AlgorithmIdentifier.GetInstance(tObj, false);
                        break;
                    case 4:
                        valueHint = Asn1OctetString.GetInstance(tObj, false);
                        break;
                }
                ++index;
            }

            encValue = DerBitString.GetInstance(seq[index]);
        }
Ejemplo n.º 12
0
		public Pbkdf2Params(
			byte[] salt,
			int iterationCount)
		{
			this.octStr = new DerOctetString(salt);
			this.iterationCount = new DerInteger(iterationCount);
		}
Ejemplo n.º 13
0
		public RC2CbcParameter(
            int		parameterVersion,
            byte[]	iv)
        {
            this.version = new DerInteger(parameterVersion);
            this.iv = new DerOctetString(iv);
        }
Ejemplo n.º 14
0
        public Pbkdf2Params(
            Asn1Sequence seq)
        {
            if (seq.Count < 2 || seq.Count > 4)
                throw new ArgumentException("Wrong number of elements in sequence", "seq");

            this.octStr = (Asn1OctetString)seq[0];
            this.iterationCount = (DerInteger)seq[1];

            Asn1Encodable kl = null, d = null;
            if (seq.Count > 3)
            {
                kl = seq[2];
                d = seq[3];
            }
            else if (seq.Count > 2)
            {
                if (seq[2] is DerInteger)
                {
                    kl = seq[2];
                }
                else
                {
                    d = seq[2];
                }
            }
            if (kl != null)
            {
                keyLength = (DerInteger)kl;
            }
            if (d != null)
            {
                prf = AlgorithmIdentifier.GetInstance(d);
            }
        }
Ejemplo n.º 15
0
		public KeySpecificInfo(
            DerObjectIdentifier	algorithm,
            Asn1OctetString		counter)
        {
            this.algorithm = algorithm;
            this.counter = counter;
        }
Ejemplo n.º 16
0
		public KeyTransRecipientInfo(
            Asn1Sequence seq)
        {
            this.version = (DerInteger) seq[0];
            this.rid = RecipientIdentifier.GetInstance(seq[1]);
            this.keyEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(seq[2]);
            this.encryptedKey = (Asn1OctetString) seq[3];
        }
Ejemplo n.º 17
0
		private PbeParameter(Asn1Sequence seq)
		{
			if (seq.Count != 2)
				throw new ArgumentException("Wrong number of elements in sequence", "seq");

			salt = Asn1OctetString.GetInstance(seq[0]);
			iterationCount = DerInteger.GetInstance(seq[1]);
		}
Ejemplo n.º 18
0
		public KekRecipientInfo(
            Asn1Sequence seq)
        {
            version = (DerInteger) seq[0];
            kekID = KekIdentifier.GetInstance(seq[1]);
            keyEncryptionAlgorithm = AlgorithmIdentifier.GetInstance(seq[2]);
            encryptedKey = (Asn1OctetString) seq[3];
        }
Ejemplo n.º 19
0
		public OtherHash(
			byte[] sha1Hash)
		{
			if (sha1Hash == null)
				throw new ArgumentNullException("sha1Hash");

			this.sha1Hash = new DerOctetString(sha1Hash);
		}
Ejemplo n.º 20
0
		public OtherHash(
			Asn1OctetString sha1Hash)
		{
			if (sha1Hash == null)
				throw new ArgumentNullException("sha1Hash");

			this.sha1Hash = sha1Hash;
		}
Ejemplo n.º 21
0
		public PasswordRecipientInfo(
            AlgorithmIdentifier	keyEncryptionAlgorithm,
            Asn1OctetString		encryptedKey)
        {
            this.version = new DerInteger(0);
            this.keyEncryptionAlgorithm = keyEncryptionAlgorithm;
            this.encryptedKey = encryptedKey;
        }
Ejemplo n.º 22
0
        private Gost28147Parameters(
            Asn1Sequence seq)
        {
			if (seq.Count != 2)
				throw new ArgumentException("Wrong number of elements in sequence", "seq");

			this.iv = Asn1OctetString.GetInstance(seq[0]);
			this.paramSet = DerObjectIdentifier.GetInstance(seq[1]);
        }
        private EncryptedPrivateKeyInfo(
            Asn1Sequence seq)
        {
            if (seq.Count != 2)
                throw new ArgumentException(@"Wrong number of elements in sequence", "seq");

            algId = AlgorithmIdentifier.GetInstance(seq[0]);
            data = Asn1OctetString.GetInstance(seq[1]);
        }
Ejemplo n.º 24
0
		public TimeStampedData(DerIA5String dataUri, MetaData metaData, Asn1OctetString content,
			Evidence temporalEvidence)
		{
			this.version = new DerInteger(1);
			this.dataUri = dataUri;
			this.metaData = metaData;
			this.content = content;
			this.temporalEvidence = temporalEvidence;
		}
Ejemplo n.º 25
0
		public OtherInfo(
            KeySpecificInfo	keyInfo,
            Asn1OctetString	partyAInfo,
            Asn1OctetString	suppPubInfo)
        {
            this.keyInfo = keyInfo;
            this.partyAInfo = partyAInfo;
            this.suppPubInfo = suppPubInfo;
        }
Ejemplo n.º 26
0
		public EncryptedContentInfo(
            DerObjectIdentifier	contentType,
            AlgorithmIdentifier	contentEncryptionAlgorithm,
            Asn1OctetString		encryptedContent)
        {
            this.contentType = contentType;
            this.contentEncryptionAlgorithm = contentEncryptionAlgorithm;
            this.encryptedContent = encryptedContent;
        }
Ejemplo n.º 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]);
        }
Ejemplo n.º 28
0
		public X9FieldElement(
			int				m,
			int				k1,
			int				k2,
			int				k3,
			Asn1OctetString	s)
			: this(new F2mFieldElement(m, k1, k2, k3, new BigInteger(1, s.GetOctets())))
		{
		}
		public MQVuserKeyingMaterial(
			OriginatorPublicKey	ephemeralPublicKey,
			Asn1OctetString		addedukm)
		{
			// TODO Check ephemeralPublicKey not null

			this.ephemeralPublicKey = ephemeralPublicKey;
			this.addedukm = addedukm;
		}
Ejemplo n.º 30
0
 public PrivateKeyInfo(
     AlgorithmIdentifier	algID,
     Asn1Object			privateKey,
     Asn1Set				attributes)
 {
     this.algID = algID;
     this.privKey = new DerOctetString(privateKey.GetEncoded(Asn1Encodable.Der));
     this.attributes = attributes;
 }
Ejemplo n.º 31
0
 public CertDigestObj(DerPrintableString type, Asn1OctetString value)
 {
     Type  = type;
     Value = value;
 }
Ejemplo n.º 32
0
 public PbeParameter(byte[] salt, int iterationCount)
 {
     this.salt           = new DerOctetString(salt);
     this.iterationCount = new DerInteger(iterationCount);
 }
 public ExtendedRequest()
 {
     this.requestName  = null;
     this.requestValue = null;
 }
Ejemplo n.º 34
0
 public virtual PkiHeaderBuilder SetRecipKID(DerOctetString kid)
 {
     recipKID = kid;
     return(this);
 }
Ejemplo n.º 35
0
 private RecipientEncryptedKey(
     Asn1Sequence seq)
 {
     identifier   = KeyAgreeRecipientIdentifier.GetInstance(seq[0]);
     encryptedKey = (Asn1OctetString)seq[1];
 }
Ejemplo n.º 36
0
 public KekRecipientInfo(KekIdentifier kekID, AlgorithmIdentifier keyEncryptionAlgorithm, Asn1OctetString encryptedKey)
 {
     this.version = new DerInteger(4);
     this.kekID   = kekID;
     this.keyEncryptionAlgorithm = keyEncryptionAlgorithm;
     this.encryptedKey           = encryptedKey;
 }
Ejemplo n.º 37
0
 private MsCertTemplateName(string name)
 {
     templateName = new DerOctetString(Utility.StringToUTF8ByteArray(name));
 }
Ejemplo n.º 38
0
 public KeyTransRecipientInfoGenerator(byte[] subjectKeyID, IKeyWrapper keyWrapper)
 {
     this.subjectKeyIdentifier = new DerOctetString(subjectKeyIdentifier);
     this.keyWrapper           = keyWrapper;
 }
Ejemplo n.º 39
0
 public virtual PkiHeaderBuilder SetRecipNonce(Asn1OctetString nonce)
 {
     recipNonce = nonce;
     return(this);
 }
Ejemplo n.º 40
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 = new X962Parameters(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 = new Gost3410PublicKeyAlgParameters(
                    Asn1Sequence.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");
            }
        }
Ejemplo n.º 41
0
 public virtual PkiHeaderBuilder SetTransactionID(Asn1OctetString tid)
 {
     transactionID = tid;
     return(this);
 }
        /// <summary>
        ///     Constructs an extended operations object which contains the ber encoded
        ///     replication filter.
        /// </summary>
        /// <param name="serverDN">
        ///     The server on which the replication filter needs to be set
        /// </param>
        /// <param name="replicationFilter">
        ///     An array of String Arrays. Each array starting with
        ///     a class name followed by the attribute names for that class that should comprise
        ///     the replication filter.
        /// </param>
        /// <exception>
        ///     LdapException A general exception which includes an error
        ///     message and an Ldap error code.
        /// </exception>
        public SetReplicationFilterRequest(string serverDN, string[][] replicationFilter)
            : base(ReplicationConstants.SET_REPLICATION_FILTER_REQ, null)
        {
            try
            {
                if ((object)serverDN == null)
                {
                    throw new ArgumentException(ExceptionMessages.PARAM_ERROR);
                }

                var encodedData = new MemoryStream();
                var encoder     = new LBEREncoder();

                var asn1_serverDN = new Asn1OctetString(serverDN);

                // Add the serverDN to encoded data
                asn1_serverDN.encode(encoder, encodedData);

                // The toplevel sequenceOF
                var asn1_replicationFilter = new Asn1SequenceOf();

                if (replicationFilter == null)
                {
                    asn1_replicationFilter.encode(encoder, encodedData);
                    setValue(SupportClass.ToSByteArray(encodedData.ToArray()));
                    return;
                }

                var i = 0;
                // for every element in the array
                while (i < replicationFilter.Length && replicationFilter[i] != null)
                {
                    // The following additional Sequence is not needed
                    // as defined by the Asn1. But the server and the
                    // C client are encoding it. Remove this when server
                    // and C client are fixed to conform to the published Asn1.
                    var buginAsn1Representation = new Asn1Sequence();

                    // Add the classname to the sequence -
                    buginAsn1Representation.add(new Asn1OctetString(replicationFilter[i][0]));

                    // Start a sequenceOF for attributes
                    var asn1_attributeList = new Asn1SequenceOf();

                    // For every attribute in the array - remember attributes start after
                    // the first element
                    var j = 1;
                    while (j < replicationFilter[i].Length && (object)replicationFilter[i][j] != null)
                    {
                        // Add the attribute name to the inner SequenceOf
                        asn1_attributeList.add(new Asn1OctetString(replicationFilter[i][j]));
                        j++;
                    }


                    // Add the attributeList to the sequence - extra add due to bug
                    buginAsn1Representation.add(asn1_attributeList);
                    asn1_replicationFilter.add(buginAsn1Representation);
                    i++;
                }

                asn1_replicationFilter.encode(encoder, encodedData);
                setValue(SupportClass.ToSByteArray(encodedData.ToArray()));
            }
            catch (IOException ioe)
            {
                throw new LdapException(ExceptionMessages.ENCODING_ERROR, LdapException.ENCODING_ERROR, null, ioe);
            }
        }
Ejemplo n.º 43
0
 public RC2CbcParameter(
     byte[] iv)
 {
     this.iv = new DerOctetString(iv);
 }
Ejemplo n.º 44
0
 private MsCertTemplateName(Asn1OctetString name)
 {
     templateName = name;
 }
Ejemplo n.º 45
0
        public virtual bool Match(object obj)
        {
            X509Certificate x509Certificate = obj as X509Certificate;

            if (x509Certificate == null)
            {
                return(false);
            }
            if (!MatchExtension(authorityKeyIdentifier, x509Certificate, X509Extensions.AuthorityKeyIdentifier))
            {
                return(false);
            }
            if (basicConstraints != -1)
            {
                int num = x509Certificate.GetBasicConstraints();
                if (basicConstraints == -2)
                {
                    if (num != -1)
                    {
                        return(false);
                    }
                }
                else if (num < basicConstraints)
                {
                    return(false);
                }
            }
            if (certificate != null && !certificate.Equals(x509Certificate))
            {
                return(false);
            }
            if (certificateValid != null && !x509Certificate.IsValid(certificateValid.Value))
            {
                return(false);
            }
            if (extendedKeyUsage != null)
            {
                global::System.Collections.IList list = x509Certificate.GetExtendedKeyUsage();
                if (list != null)
                {
                    {
                        global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)extendedKeyUsage).GetEnumerator();
                        try
                        {
                            while (enumerator.MoveNext())
                            {
                                DerObjectIdentifier derObjectIdentifier = (DerObjectIdentifier)enumerator.get_Current();
                                if (!list.Contains((object)derObjectIdentifier.Id))
                                {
                                    return(false);
                                }
                            }
                        }
                        finally
                        {
                            global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                            if (disposable != null)
                            {
                                disposable.Dispose();
                            }
                        }
                    }
                }
            }
            if (issuer != null && !issuer.Equivalent(x509Certificate.IssuerDN, inOrder: true))
            {
                return(false);
            }
            if (keyUsage != null)
            {
                bool[] array = x509Certificate.GetKeyUsage();
                if (array != null)
                {
                    for (int i = 0; i < 9; i++)
                    {
                        if (keyUsage[i] && !array[i])
                        {
                            return(false);
                        }
                    }
                }
            }
            if (policy != null)
            {
                Asn1OctetString extensionValue = x509Certificate.GetExtensionValue(X509Extensions.CertificatePolicies);
                if (extensionValue == null)
                {
                    return(false);
                }
                Asn1Sequence instance = Asn1Sequence.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue));
                if (((global::System.Collections.ICollection)policy).get_Count() < 1 && instance.Count < 1)
                {
                    return(false);
                }
                bool flag = false;
                {
                    global::System.Collections.IEnumerator enumerator = instance.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            PolicyInformation policyInformation = (PolicyInformation)enumerator.get_Current();
                            if (policy.Contains(policyInformation.PolicyIdentifier))
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                    finally
                    {
                        global::System.IDisposable disposable2 = enumerator as global::System.IDisposable;
                        if (disposable2 != null)
                        {
                            disposable2.Dispose();
                        }
                    }
                }
                if (!flag)
                {
                    return(false);
                }
            }
            if (privateKeyValid != null)
            {
                Asn1OctetString extensionValue2 = x509Certificate.GetExtensionValue(X509Extensions.PrivateKeyUsagePeriod);
                if (extensionValue2 == null)
                {
                    return(false);
                }
                PrivateKeyUsagePeriod   instance2 = PrivateKeyUsagePeriod.GetInstance(X509ExtensionUtilities.FromExtensionValue(extensionValue2));
                global::System.DateTime value     = privateKeyValid.Value;
                global::System.DateTime dateTime  = instance2.NotAfter.ToDateTime();
                global::System.DateTime dateTime2 = instance2.NotBefore.ToDateTime();
                if (value.CompareTo((object)dateTime) > 0 || value.CompareTo((object)dateTime2) < 0)
                {
                    return(false);
                }
            }
            if (serialNumber != null && !serialNumber.Equals(x509Certificate.SerialNumber))
            {
                return(false);
            }
            if (subject != null && !subject.Equivalent(x509Certificate.SubjectDN, inOrder: true))
            {
                return(false);
            }
            if (!MatchExtension(subjectKeyIdentifier, x509Certificate, X509Extensions.SubjectKeyIdentifier))
            {
                return(false);
            }
            if (subjectPublicKey != null && !subjectPublicKey.Equals(GetSubjectPublicKey(x509Certificate)))
            {
                return(false);
            }
            if (subjectPublicKeyAlgID != null && !subjectPublicKeyAlgID.Equals(GetSubjectPublicKey(x509Certificate).AlgorithmID))
            {
                return(false);
            }
            return(true);
        }
        /// <summary> Constructs an object from the responseValue which contains the replication
        /// filter.
        ///
        /// The constructor parses the responseValue which has the following
        /// format:
        /// responseValue ::=
        ///  SEQUENCE of SEQUENCE {
        ///  classname  OCTET STRING
        ///  SEQUENCE of ATTRIBUTES
        /// }
        /// where
        /// ATTRIBUTES:: OCTET STRING
        ///
        /// </summary>
        /// <exception> IOException The responseValue could not be decoded.
        /// </exception>
        public GetReplicationFilterResponse(RfcLdapMessage rfcMessage) : base(rfcMessage)
        {
            if (ResultCode != LdapException.SUCCESS)
            {
                returnedFilter = new String[0][];
                for (int i = 0; i < 0; i++)
                {
                    returnedFilter[i] = new String[0];
                }
            }
            else
            {
                // parse the contents of the reply
                sbyte[] returnedValue = Value;
                if (returnedValue == null)
                {
                    throw new System.IO.IOException("No returned value");
                }

                // Create a decoder object
                LBERDecoder decoder = new LBERDecoder();
                if (decoder == null)
                {
                    throw new System.IO.IOException("Decoding error");
                }

                // We should get back a sequence
                Asn1Sequence returnedSequence = (Asn1Sequence)decoder.decode(returnedValue);

                if (returnedSequence == null)
                {
                    throw new System.IO.IOException("Decoding error");
                }

                // How many sequences in this list
                int numberOfSequences = returnedSequence.size();
                returnedFilter = new String[numberOfSequences][];

                // Parse each returned sequence object
                for (int classNumber = 0; classNumber < numberOfSequences; classNumber++)
                {
                    // Get the next Asn1Sequence
                    Asn1Sequence asn1_innerSequence = (Asn1Sequence)returnedSequence.get_Renamed(classNumber);
                    if (asn1_innerSequence == null)
                    {
                        throw new System.IO.IOException("Decoding error");
                    }

                    // Get the asn1 encoded classname
                    Asn1OctetString asn1_className = (Asn1OctetString)asn1_innerSequence.get_Renamed(0);
                    if (asn1_className == null)
                    {
                        return;
                    }

                    // Get the attribute List
                    Asn1Sequence asn1_attributeList = (Asn1Sequence)asn1_innerSequence.get_Renamed(1);
                    if (asn1_attributeList == null)
                    {
                        throw new System.IO.IOException("Decoding error");
                    }

                    int numberOfAttributes = asn1_attributeList.size();
                    returnedFilter[classNumber] = new String[numberOfAttributes + 1];

                    // Get the classname
                    returnedFilter[classNumber][0] = asn1_className.stringValue();
                    if ((object)returnedFilter[classNumber][0] == null)
                    {
                        throw new System.IO.IOException("Decoding error");
                    }

                    for (int attributeNumber = 0; attributeNumber < numberOfAttributes; attributeNumber++)
                    {
                        // Get the asn1 encoded attribute name
                        Asn1OctetString asn1_attributeName = (Asn1OctetString)asn1_attributeList.get_Renamed(attributeNumber);
                        if (asn1_attributeName == null)
                        {
                            throw new System.IO.IOException("Decoding error");
                        }

                        // Get attributename string
                        returnedFilter[classNumber][attributeNumber + 1] = asn1_attributeName.stringValue();
                        if ((object)returnedFilter[classNumber][attributeNumber + 1] == null)
                        {
                            throw new System.IO.IOException("Decoding error");
                        }
                    }
                }
            }
        }
Ejemplo n.º 47
0
    public static ICollection GetSubjectAlternativeNames(X509Certificate cert)
    {
        Asn1OctetString extensionValue = cert.GetExtensionValue(X509Extensions.SubjectAlternativeName);

        return(GetAlternativeName(extensionValue));
    }
Ejemplo n.º 48
0
 public virtual PkiHeaderBuilder SetSenderKID(Asn1OctetString kid)
 {
     senderKID = kid;
     return(this);
 }
Ejemplo n.º 49
0
 public static Asn1Object FromExtensionValue(Asn1OctetString extensionValue)
 {
     return(Asn1Object.FromByteArray(extensionValue.GetOctets()));
 }
Ejemplo n.º 50
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];

            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.ObjectID;
                Asn1Object          encParams = encScheme.Parameters.ToAsn1Object();

                // TODO What about s2p.KeyDerivationFunc.ObjectID?
                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 (mechanism.StartsWith("PBEwithSHA-1"))
            {
                PbeParametersGenerator generator = MakePbeGenerator(
                    (string)algorithmType[mechanism], new Sha1Digest(), keyBytes, salt, iterationCount);

                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 (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.StartsWith("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 (mechanism.StartsWith("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 (mechanism.StartsWith("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 (mechanism.StartsWith("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));
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Decides if the given attribute certificate should be selected.
        /// </summary>
        /// <param name="obj">The attribute certificate to be checked.</param>
        /// <returns><code>true</code> if the object matches this selector.</returns>
        public bool Match(
            object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            IX509AttributeCertificate attrCert = obj as IX509AttributeCertificate;

            if (attrCert == null)
            {
                return(false);
            }

            if (this.attributeCert != null && !this.attributeCert.Equals(attrCert))
            {
                return(false);
            }

            if (serialNumber != null && !attrCert.SerialNumber.Equals(serialNumber))
            {
                return(false);
            }

            if (holder != null && !attrCert.Holder.Equals(holder))
            {
                return(false);
            }

            if (issuer != null && !attrCert.Issuer.Equals(issuer))
            {
                return(false);
            }

            if (attributeCertificateValid != null && !attrCert.IsValid(attributeCertificateValid.Value))
            {
                return(false);
            }

            if (targetNames.Count > 0 || targetGroups.Count > 0)
            {
                Asn1OctetString targetInfoExt = attrCert.GetExtensionValue(
                    X509Extensions.TargetInformation);

                if (targetInfoExt != null)
                {
                    TargetInformation targetinfo;
                    try
                    {
                        targetinfo = TargetInformation.GetInstance(
                            X509ExtensionUtilities.FromExtensionValue(targetInfoExt));
                    }
                    catch (Exception)
                    {
                        return(false);
                    }

                    Targets[] targetss = targetinfo.GetTargetsObjects();

                    if (targetNames.Count > 0)
                    {
                        bool found = false;

                        for (int i = 0; i < targetss.Length && !found; i++)
                        {
                            Target[] targets = targetss[i].GetTargets();

                            for (int j = 0; j < targets.Length; j++)
                            {
                                GeneralName targetName = targets[j].TargetName;

                                if (targetName != null && targetNames.Contains(targetName))
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (!found)
                        {
                            return(false);
                        }
                    }

                    if (targetGroups.Count > 0)
                    {
                        bool found = false;

                        for (int i = 0; i < targetss.Length && !found; i++)
                        {
                            Target[] targets = targetss[i].GetTargets();

                            for (int j = 0; j < targets.Length; j++)
                            {
                                GeneralName targetGroup = targets[j].TargetGroup;

                                if (targetGroup != null && targetGroups.Contains(targetGroup))
                                {
                                    found = true;
                                    break;
                                }
                            }
                        }

                        if (!found)
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 52
0
 public CertStatus(byte[] certHash, BigInteger certReqId, PkiStatusInfo statusInfo)
 {
     this.certHash   = new DerOctetString(certHash);
     this.certReqId  = new DerInteger(certReqId);
     this.statusInfo = statusInfo;
 }
Ejemplo n.º 53
0
 public Checksum()
 {
     this.cksumtype = null;
     this.checksum  = null;
 }
        public X509Certificate(
            X509CertificateStructure c)
        {
            this.c = c;

            try
            {
                this.sigAlgName = X509SignatureUtilities.GetSignatureName(c.SignatureAlgorithm);

                Asn1Encodable parameters = c.SignatureAlgorithm.Parameters;
                this.sigAlgParams = (null == parameters) ? null : parameters.GetEncoded(Asn1Encodable.Der);
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("Certificate contents invalid: " + e);
            }

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));

                if (str != null)
                {
                    basicConstraints = BasicConstraints.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct BasicConstraints: " + e);
            }

            try
            {
                Asn1OctetString str = this.GetExtensionValue(new DerObjectIdentifier("2.5.29.15"));

                if (str != null)
                {
                    DerBitString bits = DerBitString.GetInstance(
                        X509ExtensionUtilities.FromExtensionValue(str));

                    byte[] bytes  = bits.GetBytes();
                    int    length = (bytes.Length * 8) - bits.PadBits;

                    keyUsage = new bool[(length < 9) ? 9 : length];

                    for (int i = 0; i != length; i++)
                    {
                        keyUsage[i] = (bytes[i / 8] & (0x80 >> (i % 8))) != 0;
                    }
                }
                else
                {
                    keyUsage = null;
                }
            }
            catch (Exception e)
            {
                throw new CertificateParsingException("cannot construct KeyUsage: " + e);
            }
        }
Ejemplo n.º 55
0
 public CertStatus(byte[] certHash, BigInteger certReqId)
 {
     this.certHash  = new DerOctetString(certHash);
     this.certReqId = new DerInteger(certReqId);
 }
Ejemplo n.º 56
0
 public void SetValue(byte[] value)
 {
     Value = new DerOctetString(value);
 }
Ejemplo n.º 57
0
        /**
         * generate a signed object that for a CMS Signed Data
         * object  - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         */
        public CmsSignedData Generate(
            string signedContentType,
            // FIXME Avoid accessing more than once to support CmsProcessableInputStream
            CmsProcessable content,
            bool encapsulate)
        {
            Asn1EncodableVector digestAlgs  = new Asn1EncodableVector();
            Asn1EncodableVector signerInfos = new Asn1EncodableVector();

            _digests.Clear();             // clear the current preserved digest state

            //
            // add the precalculated SignerInfo objects.
            //
            foreach (SignerInformation signer in _signers)
            {
                digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));

                // TODO Verify the content type and calculated digest match the precalculated SignerInfo
                signerInfos.Add(signer.ToSignerInfo());
            }

            //
            // add the SignerInfo objects
            //
            bool isCounterSignature = (signedContentType == null);

            DerObjectIdentifier contentTypeOid = isCounterSignature
                ?   null
                                :       new DerObjectIdentifier(signedContentType);

            foreach (SignerInf signer in signerInfs)
            {
                try
                {
                    digestAlgs.Add(signer.DigestAlgorithmID);
                    signerInfos.Add(signer.ToSignerInfo(contentTypeOid, content, rand));
                }
                catch (IOException e)
                {
                    throw new CmsException("encoding error.", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for signature.", e);
                }
                catch (SignatureException e)
                {
                    throw new CmsException("error creating signature.", e);
                }
                catch (CertificateEncodingException e)
                {
                    throw new CmsException("error creating sid.", e);
                }
            }

            Asn1Set certificates = null;

            if (_certs.Count != 0)
            {
                certificates = UseDerForCerts
                    ?   CmsUtilities.CreateDerSetFromList(_certs)
                    :   CmsUtilities.CreateBerSetFromList(_certs);
            }

            Asn1Set certrevlist = null;

            if (_crls.Count != 0)
            {
                certrevlist = UseDerForCrls
                    ?   CmsUtilities.CreateDerSetFromList(_crls)
                    :   CmsUtilities.CreateBerSetFromList(_crls);
            }

            Asn1OctetString octs = null;

            if (encapsulate)
            {
                MemoryStream bOut = new MemoryStream();
                if (content != null)
                {
                    try
                    {
                        content.Write(bOut);
                    }
                    catch (IOException e)
                    {
                        throw new CmsException("encapsulation error.", e);
                    }
                }
                octs = new BerOctetString(bOut.ToArray());
            }

            ContentInfo encInfo = new ContentInfo(contentTypeOid, octs);

            SignedData sd = new SignedData(
                new DerSet(digestAlgs),
                encInfo,
                certificates,
                certrevlist,
                new DerSet(signerInfos));

            ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.SignedData, sd);

            return(new CmsSignedData(content, contentInfo));
        }
 public LSAP_TOKEN_INFO_INTEGRITY()
 {
     this.flags     = null;
     this.tokenIL   = null;
     this.machineID = null;
 }
Ejemplo n.º 59
0
 public virtual PkiHeaderBuilder SetSenderNonce(Asn1OctetString nonce)
 {
     senderNonce = nonce;
     return(this);
 }
Ejemplo n.º 60
0
        /// <summary>
        /// Create a Subject Public Key Info object for a given public key.
        /// </summary>
        /// <param name="key">One of ElGammalPublicKeyParameters, DSAPublicKeyParameter, DHPublicKeyParameters, RsaKeyParameters or ECPublicKeyParameters</param>
        /// <returns>A subject public key info object.</returns>
        /// <exception cref="Exception">Throw exception if object provided is not one of the above.</exception>
        public static SubjectPublicKeyInfo CreateSubjectPublicKeyInfo(
            AsymmetricKeyParameter key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (key.IsPrivate)
            {
                throw new ArgumentException("Private key passed - public key expected.", "key");
            }

            if (key is ElGamalPublicKeyParameters)
            {
                ElGamalPublicKeyParameters _key = (ElGamalPublicKeyParameters)key;
                ElGamalParameters          kp   = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        OiwObjectIdentifiers.ElGamalAlgorithm,
                        new ElGamalParameter(kp.P, kp.G).ToAsn1Object()),
                    new DerInteger(_key.Y));

                return(info);
            }

            if (key is DsaPublicKeyParameters)
            {
                DsaPublicKeyParameters _key = (DsaPublicKeyParameters)key;
                DsaParameters          kp   = _key.Parameters;
                Asn1Encodable          ae   = kp == null
                                        ?       null
                                        :       new DsaParameter(kp.P, kp.Q, kp.G).ToAsn1Object();

                return(new SubjectPublicKeyInfo(
                           new AlgorithmIdentifier(X9ObjectIdentifiers.IdDsa, ae),
                           new DerInteger(_key.Y)));
            }

            if (key is DHPublicKeyParameters)
            {
                DHPublicKeyParameters _key = (DHPublicKeyParameters)key;
                DHParameters          kp   = _key.Parameters;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(
                        _key.AlgorithmOid,
                        new DHParameter(kp.P, kp.G, kp.L).ToAsn1Object()),
                    new DerInteger(_key.Y));

                return(info);
            } // End of DH

            if (key is RsaKeyParameters)
            {
                RsaKeyParameters _key = (RsaKeyParameters)key;

                SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                    new AlgorithmIdentifier(PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance),
                    new RsaPublicKeyStructure(_key.Modulus, _key.Exponent).ToAsn1Object());

                return(info);
            } // End of RSA.

            if (key is ECPublicKeyParameters)
            {
                ECPublicKeyParameters _key = (ECPublicKeyParameters)key;

                if (_key.AlgorithmName == "ECGOST3410")
                {
                    if (_key.PublicKeyParamSet == null)
                    {
                        throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
                    }

                    ECPoint    q  = _key.Q;
                    BigInteger bX = q.X.ToBigInteger();
                    BigInteger bY = q.Y.ToBigInteger();

                    byte[] encKey = new byte[64];
                    ExtractBytes(encKey, 0, bX);
                    ExtractBytes(encKey, 32, bY);

                    Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
                        _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        CryptoProObjectIdentifiers.GostR3410x2001,
                        gostParams.ToAsn1Object());

                    return(new SubjectPublicKeyInfo(algID, new DerOctetString(encKey)));
                }
                else
                {
                    X962Parameters x962;
                    if (_key.PublicKeyParamSet == null)
                    {
                        ECDomainParameters kp  = _key.Parameters;
                        X9ECParameters     ecP = new X9ECParameters(kp.Curve, kp.G, kp.N, kp.H, kp.GetSeed());

                        x962 = new X962Parameters(ecP);
                    }
                    else
                    {
                        x962 = new X962Parameters(_key.PublicKeyParamSet);
                    }

                    Asn1OctetString p = (Asn1OctetString)(new X9ECPoint(_key.Q).ToAsn1Object());

                    AlgorithmIdentifier algID = new AlgorithmIdentifier(
                        X9ObjectIdentifiers.IdECPublicKey, x962.ToAsn1Object());

                    return(new SubjectPublicKeyInfo(algID, p.GetOctets()));
                }
            }             // End of EC

            if (key is Gost3410PublicKeyParameters)
            {
                Gost3410PublicKeyParameters _key = (Gost3410PublicKeyParameters)key;

                if (_key.PublicKeyParamSet == null)
                {
                    throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
                }

                byte[] keyEnc   = _key.Y.ToByteArrayUnsigned();
                byte[] keyBytes = new byte[keyEnc.Length];

                for (int i = 0; i != keyBytes.Length; i++)
                {
                    keyBytes[i] = keyEnc[keyEnc.Length - 1 - i];                     // must be little endian
                }

                Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
                    _key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);

                AlgorithmIdentifier algID = new AlgorithmIdentifier(
                    CryptoProObjectIdentifiers.GostR3410x94,
                    algParams.ToAsn1Object());

                return(new SubjectPublicKeyInfo(algID, new DerOctetString(keyBytes)));
            }

            throw new ArgumentException("Class provided no convertible: " + key.GetType().FullName);
        }