Inheritance: Org.BouncyCastle.Asn1.Asn1Encodable
Esempio n. 1
0
        internal KeyTransRecipientInformation(KeyTransRecipientInfo info, CmsSecureReadable secureReadable) : base(info.KeyEncryptionAlgorithm, secureReadable)
        {
            this.info = info;
            this.rid  = new RecipientID();
            RecipientIdentifier recipientIdentifier = info.RecipientIdentifier;

            try
            {
                if (recipientIdentifier.IsTagged)
                {
                    Asn1OctetString instance = Asn1OctetString.GetInstance(recipientIdentifier.ID);
                    this.rid.SubjectKeyIdentifier = instance.GetOctets();
                }
                else
                {
                    Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber instance2 = Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber.GetInstance(recipientIdentifier.ID);
                    this.rid.Issuer       = instance2.Name;
                    this.rid.SerialNumber = instance2.SerialNumber.Value;
                }
            }
            catch (IOException)
            {
                throw new ArgumentException("invalid rid in KeyTransRecipientInformation");
            }
        }
Esempio n. 2
0
        /// <summary>
        /// RFC 3852의 EnvelopedData 구조체 중 KeyTransRecipientInfo 항목을 생성하고
        /// 이를 이용해 RecipientInfo 구조체를 생성한다.
        /// </summary>
        /// <param name="x509_certificate2">키를 암호화하기 위한 공인인증서(국세청 공인인증서)</param>
        /// <param name="random_key">암호화에 사용된 램덤 키</param>
        /// <returns></returns>
        private RecipientInfo GetKeyTransRecipientInfo(X509Certificate2 x509_certificate2, byte[] random_key)
        {
            // RecipientIdentifier 필드에는 누구의 공개키를 이용하였는지에 대한 정보가 들어간다.
            // IssuerAndSerialNumber(ASN.1 형태) 데이터를 생성하기 위하여 파라미터로 전달받은 cert 를 Org.BouncyCastle.X509.X509Certificate 타입으로 변환한다.
            X509CertificateParser _x509Parser = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate _bouncyCert = _x509Parser.ReadCertificate(x509_certificate2.GetRawCertData());

            // IssuerAndSerialNumber 데이터를 생성한다.
            Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber _issuerAndSerial = new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(_bouncyCert.IssuerDN, new DerInteger(_bouncyCert.SerialNumber));

            // IssuerAndSerialNumber 데이터를 이용하여 RecipientIdentifier 형태의 데이터를 생성한다.
            RecipientIdentifier _rid = new RecipientIdentifier(_issuerAndSerial.ToAsn1Object());

            // 대칭키 알고리즘에 사용된 키를 암호화할 때 이용되는 암호화 알고리즘에 대한 OID
            // 암호화 알고리즘 : RSA (비대칭 알고리즘)
            // OID : 1.2.840.113549.1.1.1
            AlgorithmIdentifier _keyEncryptionAlgorithm = new AlgorithmIdentifier(new DerObjectIdentifier("1.2.840.113549.1.1.1"));

            // 랜덤키를 공개키를 사용해 암호화 한다.
            RSACryptoServiceProvider _rsaCrypto = (RSACryptoServiceProvider)x509_certificate2.PublicKey.Key;

            byte[]          _byteEncryptedKey = _rsaCrypto.Encrypt(random_key, false);         // 대칭키를 암호화
            Asn1OctetString _encryptedKey     = new BerOctetString(_byteEncryptedKey);

            // KeyTransRecipientInfo 구조체를 생성, 설정한다.
            KeyTransRecipientInfo _keyTransRecipientInfo = new KeyTransRecipientInfo(_rid, _keyEncryptionAlgorithm, _encryptedKey);

            // KeyTransRecipientInfo 구조체를 이용하여 RecipientInfo를 생성 및 설정한다.
            return(new RecipientInfo(_keyTransRecipientInfo));
        }
        private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        {
            TbsCertificateStructure certificate;

            using (Asn1InputStream input = new Asn1InputStream(x509certificate.GetTbsCertificate()))
            {
                certificate = TbsCertificateStructure.GetInstance(input.ReadObject());
            }

            AlgorithmIdentifier algorithmId = certificate.SubjectPublicKeyInfo.AlgorithmID;

            var             serial = new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(certificate.Issuer, certificate.SerialNumber.Value);
            IBufferedCipher cipher;

            try
            {
                cipher = CipherUtilities.GetCipher(algorithmId.Algorithm.Id);
            }
            catch (Exception e)
            {
                // should never happen, if this happens throw IOException instead
                throw new Exception("Could not find a suitable javax.crypto provider", e);
            }

            cipher.Init(true, x509certificate.GetPublicKey());

            DerOctetString      octets      = new DerOctetString(cipher.DoFinal(abyte0));
            RecipientIdentifier recipientId = new RecipientIdentifier(serial);

            return(new KeyTransRecipientInfo(recipientId, algorithmId, octets));
        }
