Beispiel #1
0
        /**
         * Add a key agreement based recipient.
         *
         * @param agreementAlgorithm key agreement algorithm to use.
         * @param senderPrivateKey private key to initialise sender side of agreement with.
         * @param senderPublicKey sender public key to include with message.
         * @param recipientCert recipient's public key certificate.
         * @param cekWrapAlgorithm OID for key wrapping algorithm to use.
         * @exception SecurityUtilityException if the algorithm requested cannot be found
         * @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
         */
        public void AddKeyAgreementRecipient(
            string agreementAlgorithm,
            AsymmetricKeyParameter senderPrivateKey,
            AsymmetricKeyParameter senderPublicKey,
            X509Certificate recipientCert,
            string cekWrapAlgorithm)
        {
            if (!senderPrivateKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "senderPrivateKey");
            }
            if (senderPublicKey.IsPrivate)
            {
                throw new ArgumentException("Expected public key", "senderPublicKey");
            }

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                agreementAlgorithm, cekWrapAlgorithm);

            agreement.Init(new ParametersWithRandom(senderPrivateKey, rand));

            BigInteger secretNum = agreement.CalculateAgreement(recipientCert.GetPublicKey());

            try
            {
                SubjectPublicKeyInfo oPubKeyInfo =
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(senderPublicKey);

                OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
                    new OriginatorPublicKey(
                        new AlgorithmIdentifier(oPubKeyInfo.AlgorithmID.ObjectID, DerNull.Instance),
                        oPubKeyInfo.PublicKeyData.GetBytes()));

                // TODO Fix the way bytes are derived from the secret
                byte[]       secretBytes = secretNum.ToByteArrayUnsigned();
                KeyParameter secret      = ParameterUtilities.CreateKeyParameter(
                    cekWrapAlgorithm, secretBytes);

                recipientInfs.Add(
                    new RecipientInf(cekWrapAlgorithm, secret, agreementAlgorithm,
                                     cekWrapAlgorithm, originator, recipientCert));
            }
            catch (IOException e)
            {
                throw new InvalidKeyException("cannot extract originator public key: " + e);
            }
        }
