Ejemplo n.º 1
0
		/**
		 * @param explicitly true if an explicitly tagged object.
		 * @param tagNo the tag number for this object.
		 * @param obj the tagged object.
		 */
		public DerTaggedObject(
			bool			explicitly,
			int				tagNo,
			Asn1Encodable	obj)
			: base(explicitly, tagNo, obj)
		{
		}
 public OtherRevocationInfoFormat(
     DerObjectIdentifier otherRevInfoFormat,
     Asn1Encodable otherRevInfo)
 {
     this.otherRevInfoFormat = otherRevInfoFormat;
     this.otherRevInfo = otherRevInfo;
 }
Ejemplo n.º 3
0
		private void AddOptional(Asn1EncodableVector v, int tagNo, Asn1Encodable obj)
		{
			if (obj != null)
			{
				v.Add(new DerTaggedObject(true, tagNo, obj));
			}
		}
Ejemplo n.º 4
0
		public OtherKeyAttribute(
            DerObjectIdentifier	keyAttrId,
            Asn1Encodable		keyAttr)
        {
            this.keyAttrId = keyAttrId;
            this.keyAttr = keyAttr;
        }
Ejemplo n.º 5
0
 public ContentInfo(
     DerObjectIdentifier	contentType,
     Asn1Encodable		content)
 {
     this.contentType = contentType;
     this.content = content;
 }
 public DistributionPointName(
     int				type,
     Asn1Encodable	name)
 {
     this.type = type;
     this.name = name;
 }
		public SigPolicyQualifierInfo(
			DerObjectIdentifier	sigPolicyQualifierId,
			Asn1Encodable		sigQualifier)
		{
			this.sigPolicyQualifierId = sigPolicyQualifierId;
			this.sigQualifier = sigQualifier.ToAsn1Object();
		}
Ejemplo n.º 8
0
		protected void checkMandatoryField(string name, Asn1Encodable expected, Asn1Encodable present)
		{
			if (!expected.Equals(present))
			{
				Fail(name + " field doesn't match.");
			}
		}
Ejemplo n.º 9
0
 public QCStatement(
     DerObjectIdentifier qcStatementId,
     Asn1Encodable       qcStatementInfo)
 {
     this.qcStatementId = qcStatementId;
     this.qcStatementInfo = qcStatementInfo;
 }
 public AttributeTypeAndValue(
     DerObjectIdentifier type,
     Asn1Encodable value)
 {
     this.type = type;
     this.value = value;
 }
Ejemplo n.º 11
0
 public InfoTypeAndValue(
     DerObjectIdentifier infoType,
     Asn1Encodable       optionalValue)
 {
     this.infoType = infoType;
     this.infoValue = optionalValue;
 }
Ejemplo n.º 12
0
        /**
         * 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;
        }
Ejemplo n.º 13
0
		public AlgorithmIdentifier(
            DerObjectIdentifier	objectID,
            Asn1Encodable		parameters)
        {
            this.objectID = objectID;
            this.parameters = parameters;
        }
Ejemplo n.º 14
0
		public SubjectPublicKeyInfo(
            AlgorithmIdentifier	algID,
            Asn1Encodable		publicKey)
        {
            this.keyData = new DerBitString(publicKey);
            this.algID = algID;
        }
Ejemplo n.º 15
0
		public CertStatus(
            int				tagNo,
            Asn1Encodable	value)
        {
            this.tagNo = tagNo;
            this.value = value;
        }
Ejemplo n.º 16
0
        private PopoPrivKey(Asn1TaggedObject obj)
        {
            this.tagNo = obj.TagNo;

            switch (tagNo)
            {
            case thisMessage:
                this.obj = DerBitString.GetInstance(obj, false);
                break;
            case subsequentMessage:
                this.obj = SubsequentMessage.ValueOf(DerInteger.GetInstance(obj, false).Value.IntValue);
                break;
            case dhMAC:
                this.obj = DerBitString.GetInstance(obj, false);
                break;
            case agreeMAC:
                this.obj = PKMacValue.GetInstance(obj, false);
                break;
            case encryptedKey:
                this.obj = EnvelopedData.GetInstance(obj, false);
                break;
            default:
                throw new ArgumentException("unknown tag in PopoPrivKey", "obj");
            }
        }
Ejemplo n.º 17
0
 public AlgorithmIdentifier(
     DerObjectIdentifier algorithm,
     Asn1Encodable		parameters)
 {
     this.algorithm = algorithm;
     this.parameters = parameters;
 }
Ejemplo n.º 18
0
 /**
  * Creates a new PkiBody.
  * @param type one of the TYPE_* constants
  * @param content message content
  */
 public PkiBody(
     int type,
     Asn1Encodable content)
 {
     tagNo = type;
     body = GetBodyForType(type, content);
 }
 public OtherRecipientInfo(
     DerObjectIdentifier	oriType,
     Asn1Encodable		oriValue)
 {
     this.oriType = oriType;
     this.oriValue = oriValue;
 }