Esempio n. 4
0
        private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        {
            Asn1InputStream asn1inputstream =
                new Asn1InputStream(new MemoryStream(x509certificate.GetTbsCertificate()));
            TbsCertificateStructure tbscertificatestructure =
                TbsCertificateStructure.GetInstance(asn1inputstream.ReadObject());
            AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.SubjectPublicKeyInfo.AlgorithmID;

            Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerandserialnumber =
                new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(
                    tbscertificatestructure.Issuer,
                    tbscertificatestructure.SerialNumber.Value);
            IBufferedCipher cipher = CipherUtilities.GetCipher(algorithmidentifier.ObjectID);

            cipher.Init(true, x509certificate.GetPublicKey());
            byte[] outp = new byte[10000];
            int    len  = cipher.DoFinal(abyte0, outp, 0);

            byte[] abyte1 = new byte[len];
            System.Array.Copy(outp, 0, abyte1, 0, len);
            DerOctetString      deroctetstring = new DerOctetString(abyte1);
            RecipientIdentifier recipId        = new RecipientIdentifier(issuerandserialnumber);

            return(new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring));
        }
 internal static void ReadRecipientInfo(IList infos, KeyAgreeRecipientInfo info, CmsSecureReadable secureReadable)
 {
     try
     {
         foreach (Asn1Encodable asn1Encodable in info.RecipientEncryptedKeys)
         {
             RecipientEncryptedKey       instance    = RecipientEncryptedKey.GetInstance(asn1Encodable.ToAsn1Object());
             RecipientID                 recipientID = new RecipientID();
             KeyAgreeRecipientIdentifier identifier  = instance.Identifier;
             Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerAndSerialNumber = identifier.IssuerAndSerialNumber;
             if (issuerAndSerialNumber != null)
             {
                 recipientID.Issuer       = issuerAndSerialNumber.Name;
                 recipientID.SerialNumber = issuerAndSerialNumber.SerialNumber.Value;
             }
             else
             {
                 RecipientKeyIdentifier rKeyID = identifier.RKeyID;
                 recipientID.SubjectKeyIdentifier = rKeyID.SubjectKeyIdentifier.GetOctets();
             }
             infos.Add(new KeyAgreeRecipientInformation(info, recipientID, instance.EncryptedKey, secureReadable));
         }
     }
     catch (IOException innerException)
     {
         throw new ArgumentException("invalid rid in KeyAgreeRecipientInformation", innerException);
     }
 }
 internal SignerInformation(Org.BouncyCastle.Asn1.Cms.SignerInfo info, DerObjectIdentifier contentType, CmsProcessable content, IDigestCalculator digestCalculator)
 {
     this.info               = info;
     this.sid                = new SignerID();
     this.contentType        = contentType;
     this.isCounterSignature = (contentType == null);
     try
     {
         SignerIdentifier signerID = info.SignerID;
         if (signerID.IsTagged)
         {
             Asn1OctetString instance = Asn1OctetString.GetInstance(signerID.ID);
             this.sid.SubjectKeyIdentifier = instance.GetEncoded();
         }
         else
         {
             Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber instance2 = Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber.GetInstance(signerID.ID);
             this.sid.Issuer       = instance2.Name;
             this.sid.SerialNumber = instance2.SerialNumber.Value;
         }
     }
     catch (IOException)
     {
         throw new ArgumentException("invalid sid in SignerInfo");
     }
     this.digestAlgorithm      = info.DigestAlgorithm;
     this.signedAttributeSet   = info.AuthenticatedAttributes;
     this.unsignedAttributeSet = info.UnauthenticatedAttributes;
     this.encryptionAlgorithm  = info.DigestEncryptionAlgorithm;
     this.signature            = info.EncryptedDigest.GetOctets();
     this.content          = content;
     this.digestCalculator = digestCalculator;
 }