Beispiel #2
0
        private KeyParameter CalculateAgreedWrapKey(
            string wrapAlg,
            AsymmetricKeyParameter senderPublicKey,
            AsymmetricKeyParameter receiverPrivateKey)
        {
            DerObjectIdentifier agreeAlgID = keyEncAlg.Algorithm;

            ICipherParameters senderPublicParams    = senderPublicKey;
            ICipherParameters receiverPrivateParams = receiverPrivateKey;

            if (agreeAlgID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                byte[] ukmEncoding        = info.UserKeyingMaterial.GetOctets();
                MQVuserKeyingMaterial ukm = MQVuserKeyingMaterial.GetInstance(
                    Asn1Object.FromByteArray(ukmEncoding));

                AsymmetricKeyParameter ephemeralKey = GetPublicKeyFromOriginatorPublicKey(
                    receiverPrivateKey, ukm.EphemeralPublicKey);

                senderPublicParams = new MqvPublicParameters(
                    (ECPublicKeyParameters)senderPublicParams,
                    (ECPublicKeyParameters)ephemeralKey);
                receiverPrivateParams = new MqvPrivateParameters(
                    (ECPrivateKeyParameters)receiverPrivateParams,
                    (ECPrivateKeyParameters)receiverPrivateParams);
            }

            IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                agreeAlgID, wrapAlg);

            agreement.Init(receiverPrivateParams);
            BigInteger agreedValue = agreement.CalculateAgreement(senderPublicParams);

            int wrapKeySize = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;

            byte[] wrapKeyBytes = X9IntegerConverter.IntegerToBytes(agreedValue, wrapKeySize);
            return(ParameterUtilities.CreateKeyParameter(wrapAlg, wrapKeyBytes));
        }
        private KeyParameter CalculateAgreedWrapKey(string wrapAlg, AsymmetricKeyParameter senderPublicKey, AsymmetricKeyParameter receiverPrivateKey)
        {
            DerObjectIdentifier objectID          = this.keyEncAlg.ObjectID;
            ICipherParameters   cipherParameters  = senderPublicKey;
            ICipherParameters   cipherParameters2 = receiverPrivateKey;

            if (objectID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                byte[] octets = this.info.UserKeyingMaterial.GetOctets();
                MQVuserKeyingMaterial  instance = MQVuserKeyingMaterial.GetInstance(Asn1Object.FromByteArray(octets));
                AsymmetricKeyParameter publicKeyFromOriginatorPublicKey = this.GetPublicKeyFromOriginatorPublicKey(receiverPrivateKey, instance.EphemeralPublicKey);
                cipherParameters  = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters, (ECPublicKeyParameters)publicKeyFromOriginatorPublicKey);
                cipherParameters2 = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters2, (ECPrivateKeyParameters)cipherParameters2);
            }
            IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(objectID, wrapAlg);

            basicAgreementWithKdf.Init(cipherParameters2);
            BigInteger s       = basicAgreementWithKdf.CalculateAgreement(cipherParameters);
            int        qLength = GeneratorUtilities.GetDefaultKeySize(wrapAlg) / 8;

            byte[] keyBytes = X9IntegerConverter.IntegerToBytes(s, qLength);
            return(ParameterUtilities.CreateKeyParameter(wrapAlg, keyBytes));
        }
        /**
         * decrypt the content and return an input stream.
         */
        public override CmsTypedStream GetContentStream(
//			Key key)
            ICipherParameters key)
        {
            if (!(key is AsymmetricKeyParameter))
            {
                throw new ArgumentException("KeyAgreement requires asymmetric key", "key");
            }

            AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)key;

            if (!privKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "key");
            }

            try
            {
                OriginatorPublicKey    origK    = _info.Originator.OriginatorKey;
                PrivateKeyInfo         privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
                SubjectPublicKeyInfo   pubInfo  = new SubjectPublicKeyInfo(privInfo.AlgorithmID, origK.PublicKey.GetBytes());
                AsymmetricKeyParameter pubKey   = PublicKeyFactory.CreateKey(pubInfo);

                string wrapAlg = DerObjectIdentifier.GetInstance(
                    Asn1Sequence.GetInstance(_keyEncAlg.Parameters)[0]).Id;

                IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    _keyEncAlg.ObjectID, wrapAlg);

                agreement.Init(privKey);

                BigInteger wKeyNum = agreement.CalculateAgreement(pubKey);
                // TODO Fix the way bytes are derived from the secret
                byte[]       wKeyBytes = wKeyNum.ToByteArrayUnsigned();
                KeyParameter wKey      = ParameterUtilities.CreateKeyParameter(wrapAlg, wKeyBytes);

                IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg);

                keyCipher.Init(false, wKey);

                AlgorithmIdentifier aid = _encAlg;
                string alg = aid.ObjectID.Id;

                byte[] encryptedKey = _encryptedKey.GetOctets();
                byte[] sKeyBytes    = keyCipher.Unwrap(encryptedKey, 0, encryptedKey.Length);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(alg, sKeyBytes);

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (Exception e)
            {
                throw new CmsException("originator key invalid.", e);
            }
        }
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            byte[] keyBytes = contentEncryptionKey.GetKey();

            AsymmetricKeyParameter 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));

                    AsymmetricCipherKeyPair 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));
                BigInteger 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))));
        }