Ejemplo n.º 20
0
		public OtherCertID(
			AlgorithmIdentifier	algId,
			byte[]				digest,
			IssuerSerial		issuerSerial)
		{
			this.otherCertHash = new DigestInfo(algId, digest);
			this.issuerSerial = issuerSerial;
		}
Ejemplo n.º 21
0
 /**
  * Dump out the object as a string
  *
  * @param obj the Asn1Encodable to be dumped out.
  * @param verbose  if true, dump out the contents of octet and bit strings.
  * @return  the resulting string.
  */
 public static string DumpAsString(
     Asn1Encodable	obj,
     bool			verbose)
 {
     StringBuilder buf = new StringBuilder();
     AsString("", verbose, obj.ToAsn1Object(), buf);
     return buf.ToString();
 }
Ejemplo n.º 22
0
 public PrivateKeyInfo(
     AlgorithmIdentifier	algID,
     Asn1Encodable       privateKey,
     Asn1Set				attributes)
 {
     this.algID = algID;
     this.privKey = new DerOctetString(privateKey.GetEncoded(Asn1Encodable.Der));
     this.attributes = attributes;
 }
Ejemplo n.º 23
0
        internal AlgorithmIdentifier(
            Asn1Sequence seq)
        {
            if (seq.Count < 1 || seq.Count > 2)
                throw new ArgumentException("Bad sequence size: " + seq.Count);

            this.algorithm = DerObjectIdentifier.GetInstance(seq[0]);
            this.parameters = seq.Count < 2 ? null : seq[1];
        }
Ejemplo n.º 24
0
        private InfoTypeAndValue(Asn1Sequence seq)
        {
            infoType = DerObjectIdentifier.GetInstance(seq[0]);

            if (seq.Count > 1)
            {
                infoValue = (Asn1Encodable)seq[1];
            }
        }