Esempio n. 7
0
        public static IssuerAndSerialNumber GetInstance(object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            IssuerAndSerialNumber issuerAndSerialNumber = obj as IssuerAndSerialNumber;

            if (issuerAndSerialNumber != null)
            {
                return(issuerAndSerialNumber);
            }
            return(new IssuerAndSerialNumber(Asn1Sequence.GetInstance(obj)));
        }
Esempio n. 8
0
        public static IssuerAndSerialNumber GetInstance(object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            IssuerAndSerialNumber existing = obj as IssuerAndSerialNumber;

            if (existing != null)
            {
                return(existing);
            }
            return(new IssuerAndSerialNumber(Asn1Sequence.GetInstance(obj)));
        }
Esempio n. 9
0
 public static KeyAgreeRecipientIdentifier GetInstance(object obj)
 {
     if (obj == null || obj is KeyAgreeRecipientIdentifier)
     {
         return((KeyAgreeRecipientIdentifier)obj);
     }
     if (obj is Asn1Sequence)
     {
         return(new KeyAgreeRecipientIdentifier(IssuerAndSerialNumber.GetInstance(obj)));
     }
     if (obj is Asn1TaggedObject && ((Asn1TaggedObject)obj).TagNo == 0)
     {
         return(new KeyAgreeRecipientIdentifier(RecipientKeyIdentifier.GetInstance((Asn1TaggedObject)obj, false)));
     }
     throw new ArgumentException("Invalid KeyAgreeRecipientIdentifier: " + obj.GetType().FullName, "obj");
 }
Esempio n. 10
0
 internal static void ReadRecipientInfo(global::System.Collections.IList infos, KeyAgreeRecipientInfo info, CmsSecureReadable secureReadable)
 {
     //IL_00bb: Expected O, but got Unknown
     //IL_00c2: Unknown result type (might be due to invalid IL or missing references)
     try
     {
         global::System.Collections.IEnumerator enumerator = info.RecipientEncryptedKeys.GetEnumerator();
         try
         {
             while (enumerator.MoveNext())
             {
                 Asn1Encodable               asn1Encodable = (Asn1Encodable)enumerator.get_Current();
                 RecipientEncryptedKey       instance      = RecipientEncryptedKey.GetInstance(asn1Encodable.ToAsn1Object());
                 RecipientID                 recipientID   = new RecipientID();
                 KeyAgreeRecipientIdentifier identifier    = instance.Identifier;
                 Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerAndSerialNumber = identifier.IssuerAndSerialNumber;
                 if (issuerAndSerialNumber != null)
                 {
                     recipientID.Issuer       = issuerAndSerialNumber.Name;
                     recipientID.SerialNumber = issuerAndSerialNumber.SerialNumber.Value;
                 }
                 else
                 {
                     RecipientKeyIdentifier rKeyID = identifier.RKeyID;
                     recipientID.SubjectKeyIdentifier = rKeyID.SubjectKeyIdentifier.GetOctets();
                 }
                 infos.Add((object)new KeyAgreeRecipientInformation(info, recipientID, instance.EncryptedKey, secureReadable));
             }
         }
         finally
         {
             global::System.IDisposable disposable = enumerator as global::System.IDisposable;
             if (disposable != null)
             {
                 disposable.Dispose();
             }
         }
     }
     catch (IOException val)
     {
         IOException val2 = val;
         throw new ArgumentException("invalid rid in KeyAgreeRecipientInformation", (global::System.Exception)(object) val2);
     }
 }
        public static IssuerAndSerialNumber GetInstance(object obj)
        {
            if (obj == null)
            {
                return(null);
            }
            IssuerAndSerialNumber existing = obj as IssuerAndSerialNumber;

            if (existing != null)
            {
                return(existing);
            }

// Disable warning since using GetInstance would result in an infinite loop
#pragma warning disable 618
            return(new IssuerAndSerialNumber(Asn1Sequence.GetInstance(obj)));

#pragma warning restore 618
        }
        private AsymmetricKeyParameter GetSenderPublicKey(AsymmetricKeyParameter receiverPrivateKey, OriginatorIdentifierOrKey originator)
        {
            OriginatorPublicKey originatorPublicKey = originator.OriginatorPublicKey;

            if (originatorPublicKey != null)
            {
                return(this.GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, originatorPublicKey));
            }
            OriginatorID originatorID = new OriginatorID();

            Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerAndSerialNumber = originator.IssuerAndSerialNumber;
            if (issuerAndSerialNumber != null)
            {
                originatorID.Issuer       = issuerAndSerialNumber.Name;
                originatorID.SerialNumber = issuerAndSerialNumber.SerialNumber.Value;
            }
            else
            {
                SubjectKeyIdentifier subjectKeyIdentifier = originator.SubjectKeyIdentifier;
                originatorID.SubjectKeyIdentifier = subjectKeyIdentifier.GetKeyIdentifier();
            }
            return(this.GetPublicKeyFromOriginatorID(originatorID));
        }
		public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
		{
			byte[] keyBytes = contentEncryptionKey.GetKey();
			AlgorithmIdentifier keyEncryptionAlgorithm = info.AlgorithmID;

            IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionAlgorithm.Algorithm.Id);
			keyWrapper.Init(true, new ParametersWithRandom(recipientPublicKey, random));
			byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

			RecipientIdentifier recipId;
			if (recipientTbsCert != null)
			{
				IssuerAndSerialNumber issuerAndSerial = new IssuerAndSerialNumber(
					recipientTbsCert.Issuer, recipientTbsCert.SerialNumber.Value);
				recipId = new RecipientIdentifier(issuerAndSerial);
			}
			else
			{
				recipId = new RecipientIdentifier(subjectKeyIdentifier);
			}

			return new RecipientInfo(new KeyTransRecipientInfo(recipId, keyEncryptionAlgorithm,
				new DerOctetString(encryptedKeyBytes)));
		}
			internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType)
            {
                AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(this._digestOID), DerNull.Instance);
				AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid);

				byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)];

				outer._digests[_digestOID] = hash.Clone();

				IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

				Asn1.Cms.AttributeTable signed = (_sAttr != null)