Beispiel #6
0
        public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
        {
            //IL_002f: Expected O, but got Unknown
            //IL_00c8: Expected O, but got Unknown
            //IL_0169: Unknown result type (might be due to invalid IL or missing references)
            byte[] key = contentEncryptionKey.GetKey();
            AsymmetricKeyParameter    @public          = senderKeyPair.Public;
            ICipherParameters         cipherParameters = senderKeyPair.Private;
            OriginatorIdentifierOrKey originator;

            try
            {
                originator = new OriginatorIdentifierOrKey(CreateOriginatorPublicKey(@public));
            }
            catch (IOException val)
            {
                IOException val2 = val;
                throw new InvalidKeyException(string.Concat((object)"cannot extract originator public key: ", (object)val2));
            }
            Asn1OctetString ukm = null;

            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                try
                {
                    IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                    keyPairGenerator.Init(((ECPublicKeyParameters)@public).CreateKeyGenerationParameters(random));
                    AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair();
                    ukm = new DerOctetString(new MQVuserKeyingMaterial(CreateOriginatorPublicKey(asymmetricCipherKeyPair.Public), null));
                    cipherParameters = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters, (ECPrivateKeyParameters)asymmetricCipherKeyPair.Private, (ECPublicKeyParameters)asymmetricCipherKeyPair.Public);
                }
                catch (IOException val3)
                {
                    IOException val4 = val3;
                    throw new InvalidKeyException(string.Concat((object)"cannot extract MQV ephemeral public key: ", (object)val4));
                }
                catch (SecurityUtilityException ex)
                {
                    throw new InvalidKeyException(string.Concat((object)"cannot determine MQV ephemeral key pair parameters from public key: ", (object)ex));
                }
            }
            DerSequence         parameters             = new DerSequence(keyEncryptionOID, DerNull.Instance);
            AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(keyAgreementOID, parameters);
            Asn1EncodableVector asn1EncodableVector    = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientCerts).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    X509Certificate         x509Certificate = (X509Certificate)enumerator.get_Current();
                    TbsCertificateStructure instance;
                    try
                    {
                        instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(x509Certificate.GetTbsCertificate()));
                    }
                    catch (global::System.Exception)
                    {
                        throw new ArgumentException("can't extract TBS structure from certificate");
                    }
                    IssuerAndSerialNumber       issuerSerial      = new IssuerAndSerialNumber(instance.Issuer, instance.SerialNumber.Value);
                    KeyAgreeRecipientIdentifier id                = new KeyAgreeRecipientIdentifier(issuerSerial);
                    ICipherParameters           cipherParameters2 = x509Certificate.GetPublicKey();
                    if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
                    {
                        cipherParameters2 = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters2, (ECPublicKeyParameters)cipherParameters2);
                    }
                    IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(keyAgreementOID, keyEncryptionOID.Id);
                    basicAgreementWithKdf.Init(new ParametersWithRandom(cipherParameters, random));
                    BigInteger   s           = basicAgreementWithKdf.CalculateAgreement(cipherParameters2);
                    int          qLength     = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
                    byte[]       keyBytes    = X9IntegerConverter.IntegerToBytes(s, qLength);
                    KeyParameter parameters2 = ParameterUtilities.CreateKeyParameter(keyEncryptionOID, keyBytes);
                    IWrapper     wrapper     = Helper.CreateWrapper(keyEncryptionOID.Id);
                    wrapper.Init(forWrapping: true, new ParametersWithRandom(parameters2, random));
                    byte[]          str          = wrapper.Wrap(key, 0, key.Length);
                    Asn1OctetString encryptedKey = new DerOctetString(str);
                    asn1EncodableVector.Add(new RecipientEncryptedKey(id, encryptedKey));
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncryptionAlgorithm, new DerSequence(asn1EncodableVector))));
        }