Ejemplo n.º 25
0
        /**
         * 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];
        }
Ejemplo n.º 26
0
		public EncryptedData(
            DerObjectIdentifier	contentType,
            AlgorithmIdentifier	encryptionAlgorithm,
            Asn1Encodable		content)
        {
			data = new BerSequence(
				contentType,
				encryptionAlgorithm.ToAsn1Object(),
				new BerTaggedObject(false, 0, content));
        }
Ejemplo n.º 27
0
		public Iso4217CurrencyCode(
            int numeric)
        {
            if (numeric > NumericMaxSize || numeric < NumericMinSize)
            {
                throw new ArgumentException("wrong size in numeric code : not in (" + NumericMinSize + ".." + NumericMaxSize + ")");
            }

			obj = new DerInteger(numeric);
        }
Ejemplo n.º 28
0
		public Iso4217CurrencyCode(
            string alphabetic)
        {
            if (alphabetic.Length > AlphabeticMaxSize)
            {
                throw new ArgumentException("wrong size in alphabetic code : max size is " + AlphabeticMaxSize);
            }

			obj = new DerPrintableString(alphabetic);
        }
Ejemplo n.º 29
0
		private QCStatement(
            Asn1Sequence seq)
        {
			qcStatementId = DerObjectIdentifier.GetInstance(seq[0]);

			if (seq.Count > 1)
			{
				qcStatementInfo = seq[1];
			}
        }
Ejemplo n.º 30
0
		public OtherRevRefs(
			DerObjectIdentifier	otherRevRefType,
			Asn1Encodable		otherRevRefs)
		{
			if (otherRevRefType == null)
				throw new ArgumentNullException("otherRevRefType");
			if (otherRevRefs == null)
				throw new ArgumentNullException("otherRevRefs");

			this.otherRevRefType = otherRevRefType;
			this.otherRevRefs = otherRevRefs.ToAsn1Object();
		}
Ejemplo n.º 31
0
 /// <summary>
 /// Don't use this one if you are trying to be RFC 3281 compliant.
 /// Use it for v1 attribute certificates only.
 /// </summary>
 /// <param name="names">Our GeneralNames structure</param>
 public AttCertIssuer(
     GeneralNames names)
 {
     obj       = names;
     choiceObj = obj.ToAsn1Object();
 }
 public OriginatorIdentifierOrKey(
     Asn1OctetString id)
 {
     this.id = new DerTaggedObject(false, 0, id);
 }
Ejemplo n.º 33
0
 public AttCertIssuer(
     V2Form v2Form)
 {
     obj       = v2Form;
     choiceObj = new DerTaggedObject(false, 0, obj);
 }
Ejemplo n.º 34
0
 public static string DumpAsString(Asn1Encodable obj)
 {
     return(DumpAsString(obj, verbose: false));
 }
Ejemplo n.º 35
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);

                    Asn1OctetString privEnc = keyInfo.PrivateKeyData;
                    if (privEnc.GetOctets().Length == 32 || privEnc.GetOctets().Length == 64)
                    {
                        byte[] dVal = Arrays.Reverse(privEnc.GetOctets());
                        d = new BigInteger(1, dVal);
                    }
                    else
                    {
                        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.º 36
0
        public static ICipherParameters GenerateCipherParameters(
            string algorithm,
            char[]          password,
            bool wrongPkcs12Zero,
            Asn1Encodable pbeParameters)
        {
            string mechanism = (string)algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];

            byte[] keyBytes;
            //string	type = (string)algorithmType[mechanism];
            byte[] salt;
            int    iterationCount;

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

            ICipherParameters parameters = null;

            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(parameters);
        }
        /**
         * generate an enveloped object that contains an CMS Enveloped Data
         * object using the given provider and the passed in key generator.
         */
        private CmsAuthenticatedData Generate(
            CmsProcessable content,
            string macOid,
            CipherKeyGenerator keyGen)
        {
            AlgorithmIdentifier macAlgId;
            KeyParameter        encKey;
            Asn1OctetString     encContent;
            Asn1OctetString     macResult;

            try
            {
                // FIXME Will this work for macs?
                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

                Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

                ICipherParameters cipherParameters;
                macAlgId = GetAlgorithmIdentifier(
                    macOid, encKey, asn1Params, out cipherParameters);

                IMac mac = MacUtilities.GetMac(macOid);
                // TODO Confirm no ParametersWithRandom needed
                // FIXME Only passing key at the moment
//	            mac.Init(cipherParameters);
                mac.Init(encKey);

                MemoryStream bOut = new MemoryStream();
                Stream       mOut = new TeeOutputStream(bOut, new MacOutputStream(mac));

                content.Write(mOut);

                Platform.Dispose(mOut);

                encContent = new BerOctetString(bOut.ToArray());

                byte[] macOctets = MacUtilities.DoFinal(mac);
                macResult = new DerOctetString(macOctets);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }

            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
            {
                try
                {
                    recipientInfos.Add(rig.Generate(encKey, rand));
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            ContentInfo eci = new ContentInfo(CmsObjectIdentifiers.Data, encContent);

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.AuthenticatedData,
                new AuthenticatedData(null, new DerSet(recipientInfos), macAlgId, null, eci, null, macResult, null));

            return(new CmsAuthenticatedData(contentInfo));
        }
Ejemplo n.º 38
0
 public ICertificateBuilder AddExtension(string oid, bool isCritical, Asn1Encodable value)
 {
     certificateGenerator.AddExtension(oid, isCritical, value);
     return(this);
 }
Ejemplo n.º 39
0
 public OtherKeyAttribute(Asn1Sequence seq)
 {
     this.keyAttrId = (DerObjectIdentifier)seq[0];
     this.keyAttr   = seq[1];
 }
Ejemplo n.º 40
0
 public ECPrivateKeyStructure(
     BigInteger key,
     Asn1Encodable parameters)
     : this(key, null, parameters)
 {
 }
Ejemplo n.º 41
0
 public PrivateKeyInfo(
     AlgorithmIdentifier privateKeyAlgorithm,
     Asn1Encodable privateKey)
     : this(privateKeyAlgorithm, privateKey, null, null)
 {
 }
Ejemplo n.º 42
0
 public KeyDerivationFunc(
     DerObjectIdentifier id,
     Asn1Encodable parameters)
     : base(id, parameters)
 {
 }
 public OriginatorIdentifierOrKey(
     OriginatorPublicKey id)
 {
     this.id = new DerTaggedObject(false, 1, id);
 }
 public OriginatorIdentifierOrKey(
     Asn1Object id)
 {
     this.id = id;
 }
Ejemplo n.º 45
0
 public PopoPrivKey(SubsequentMessage msg)
 {
     this.tagNo = subsequentMessage;
     this.obj   = msg;
 }
Ejemplo n.º 46
0
 public RecipientIdentifier(
     Asn1OctetString id)
 {
     this.id = new DerTaggedObject(false, 0, id);
 }
 public CertificateRequestMessageBuilder AddExtension(DerObjectIdentifier oid, bool critical,
                                                      Asn1Encodable value)
 {
     _extGenerator.AddExtension(oid, critical, value);
     return(this);
 }
Ejemplo n.º 48
0
 public RecipientInfo(
     Asn1Object info)
 {
     this.info = info;
 }
Ejemplo n.º 49
0
 public OtherKeyAttribute(DerObjectIdentifier keyAttrId, Asn1Encodable keyAttr)
 {
     this.keyAttrId = keyAttrId;
     this.keyAttr   = keyAttr;
 }
Ejemplo n.º 50
0
        public void Save(
            Stream stream,
            char[]                      password,
            SecureRandom random)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            if (random == null)
            {
                throw new ArgumentNullException("random");
            }

            //
            // handle the keys
            //
            Asn1EncodableVector keyBags = new Asn1EncodableVector();

            foreach (string name in keys.Keys)
            {
                byte[] kSalt = new byte[SaltSize];
                random.NextBytes(kSalt);

                AsymmetricKeyEntry privKey = (AsymmetricKeyEntry)keys[name];

                DerObjectIdentifier bagOid;
                Asn1Encodable       bagData;

                if (password == null)
                {
                    bagOid  = PkcsObjectIdentifiers.KeyBag;
                    bagData = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey.Key);
                }
                else
                {
                    bagOid  = PkcsObjectIdentifiers.Pkcs8ShroudedKeyBag;
                    bagData = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(
                        keyAlgorithm, password, kSalt, MinIterations, privKey.Key);
                }

                Asn1EncodableVector kName = new Asn1EncodableVector();

                foreach (string oid in privKey.BagAttributeKeys)
                {
                    Asn1Encodable entry = privKey[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    kName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (privKey[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (privKey[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    X509CertificateEntry   ct           = GetCertificate(name);
                    AsymmetricKeyParameter pubKey       = ct.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   subjectKeyID = CreateSubjectKeyID(pubKey);

                    kName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                keyBags.Add(new SafeBag(bagOid, bagData.ToAsn1Object(), new DerSet(kName)));
            }

            byte[]      keyBagsEncoding = new DerSequence(keyBags).GetDerEncoded();
            ContentInfo keysInfo        = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(keyBagsEncoding));

            //
            // certificate processing
            //
            byte[] cSalt = new byte[SaltSize];

            random.NextBytes(cSalt);

            Asn1EncodableVector certBags = new Asn1EncodableVector();
            Pkcs12PbeParams     cParams  = new Pkcs12PbeParams(cSalt, MinIterations);
            AlgorithmIdentifier cAlgId   = new AlgorithmIdentifier(certAlgorithm, cParams.ToAsn1Object());
            ISet doneCerts = new HashSet();

            foreach (string name in keys.Keys)
            {
                X509CertificateEntry certEntry = GetCertificate(name);
                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(certEntry.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in certEntry.BagAttributeKeys)
                {
                    Asn1Encodable entry = certEntry[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'name'
                //if (certEntry[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(name))));
                }

                //
                // make sure we have a local key-id
                //
                if (certEntry[PkcsObjectIdentifiers.Pkcs9AtLocalKeyID] == null)
                {
                    AsymmetricKeyParameter pubKey       = certEntry.Certificate.GetPublicKey();
                    SubjectKeyIdentifier   subjectKeyID = CreateSubjectKeyID(pubKey);

                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtLocalKeyID,
                            new DerSet(subjectKeyID)));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(certEntry.Certificate);
            }

            foreach (string certId in certs.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)certs[certId];

                if (keys[certId] != null)
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                    {
                        continue;
                    }

                    Asn1Encodable entry = cert[oid];

                    // NB: Ignore any existing FriendlyName
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(entry)));
                }

                //
                // make sure we are using the local alias on store
                //
                // NB: We always set the FriendlyName based on 'certId'
                //if (cert[PkcsObjectIdentifiers.Pkcs9AtFriendlyName] == null)
                {
                    fName.Add(
                        new DerSequence(
                            PkcsObjectIdentifiers.Pkcs9AtFriendlyName,
                            new DerSet(new DerBmpString(certId))));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));

                doneCerts.Add(cert.Certificate);
            }

            foreach (CertId certId in chainCerts.Keys)
            {
                X509CertificateEntry cert = (X509CertificateEntry)chainCerts[certId];

                if (doneCerts.Contains(cert.Certificate))
                {
                    continue;
                }

                CertBag cBag = new CertBag(
                    PkcsObjectIdentifiers.X509Certificate,
                    new DerOctetString(cert.Certificate.GetEncoded()));

                Asn1EncodableVector fName = new Asn1EncodableVector();

                foreach (string oid in cert.BagAttributeKeys)
                {
                    // a certificate not immediately linked to a key doesn't require
                    // a localKeyID and will confuse some PKCS12 implementations.
                    //
                    // If we find one, we'll prune it out.
                    if (oid.Equals(PkcsObjectIdentifiers.Pkcs9AtLocalKeyID.Id))
                    {
                        continue;
                    }

                    fName.Add(
                        new DerSequence(
                            new DerObjectIdentifier(oid),
                            new DerSet(cert[oid])));
                }

                certBags.Add(new SafeBag(PkcsObjectIdentifiers.CertBag, cBag.ToAsn1Object(), new DerSet(fName)));
            }

            byte[] certBagsEncoding = new DerSequence(certBags).GetDerEncoded();

            ContentInfo certsInfo;

            if (password == null)
            {
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(certBagsEncoding));
            }
            else
            {
                byte[]        certBytes = CryptPbeData(true, cAlgId, password, false, certBagsEncoding);
                EncryptedData cInfo     = new EncryptedData(PkcsObjectIdentifiers.Data, cAlgId, new BerOctetString(certBytes));
                certsInfo = new ContentInfo(PkcsObjectIdentifiers.EncryptedData, cInfo.ToAsn1Object());
            }

            ContentInfo[] info = new ContentInfo[] { keysInfo, certsInfo };

            byte[] data = new AuthenticatedSafe(info).GetEncoded(
                useDerEncoding ? Asn1Encodable.Der : Asn1Encodable.Ber);

            ContentInfo mainInfo = new ContentInfo(PkcsObjectIdentifiers.Data, new BerOctetString(data));

            //
            // create the mac
            //
            MacData macData = null;

            if (password != null)
            {
                byte[] mSalt = new byte[20];
                random.NextBytes(mSalt);

                byte[] mac = CalculatePbeMac(OiwObjectIdentifiers.IdSha1,
                                             mSalt, MinIterations, password, false, data);

                AlgorithmIdentifier algId = new AlgorithmIdentifier(
                    OiwObjectIdentifiers.IdSha1, DerNull.Instance);
                DigestInfo dInfo = new DigestInfo(algId, mac);

                macData = new MacData(dInfo, mSalt, MinIterations);
            }

            //
            // output the Pfx
            //
            Pfx pfx = new Pfx(mainInfo, macData);

            DerOutputStream derOut;

            if (useDerEncoding)
            {
                derOut = new DerOutputStream(stream);
            }
            else
            {
                derOut = new BerOutputStream(stream);
            }

            derOut.WriteObject(pfx);
        }