//					?	_sAttr.GetAttributes(Collections.unmodifiableMap(parameters))
					?	_sAttr.GetAttributes(parameters)
					:	null;

				Asn1Set signedAttr = outer.GetAttributeSet(signed);

                //
                // sig must be composed from the DER encoding.
                //
				byte[] tmp;
				if (signedAttr != null)
                {
					tmp = signedAttr.GetEncoded(Asn1Encodable.Der);
				}
                else
                {
					throw new Exception("signatures without signed attributes not implemented.");
				}

				_signature.BlockUpdate(tmp, 0, tmp.Length);

				Asn1OctetString	encDigest = new DerOctetString(_signature.GenerateSignature());

				parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
				parameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone();

				Asn1.Cms.AttributeTable unsigned = (_unsAttr != null)
//					?	_unsAttr.getAttributes(Collections.unmodifiableMap(parameters))
					?	_unsAttr.GetAttributes(parameters)
					:	null;

				Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned);

                X509Certificate cert = this.Certificate;
				SignerIdentifier signerIdentifier;
				if (cert != null)
				{
	                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
						Asn1Object.FromByteArray(cert.GetTbsCertificate()));
	                IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(
						tbs.Issuer, tbs.SerialNumber.Value);

					signerIdentifier = new SignerIdentifier(encSid);
				}
				else
				{
					signerIdentifier = new SignerIdentifier(new DerOctetString(_subjectKeyID));
				}

				return new SignerInfo(signerIdentifier, digAlgId,
					signedAttr, encAlgId, encDigest, unsignedAttr);
            }
		private KeyAgreeRecipientIdentifier(
			Asn1Sequence seq)
		{
			this.issuerSerial = IssuerAndSerialNumber.GetInstance(seq);
		}