Beispiel #7
0
    public RecipientInfo Generate(KeyParameter contentEncryptionKey, SecureRandom random)
    {
        byte[] key = contentEncryptionKey.GetKey();
        AsymmetricKeyParameter    @public          = senderKeyPair.Public;
        ICipherParameters         cipherParameters = senderKeyPair.Private;
        OriginatorIdentifierOrKey originator;

        try
        {
            originator = new OriginatorIdentifierOrKey(CreateOriginatorPublicKey(@public));
        }
        catch (IOException arg)
        {
            throw new InvalidKeyException("cannot extract originator public key: " + arg);
        }
        Asn1OctetString ukm = null;

        if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
        {
            try
            {
                IAsymmetricCipherKeyPairGenerator keyPairGenerator = GeneratorUtilities.GetKeyPairGenerator(keyAgreementOID);
                keyPairGenerator.Init(((ECPublicKeyParameters)@public).CreateKeyGenerationParameters(random));
                AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.GenerateKeyPair();
                ukm = new DerOctetString(new MQVuserKeyingMaterial(CreateOriginatorPublicKey(asymmetricCipherKeyPair.Public), null));
                cipherParameters = new MqvPrivateParameters((ECPrivateKeyParameters)cipherParameters, (ECPrivateKeyParameters)asymmetricCipherKeyPair.Private, (ECPublicKeyParameters)asymmetricCipherKeyPair.Public);
            }
            catch (IOException arg2)
            {
                throw new InvalidKeyException("cannot extract MQV ephemeral public key: " + arg2);
            }
            catch (SecurityUtilityException arg3)
            {
                throw new InvalidKeyException("cannot determine MQV ephemeral key pair parameters from public key: " + arg3);
            }
        }
        DerSequence         parameters             = new DerSequence(keyEncryptionOID, DerNull.Instance);
        AlgorithmIdentifier keyEncryptionAlgorithm = new AlgorithmIdentifier(keyAgreementOID, parameters);
        Asn1EncodableVector asn1EncodableVector    = new Asn1EncodableVector();

        foreach (X509Certificate recipientCert in recipientCerts)
        {
            TbsCertificateStructure instance;
            try
            {
                instance = TbsCertificateStructure.GetInstance(Asn1Object.FromByteArray(recipientCert.GetTbsCertificate()));
            }
            catch (Exception)
            {
                throw new ArgumentException("can't extract TBS structure from certificate");
            }
            IssuerAndSerialNumber       issuerSerial      = new IssuerAndSerialNumber(instance.Issuer, instance.SerialNumber.Value);
            KeyAgreeRecipientIdentifier id                = new KeyAgreeRecipientIdentifier(issuerSerial);
            ICipherParameters           cipherParameters2 = recipientCert.GetPublicKey();
            if (keyAgreementOID.Id.Equals(CmsEnvelopedGenerator.ECMqvSha1Kdf))
            {
                cipherParameters2 = new MqvPublicParameters((ECPublicKeyParameters)cipherParameters2, (ECPublicKeyParameters)cipherParameters2);
            }
            IBasicAgreement basicAgreementWithKdf = AgreementUtilities.GetBasicAgreementWithKdf(keyAgreementOID, keyEncryptionOID.Id);
            basicAgreementWithKdf.Init(new ParametersWithRandom(cipherParameters, random));
            BigInteger   s           = basicAgreementWithKdf.CalculateAgreement(cipherParameters2);
            int          qLength     = GeneratorUtilities.GetDefaultKeySize(keyEncryptionOID) / 8;
            byte[]       keyBytes    = X9IntegerConverter.IntegerToBytes(s, qLength);
            KeyParameter parameters2 = ParameterUtilities.CreateKeyParameter(keyEncryptionOID, keyBytes);
            IWrapper     wrapper     = Helper.CreateWrapper(keyEncryptionOID.Id);
            wrapper.Init(forWrapping: true, new ParametersWithRandom(parameters2, random));
            byte[]          str          = wrapper.Wrap(key, 0, key.Length);
            Asn1OctetString encryptedKey = new DerOctetString(str);
            asn1EncodableVector.Add(new RecipientEncryptedKey(id, encryptedKey));
        }
        return(new RecipientInfo(new KeyAgreeRecipientInfo(originator, ukm, keyEncryptionAlgorithm, new DerSequence(asn1EncodableVector))));
    }