Ejemplo n.º 51
0
 public RecipientIdentifier(
     Asn1Object id)
 {
     this.id = id;
 }
Ejemplo n.º 52
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.Algorithm, 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.Algorithm, 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;
                    }
                }
            }
        }
Ejemplo n.º 53
0
 public RecipientIdentifier(
     IssuerAndSerialNumber id)
 {
     this.id = id;
 }
Ejemplo n.º 54
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;
            }
        }
 public EncryptionScheme(
     DerObjectIdentifier objectID,
     Asn1Encodable parameters)
     : base(objectID, parameters)
 {
 }
Ejemplo n.º 56
0
 public InfoTypeAndValue(
     DerObjectIdentifier infoType)
 {
     this.infoType  = infoType;
     this.infoValue = null;
 }
Ejemplo n.º 57
0
 private static void AsString(string indent, bool verbose, Asn1Object obj, StringBuilder buf)
 {
     if (obj is Asn1Sequence)
     {
         string text = indent + "    ";
         buf.Append(indent);
         if (obj is BerSequence)
         {
             buf.Append("BER Sequence");
         }
         else if (obj is DerSequence)
         {
             buf.Append("DER Sequence");
         }
         else
         {
             buf.Append("Sequence");
         }
         buf.Append(NewLine);
         {
             global::System.Collections.IEnumerator enumerator = ((Asn1Sequence)obj).GetEnumerator();
             try
             {
                 while (enumerator.MoveNext())
                 {
                     Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                     if (asn1Encodable == null || asn1Encodable is Asn1Null)
                     {
                         buf.Append(text);
                         buf.Append("NULL");
                         buf.Append(NewLine);
                     }
                     else
                     {
                         AsString(text, verbose, asn1Encodable.ToAsn1Object(), buf);
                     }
                 }
             }
             finally
             {
                 global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                 if (disposable != null)
                 {
                     disposable.Dispose();
                 }
             }
         }
     }
     else if (obj is DerTaggedObject)
     {
         string text2 = indent + "    ";
         buf.Append(indent);
         if (obj is BerTaggedObject)
         {
             buf.Append("BER Tagged [");
         }
         else
         {
             buf.Append("Tagged [");
         }
         DerTaggedObject derTaggedObject = (DerTaggedObject)obj;
         buf.Append(derTaggedObject.TagNo.ToString());
         buf.Append(']');
         if (!derTaggedObject.IsExplicit())
         {
             buf.Append(" IMPLICIT ");
         }
         buf.Append(NewLine);
         if (derTaggedObject.IsEmpty())
         {
             buf.Append(text2);
             buf.Append("EMPTY");
             buf.Append(NewLine);
         }
         else
         {
             AsString(text2, verbose, derTaggedObject.GetObject(), buf);
         }
     }
     else if (obj is BerSet)
     {
         string text3 = indent + "    ";
         buf.Append(indent);
         buf.Append("BER Set");
         buf.Append(NewLine);
         {
             global::System.Collections.IEnumerator enumerator = ((Asn1Set)obj).GetEnumerator();
             try
             {
                 while (enumerator.MoveNext())
                 {
                     Asn1Encodable asn1Encodable2 = (Asn1Encodable)enumerator.get_Current();
                     if (asn1Encodable2 == null)
                     {
                         buf.Append(text3);
                         buf.Append("NULL");
                         buf.Append(NewLine);
                     }
                     else
                     {
                         AsString(text3, verbose, asn1Encodable2.ToAsn1Object(), buf);
                     }
                 }
             }
             finally
             {
                 global::System.IDisposable disposable2 = enumerator as global::System.IDisposable;
                 if (disposable2 != null)
                 {
                     disposable2.Dispose();
                 }
             }
         }
     }
     else if (obj is DerSet)
     {
         string text4 = indent + "    ";
         buf.Append(indent);
         buf.Append("DER Set");
         buf.Append(NewLine);
         {
             global::System.Collections.IEnumerator enumerator = ((Asn1Set)obj).GetEnumerator();
             try
             {
                 while (enumerator.MoveNext())
                 {
                     Asn1Encodable asn1Encodable3 = (Asn1Encodable)enumerator.get_Current();
                     if (asn1Encodable3 == null)
                     {
                         buf.Append(text4);
                         buf.Append("NULL");
                         buf.Append(NewLine);
                     }
                     else
                     {
                         AsString(text4, verbose, asn1Encodable3.ToAsn1Object(), buf);
                     }
                 }
             }
             finally
             {
                 global::System.IDisposable disposable3 = enumerator as global::System.IDisposable;
                 if (disposable3 != null)
                 {
                     disposable3.Dispose();
                 }
             }
         }
     }
     else if (obj is DerObjectIdentifier)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "ObjectIdentifier(",
             ((DerObjectIdentifier)obj).Id,
             ")",
             NewLine
         }));
     }
     else if (obj is DerBoolean)
     {
         buf.Append(string.Concat(new object[5]
         {
             indent,
             "Boolean(",
             ((DerBoolean)obj).IsTrue,
             ")",
             NewLine
         }));
     }
     else if (obj is DerInteger)
     {
         buf.Append(string.Concat(new object[5]
         {
             indent,
             "Integer(",
             ((DerInteger)obj).Value,
             ")",
             NewLine
         }));
     }
     else if (obj is BerOctetString)
     {
         byte[] octets = ((Asn1OctetString)obj).GetOctets();
         string text5  = (verbose ? dumpBinaryDataAsString(indent, octets) : "");
         buf.Append(string.Concat(new object[6] {
             indent, "BER Octet String[", octets.Length, "] ", text5, NewLine
         }));
     }
     else if (obj is DerOctetString)
     {
         byte[] octets2 = ((Asn1OctetString)obj).GetOctets();
         string text6   = (verbose ? dumpBinaryDataAsString(indent, octets2) : "");
         buf.Append(string.Concat(new object[6] {
             indent, "DER Octet String[", octets2.Length, "] ", text6, NewLine
         }));
     }
     else if (obj is DerBitString)
     {
         DerBitString derBitString = (DerBitString)obj;
         byte[]       bytes        = derBitString.GetBytes();
         string       text7        = (verbose ? dumpBinaryDataAsString(indent, bytes) : "");
         buf.Append(string.Concat(new object[8] {
             indent, "DER Bit String[", bytes.Length, ", ", derBitString.PadBits, "] ", text7, NewLine
         }));
     }
     else if (obj is DerIA5String)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "IA5String(",
             ((DerIA5String)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerUtf8String)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "UTF8String(",
             ((DerUtf8String)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerPrintableString)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "PrintableString(",
             ((DerPrintableString)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerVisibleString)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "VisibleString(",
             ((DerVisibleString)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerBmpString)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "BMPString(",
             ((DerBmpString)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerT61String)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "T61String(",
             ((DerT61String)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerGraphicString)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "GraphicString(",
             ((DerGraphicString)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerVideotexString)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "VideotexString(",
             ((DerVideotexString)obj).GetString(),
             ") ",
             NewLine
         }));
     }
     else if (obj is DerUtcTime)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "UTCTime(",
             ((DerUtcTime)obj).TimeString,
             ") ",
             NewLine
         }));
     }
     else if (obj is DerGeneralizedTime)
     {
         buf.Append(string.Concat(new string[5]
         {
             indent,
             "GeneralizedTime(",
             ((DerGeneralizedTime)obj).GetTime(),
             ") ",
             NewLine
         }));
     }
     else if (obj is BerApplicationSpecific)
     {
         buf.Append(outputApplicationSpecific("BER", indent, verbose, (BerApplicationSpecific)obj));
     }
     else if (obj is DerApplicationSpecific)
     {
         buf.Append(outputApplicationSpecific("DER", indent, verbose, (DerApplicationSpecific)obj));
     }
     else if (obj is DerEnumerated)
     {
         DerEnumerated derEnumerated = (DerEnumerated)obj;
         buf.Append(string.Concat(new object[5] {
             indent, "DER Enumerated(", derEnumerated.Value, ")", NewLine
         }));
     }
     else if (obj is DerExternal)
     {
         DerExternal derExternal = (DerExternal)obj;
         buf.Append(indent + "External " + NewLine);
         string text8 = indent + "    ";
         if (derExternal.DirectReference != null)
         {
             buf.Append(text8 + "Direct Reference: " + derExternal.DirectReference.Id + NewLine);
         }
         if (derExternal.IndirectReference != null)
         {
             buf.Append(text8 + "Indirect Reference: " + derExternal.IndirectReference.ToString() + NewLine);
         }
         if (derExternal.DataValueDescriptor != null)
         {
             AsString(text8, verbose, derExternal.DataValueDescriptor, buf);
         }
         buf.Append(string.Concat(new object[4] {
             text8, "Encoding: ", derExternal.Encoding, NewLine
         }));
         AsString(text8, verbose, derExternal.ExternalContent, buf);
     }
     else
     {
         buf.Append(indent + ((object)obj).ToString() + NewLine);
     }
 }
Ejemplo n.º 58
0
 public InfoTypeAndValue(DerObjectIdentifier infoType, Asn1Encodable optionalValue)
 {
     this.infoType = infoType;
     infoValue     = optionalValue;
 }
Ejemplo n.º 59
0
 private OtherRevocationInfoFormat(Asn1Sequence seq)
 {
     otherRevInfoFormat = DerObjectIdentifier.GetInstance(seq[0]);
     otherRevInfo       = seq[1];
 }
 public OriginatorIdentifierOrKey(
     IssuerAndSerialNumber id)
 {
     this.id = id;
 }