Esempio n. 16
0
 public SignerIdentifier(IssuerAndSerialNumber id)
 {
     this.id = id;
 }
 public SmimeEncryptionKeyPreferenceAttribute(
     IssuerAndSerialNumber issAndSer)
     : base(SmimeAttributes.EncrypKeyPref,
         new DerSet(new DerTaggedObject(false, 0, issAndSer)))
 {
 }
 private KeyTransRecipientInfo ComputeRecipientInfo(X509Certificate x509certificate, byte[] abyte0) {
     Asn1InputStream asn1inputstream = 
         new Asn1InputStream(new MemoryStream(x509certificate.GetTbsCertificate()));
     TbsCertificateStructure tbscertificatestructure = 
         TbsCertificateStructure.GetInstance(asn1inputstream.ReadObject());
     AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.SubjectPublicKeyInfo.AlgorithmID;
     Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber issuerandserialnumber = 
         new Org.BouncyCastle.Asn1.Cms.IssuerAndSerialNumber(
             tbscertificatestructure.Issuer, 
             tbscertificatestructure.SerialNumber.Value);
     IBufferedCipher cipher = CipherUtilities.GetCipher(algorithmidentifier.ObjectID);
     cipher.Init(true, x509certificate.GetPublicKey());
     byte[] outp = new byte[10000];
     int len = cipher.DoFinal(abyte0, outp, 0);
     byte[] abyte1 = new byte[len];
     System.Array.Copy(outp, 0, abyte1, 0, len);
     DerOctetString deroctetstring = new DerOctetString(abyte1);
     RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
     return new KeyTransRecipientInfo( recipId, algorithmidentifier, deroctetstring);
 }        
            //            internal Asn1.Cms.AttributeTable SignedAttributes
            //            {
            //                get { return _sAttr; }
            //            }
            //
            //            internal Asn1.Cms.AttributeTable UnsignedAttributes
            //            {
            //                get { return _unsAttr; }
            //            }
            internal SignerInfo ToSignerInfo(
                DerObjectIdentifier contentType)
            {
                AlgorithmIdentifier digAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(this.DigestAlgOid), DerNull.Instance);
                AlgorithmIdentifier encAlgId = CmsSignedGenerator.GetEncAlgorithmIdentifier(this.EncryptionAlgOid);

                byte[] hash = DigestUtilities.DoFinal(_digest);

                outer._digests.Add(_digestOID, hash.Clone());

                IDictionary parameters = outer.GetBaseParameters(contentType, digAlgId, hash);

                Asn1.Cms.AttributeTable signed = (_sAttr != null)
                //					?	_sAttr.GetAttributes(Collections.unmodifiableMap(parameters))
                    ?	_sAttr.GetAttributes(parameters)
                    :	null;

                Asn1Set signedAttr = outer.GetAttributeSet(signed);

                //
                // sig must be composed from the DER encoding.
                //
                byte[] bOutBytes;
                if (signedAttr != null)
                {
                    bOutBytes = signedAttr.GetDerEncoded();
                }
                else
                {
                    throw new Exception("signatures without signed attributes not implemented.");
                }

                _signature.BlockUpdate(bOutBytes, 0, bOutBytes.Length);

                Asn1OctetString	encDigest = new DerOctetString(_signature.GenerateSignature());

                parameters = outer.GetBaseParameters(contentType, digAlgId, hash);
                parameters[CmsAttributeTableParameter.Signature] = encDigest.GetOctets().Clone();

                Asn1.Cms.AttributeTable unsigned = (_unsAttr != null)
                //					?	_unsAttr.getAttributes(Collections.unmodifiableMap(parameters))
                    ?	_unsAttr.GetAttributes(parameters)
                    :	null;

                Asn1Set unsignedAttr = outer.GetAttributeSet(unsigned);

                X509Certificate cert = this.Certificate;
                TbsCertificateStructure tbs = TbsCertificateStructure.GetInstance(
                    Asn1Object.FromByteArray(cert.GetTbsCertificate()));
                IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(
                    tbs.Issuer, tbs.SerialNumber.Value);

                return new SignerInfo(new SignerIdentifier(encSid), digAlgId,
                    signedAttr, encAlgId, encDigest, unsignedAttr);
            }
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            IAsymmetricKeyParameter senderPublicKey = senderKeyPair.Public;
            ICipherParameters senderPrivateParams = senderKeyPair.Private;

            OriginatorIdentifierOrKey originator;
            try
            {
                originator = new OriginatorIdentifierOrKey(
                    CreateOriginatorPublicKey(senderPublicKey));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }

            Asn1OctetString ukm = null;
            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator ephemKPG =
                        GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    ephemKPG.Init(
                        ((ECPublicKeyParameters)senderPublicKey).CreateKeyGenerationParameters(random));

                    IAsymmetricCipherKeyPair ephemKP = ephemKPG.GenerateKeyPair();

                    ukm = new DerOctetString(
                        new MQVuserKeyingMaterial(
                            CreateOriginatorPublicKey(ephemKP.Public), null));

                    senderPrivateParams = new MqvPrivateParameters(
                        (ECPrivateKeyParameters)senderPrivateParams,
                        (ECPrivateKeyParameters)ephemKP.Private,
                        (ECPublicKeyParameters)ephemKP.Public);
                }
                catch (IOException e)
                {
                    throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + e);
                }
                catch (SecurityUtilityException e)
                {
                    throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + e);
                }
            }

            DerSequence paramSeq = new DerSequence(
                keyEncryptionOID,
                DerNull.Instance);
            AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(keyAgreementOID, paramSeq);

            Asn1EncodableVector recipientEncryptedKeys = new Asn1EncodableVector();
            foreach (X509Certificate recipientCert in recipientCerts)
            {
                TbsCertificateStructure tbsCert;
                try
                {
                    tbsCert = TbsCertificateStructure.GetInstance(
                        Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
                }
                catch (Exception)
                {
                    throw new ArgumentException("can't extract TBS structure from certificate");
                }

                // TODO Should there be a SubjectKeyIdentifier-based alternative?
                IssuerAndSerialNumber issuerSerial = new IssuerAndSerialNumber(
                    tbsCert.Issuer, tbsCert.SerialNumber.Value);
                KeyAgreeRecipientIdentifier karid = new KeyAgreeRecipientIdentifier(issuerSerial);

                ICipherParameters recipientPublicParams = recipientCert.GetPublicKey();
                if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                {
                    recipientPublicParams = new MqvPublicParameters(
                        (ECPublicKeyParameters)recipientPublicParams,
                        (ECPublicKeyParameters)recipientPublicParams);
                }

                // Use key agreement to choose a wrap key for this recipient
                IBasicAgreement keyAgreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    keyAgreementOID, keyEncryptionOID.Id);
                keyAgreement.Init(new ParametersWithRandom(senderPrivateParams, random));
                IBigInteger agreedValue = keyAgreement.CalculateAgreement(recipientPublicParams);

                int keyEncryptionKeySize = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                byte[] keyEncryptionKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, keyEncryptionKeySize);
                KeyParameter keyEncryptionKey = ParameterUtilities.CreateKeyParameter(
                    keyEncryptionOID, keyEncryptionKeyBytes);

                // Wrap the content encryption key with the agreement key
                IWrapper keyWrapper = Helper.CreateWrapper(keyEncryptionOID.Id);
                keyWrapper.Init(true, new ParametersWithRandom(keyEncryptionKey, random));
                byte[] encryptedKeyBytes = keyWrapper.Wrap(keyBytes, 0, keyBytes.Length);

                Asn1OctetString encryptedKey = new DerOctetString(encryptedKeyBytes);

                recipientEncryptedKeys.Add(new RecipientEncryptedKey(karid, encryptedKey));
            }

            return new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncAlg,
                new DerSequence(recipientEncryptedKeys)));
        }
Esempio n. 21
0
		public RecipientIdentifier(
            IssuerAndSerialNumber id)
        {
            this.id = id;
        }
 public RecipientIdentifier(IssuerAndSerialNumber id)
 {
     this.id = id;
 }
		public KeyAgreeRecipientIdentifier(
			IssuerAndSerialNumber issuerSerial)
		{
			this.issuerSerial = issuerSerial;
		}
 public OriginatorIdentifierOrKey(
     IssuerAndSerialNumber id)
 {
     this.id = id;
 }
Esempio n. 25
0
 public KeyAgreeRecipientIdentifier(IssuerAndSerialNumber issuerSerial)
 {
     this.issuerSerial = issuerSerial;
 }
Esempio n. 26
0
 private KeyAgreeRecipientIdentifier(
     Asn1Sequence seq)
 {
     this.issuerSerial = IssuerAndSerialNumber.GetInstance(seq);
 }
Esempio n. 27
0
		public SignerIdentifier(
            IssuerAndSerialNumber id)
        {
            this.id = id;
        }
 public OriginatorIdentifierOrKey(
     IssuerAndSerialNumber id)
 {
     this.id = id;
 }