Example #1
0
        public CmsReadable GetReadable(
            KeyParameter sKey,
            Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier algorithm,
            CmsProcessableByteArray readable)
        {
            IBufferedCipher cipher;

            try
            {
                cipher = CipherUtilities.GetCipher(algorithm.Algorithm);
                var asn1Enc    = algorithm.Parameters;
                var asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();
                ICipherParameters cipherParameters = sKey;

                if (asn1Params != null && !(asn1Params is Asn1Null))
                {
                    cipherParameters = ParameterUtilities.GetCipherParameters(
                        algorithm.Algorithm, cipherParameters, asn1Params);
                }
                else
                {
                    string alg = algorithm.Algorithm.Id;
                    if (alg.Equals(CmsEnvelopedGenerator.DesEde3Cbc) ||
                        alg.Equals(CmsEnvelopedGenerator.IdeaCbc) ||
                        alg.Equals(CmsEnvelopedGenerator.Cast5Cbc))
                    {
                        cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
                    }
                }

                cipher.Init(false, cipherParameters);
            }
            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("error decoding algorithm parameters.", e);
            }

            try
            {
                return(new CmsProcessableInputStream(
                           new CipherStream(readable.GetInputStream(), cipher, null)));
            }
            catch (IOException e)
            {
                throw new CmsException("error reading content.", e);
            }
        }
            public CmsReadable GetReadable(KeyParameter sKey)
            {
                try
                {
                    this.cipher = CipherUtilities.GetCipher(this.algorithm.ObjectID);

                    Asn1Encodable asn1Enc    = this.algorithm.Parameters;
                    Asn1Object    asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();

                    ICipherParameters cipherParameters = sKey;

                    if (asn1Params != null && !(asn1Params is Asn1Null))
                    {
                        cipherParameters = ParameterUtilities.GetCipherParameters(
                            this.algorithm.ObjectID, cipherParameters, asn1Params);
                    }
                    else
                    {
                        string alg = this.algorithm.ObjectID.Id;
                        if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) ||
                            alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) ||
                            alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc))
                        {
                            cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
                        }
                    }

                    cipher.Init(false, cipherParameters);
                }
                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("error decoding algorithm parameters.", e);
                }

                try
                {
                    return(new CmsProcessableInputStream(
                               new CipherStream(readable.GetInputStream(), cipher, null)));
                }
                catch (IOException e)
                {
                    throw new CmsException("error reading content.", e);
                }
            }
Example #3
0
    protected internal virtual AlgorithmIdentifier GetAlgorithmIdentifier(string encryptionOid, KeyParameter encKey, Asn1Encodable asn1Params, out ICipherParameters cipherParameters)
    {
        Asn1Object asn1Object;

        if (asn1Params != null)
        {
            asn1Object       = asn1Params.ToAsn1Object();
            cipherParameters = ParameterUtilities.GetCipherParameters(encryptionOid, encKey, asn1Object);
        }
        else
        {
            asn1Object       = DerNull.Instance;
            cipherParameters = encKey;
        }
        return(new AlgorithmIdentifier(new DerObjectIdentifier(encryptionOid), asn1Object));
    }
Example #4
0
            public CmsReadable GetReadable(KeyParameter sKey)
            {
                try
                {
                    this.cipher = CipherUtilities.GetCipher(this.algorithm.ObjectID);
                    Asn1Encodable     parameters       = this.algorithm.Parameters;
                    Asn1Object        asn1Object       = (parameters == null) ? null : parameters.ToAsn1Object();
                    ICipherParameters cipherParameters = sKey;
                    if (asn1Object != null && !(asn1Object is Asn1Null))
                    {
                        cipherParameters = ParameterUtilities.GetCipherParameters(this.algorithm.ObjectID, cipherParameters, asn1Object);
                    }
                    else
                    {
                        string id = this.algorithm.ObjectID.Id;
                        if (id.Equals(CmsEnvelopedGenerator.DesEde3Cbc) || id.Equals("1.3.6.1.4.1.188.7.1.1.2") || id.Equals("1.2.840.113533.7.66.10"))
                        {
                            cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
                        }
                    }
                    this.cipher.Init(false, cipherParameters);
                }
                catch (SecurityUtilityException e)
                {
                    throw new CmsException("couldn't create cipher.", e);
                }
                catch (InvalidKeyException e2)
                {
                    throw new CmsException("key invalid in message.", e2);
                }
                catch (IOException e3)
                {
                    throw new CmsException("error decoding algorithm parameters.", e3);
                }
                CmsReadable result;

                try
                {
                    result = new CmsProcessableInputStream(new CipherStream(this.readable.GetInputStream(), this.cipher, null));
                }
                catch (IOException e4)
                {
                    throw new CmsException("error reading content.", e4);
                }
                return(result);
            }
 public CmsReadable GetReadable(KeyParameter sKey)
 {
     //IL_00c5: Expected O, but got Unknown
     //IL_00f4: Expected O, but got Unknown
     try
     {
         cipher = CipherUtilities.GetCipher(algorithm.Algorithm);
         Asn1Object        asn1Object       = algorithm.Parameters?.ToAsn1Object();
         ICipherParameters cipherParameters = sKey;
         if (asn1Object != null && !(asn1Object is Asn1Null))
         {
             cipherParameters = ParameterUtilities.GetCipherParameters(algorithm.Algorithm, cipherParameters, asn1Object);
         }
         else
         {
             string id = algorithm.Algorithm.Id;
             if (id.Equals(CmsEnvelopedGenerator.DesEde3Cbc) || id.Equals("1.3.6.1.4.1.188.7.1.1.2") || id.Equals("1.2.840.113533.7.66.10"))
             {
                 cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
             }
         }
         cipher.Init(forEncryption: false, cipherParameters);
     }
     catch (SecurityUtilityException e)
     {
         throw new CmsException("couldn't create cipher.", e);
     }
     catch (InvalidKeyException e2)
     {
         throw new CmsException("key invalid in message.", e2);
     }
     catch (IOException val)
     {
         IOException e3 = val;
         throw new CmsException("error decoding algorithm parameters.", (global::System.Exception)(object) e3);
     }
     try
     {
         return(new CmsProcessableInputStream((Stream)(object)new CipherStream(readable.GetInputStream(), cipher, null)));
     }
     catch (IOException val2)
     {
         IOException e4 = val2;
         throw new CmsException("error reading content.", (global::System.Exception)(object) e4);
     }
 }
        internal CmsTypedStream GetContentFromSessionKey(
            KeyParameter sKey)
        {
            try
            {
                IBufferedCipher cipher = CipherUtilities.GetCipher(_encAlg.ObjectID);

                Asn1Encodable asn1Enc    = _encAlg.Parameters;
                Asn1Object    asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();

                ICipherParameters cipherParameters = sKey;

                if (asn1Params != null && !(asn1Params is Asn1Null))
                {
                    cipherParameters = ParameterUtilities.GetCipherParameters(
                        _encAlg.ObjectID, cipherParameters, asn1Params);
                }
                else
                {
                    string alg = _encAlg.ObjectID.Id;
                    if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) ||
                        alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) ||
                        alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc))
                    {
                        cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
                    }
                }

                cipher.Init(false, cipherParameters);

                return(new CmsTypedStream(new CipherStream(_data, cipher, null)));
            }
            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("error decoding algorithm parameters.", e);
            }
        }
Example #7
0
        // TODO Make private again and call from PerformTest
        public void doTestExceptions()
        {
            // TODO Put back in
//			SecretKeyFactory skF = null;
//
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			KeySpec ks = null;
//			SecretKey secKey = null;
//			byte[] bb = new byte[24];
//
//			try
//			{
//				skF.getKeySpec(null, null);
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				ks = (KeySpec)new DESedeKeySpec(bb);
//				skF.getKeySpec(null, ks.getClass());
//
//				Fail("failed exception test - no exception thrown");
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay;
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}
//			try
//			{
//				skF.getKeySpec(secKey, null);
//			}
//			catch (InvalidKeySpecException e)
//			{
//				// ignore okay
//			}
//			catch (Exception e)
//			{
//				Fail("failed exception test.", e);
//			}

            try
            {
                CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator("DESede");

                try
                {
                    kg.Init(new KeyGenerationParameters(new SecureRandom(), int.MinValue));

                    Fail("failed exception test - no exception thrown");
                }
//				catch (InvalidParameterException)
                catch (ArgumentException)
                {
                    // ignore okay
                }
                catch (Exception e)
                {
                    Fail("failed exception test.", e);
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				skF = SecretKeyFactory.getInstance("DESede");
//
//				try
//				{
//					skF.translateKey(null);
//
//					Fail("failed exception test - no exception thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore okay
//				}
//				catch (Exception e)
//				{
//					Fail("failed exception test.", e);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

//			try
//			{
//				byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134,
//						(byte)137, (byte)138, (byte)140, (byte)143 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/CBC/NoPadding");
//
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if this
//					// cipher is being
//					// initialized for decryption and requires algorithm parameters
//					// that cannot be determined from the given key
////					cipher.Init(false, cipherKey, (SecureRandom)null);
//					cipher.Init(false, new ParametersWithRandom(cipherKey, new SecureRandom()));
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
//				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118 };
                byte[] rawDESKey = { 128, 131, 133, 134, 137, 138 };

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");

//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
                try
                {
                    KeyParameter cipherKey = new DesParameters(rawDESKey);

                    // According specification engineInit(int opmode, Key key,
                    // SecureRandom random) throws InvalidKeyException if the given
                    // key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);

//					Fail("failed exception test - no InvalidKeyException thrown");
                    Fail("failed exception test - no ArgumentException thrown");
                }
//				catch (InvalidKeyException)
                catch (ArgumentException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

//			try
//			{
////				byte[] rawDESKey = { -128, -125, -123, -122, -119, -118, -117, -115, -114 };
//				byte[] rawDESKey = { 128, 131, 133, 134, 137, 138, 139, 141, 142 };
//
////				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
//				KeyParameter cipherKey = new DesParameters(rawDESKey);
//
//				IBufferedCipher cipher = CipherUtilities.GetCipher("DES/ECB/NoPadding");
//				try
//				{
//					// According specification engineInit(int opmode, Key key,
//					// SecureRandom random) throws InvalidKeyException if the given
//					// key is inappropriate for initializing this cipher
//					cipher.Init(true, cipherKey);
//
//					Fail("failed exception test - no InvalidKeyException thrown");
//				}
//				catch (InvalidKeyException)
//				{
//					// ignore
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}


            try
            {
                byte[] rawDESKey = { (byte)128, (byte)131, (byte)133, (byte)134,
                                     (byte)137, (byte)138, (byte)140, (byte)143 };

//				SecretKeySpec cipherKey = new SecretKeySpec(rawDESKey, "DES");
                KeyParameter cipherKey = new DesParameters(rawDESKey);

                IBufferedCipher ecipher = CipherUtilities.GetCipher("DES/ECB/PKCS5Padding");
                ecipher.Init(true, cipherKey);

                byte[] cipherText = new byte[0];
                try
                {
                    // According specification Method engineUpdate(byte[] input,
                    // int inputOffset, int inputLen, byte[] output, int
                    // outputOffset)
                    // throws ShortBufferException - if the given output buffer is
                    // too
                    // small to hold the result
//					ecipher.update(new byte[20], 0, 20, cipherText);
                    ecipher.ProcessBytes(new byte[20], 0, 20, cipherText, 0);

//					Fail("failed exception test - no ShortBufferException thrown");
                    Fail("failed exception test - no DataLengthException thrown");
                }
//				catch (ShortBufferException)
                catch (DataLengthException)
                {
                    // ignore
                }
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }

            // TODO Put back in
//			try
//			{
//				KeyGenerator keyGen = KeyGenerator.getInstance("DES");
//
//				keyGen.init((SecureRandom)null);
//
//				// According specification engineGenerateKey() doesn't throw any exceptions.
//
//				SecretKey key = keyGen.generateKey();
//				if (key == null)
//				{
//					Fail("key is null!");
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}
//
//			try
//			{
//				AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");
//
//				algParams.init(new IvParameterSpec(new byte[8]));
//
//				// According specification engineGetEncoded() returns
//				// the parameters in their primary encoding format. The primary
//				// encoding
//				// format for parameters is ASN.1, if an ASN.1 specification for
//				// this type
//				// of parameters exists.
//				byte[] iv = algParams.getEncoded();
//
//				if (iv.Length!= 10)
//				{
//					Fail("parameters encoding wrong length - "  + iv.Length);
//				}
//			}
//			catch (Exception e)
//			{
//				Fail("unexpected exception.", e);
//			}

            try
            {
                try
                {
//					AlgorithmParameters algParams = AlgorithmParameters.getInstance("DES");

                    byte[] encoding = new byte[10];
                    encoding[0] = 3;
                    encoding[1] = 8;

//					algParams.init(encoding, "ASN.1");
                    ParameterUtilities.GetCipherParameters(
                        "AES",
                        ParameterUtilities.CreateKeyParameter("AES", new byte[16]),
                        Asn1Object.FromByteArray(encoding));

//					Fail("failed exception test - no IOException thrown");
                    Fail("failed exception test - no Exception thrown");
                }
//				catch (IOException)
                catch (ArgumentException)
                {
                    // okay
                }

//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PublicKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(true, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for public key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
//
//				try
//				{
//					IBufferedCipher c = CipherUtilities.GetCipher("DES");
//
//					Key k = new PrivateKey()
//					{
//
//						public string getAlgorithm()
//						{
//							return "STUB";
//						}
//
//						public string getFormat()
//						{
//							return null;
//						}
//
//						public byte[] getEncoded()
//						{
//							return null;
//						}
//
//					};
//
//					c.Init(false, k);
//
//					Fail("failed exception test - no InvalidKeyException thrown for private key");
//				}
//				catch (InvalidKeyException e)
//				{
//					// okay
//				}
            }
            catch (Exception e)
            {
                Fail("unexpected exception.", e);
            }
        }
        internal CmsTypedStream GetContentFromSessionKey(
            KeyParameter sKey)
        {
            try
            {
                Stream content = data;

                if (encAlg != null)
                {
                    IBufferedCipher cipher = CipherUtilities.GetCipher(encAlg.ObjectID);

                    Asn1Encodable asn1Enc    = encAlg.Parameters;
                    Asn1Object    asn1Params = asn1Enc == null ? null : asn1Enc.ToAsn1Object();

                    ICipherParameters cipherParameters = sKey;

                    if (asn1Params != null && !(asn1Params is Asn1Null))
                    {
                        cipherParameters = ParameterUtilities.GetCipherParameters(
                            encAlg.ObjectID, cipherParameters, asn1Params);
                    }
                    else
                    {
                        string alg = encAlg.ObjectID.Id;
                        if (alg.Equals(CmsEnvelopedDataGenerator.DesEde3Cbc) ||
                            alg.Equals(CmsEnvelopedDataGenerator.IdeaCbc) ||
                            alg.Equals(CmsEnvelopedDataGenerator.Cast5Cbc))
                        {
                            cipherParameters = new ParametersWithIV(cipherParameters, new byte[8]);
                        }
                    }

                    cipher.Init(false, cipherParameters);

                    content = new CipherStream(content, cipher, null);
                }

                // If authenticated, need to wrap in MacStream to calculate MAC
                if (macAlg != null)
                {
                    content = this.macStream = CreateMacStream(macAlg, sKey, content);
                }

                if (authEncAlg != null)
                {
                    // TODO Create AEAD cipher instance to decrypt and calculate tag ( MAC)
                    throw new CmsException("AuthEnveloped data decryption not yet implemented");

//              RFC 5084 ASN.1 Module
//                -- Parameters for AigorithmIdentifier
//
//                CCMParameters ::= SEQUENCE {
//                  aes-nonce         OCTET STRING (SIZE(7..13)),
//                  aes-ICVlen        AES-CCM-ICVlen DEFAULT 12 }
//
//                AES-CCM-ICVlen ::= INTEGER (4 | 6 | 8 | 10 | 12 | 14 | 16)
//
//                GCMParameters ::= SEQUENCE {
//                  aes-nonce        OCTET STRING, -- recommended size is 12 octets
//                  aes-ICVlen       AES-GCM-ICVlen DEFAULT 12 }
//
//                AES-GCM-ICVlen ::= INTEGER (12 | 13 | 14 | 15 | 16)
                }

                return(new CmsTypedStream(content));
            }
            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("error decoding algorithm parameters.", e);
            }
        }
        /// <summary>
        /// Generate an enveloped object that contains a CMS Enveloped Data
        /// object using the passed in key generator.
        /// </summary>
        private CmsEnvelopedData Generate(
            CmsProcessable content,
            string encryptionOid,
            CipherKeyGenerator keyGen)
        {
            AlgorithmIdentifier encAlgId = null;
            KeyParameter        encKey   = null;
            Asn1OctetString     encContent;

            try
            {
                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);

                byte[] encKeyBytes = keyGen.GenerateKey();
                encKey = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);

                Asn1Encodable asn1Params = null;

                try
                {
                    if (encryptionOid.Equals(RC2Cbc))
                    {
                        // mix in a bit extra...
                        rand.SetSeed(DateTime.Now.Ticks);

                        byte[] iv = rand.GenerateSeed(8);

                        // TODO Is this detailed repeat of Java version really necessary?
                        int effKeyBits = encKeyBytes.Length * 8;
                        int parameterVersion;

                        if (effKeyBits < 256)
                        {
                            parameterVersion = rc2Table[effKeyBits];
                        }
                        else
                        {
                            parameterVersion = effKeyBits;
                        }

                        asn1Params = new RC2CbcParameter(parameterVersion, iv);
                    }
                    else
                    {
                        asn1Params = ParameterUtilities.GenerateParameters(encryptionOid, rand);
                    }
                }
                catch (SecurityUtilityException)
                {
                    // No problem... no parameters generated
                }


                Asn1Object        asn1Object;
                ICipherParameters cipherParameters;

                if (asn1Params != null)
                {
                    asn1Object       = asn1Params.ToAsn1Object();
                    cipherParameters = ParameterUtilities.GetCipherParameters(
                        encryptionOid, encKey, asn1Object);
                }
                else
                {
                    asn1Object       = DerNull.Instance;
                    cipherParameters = encKey;
                }


                encAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(encryptionOid),
                    asn1Object);


                cipher.Init(true, cipherParameters);

                MemoryStream bOut = new MemoryStream();
                CipherStream cOut = new CipherStream(bOut, null, cipher);

                content.Write(cOut);

                cOut.Close();

                encContent = new BerOctetString(bOut.ToArray());
            }
            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 (RecipientInf recipient in recipientInfs)
            {
                try
                {
                    recipientInfos.Add(recipient.ToRecipientInfo(encKey));
                }
                catch (IOException e)
                {
                    throw new CmsException("encoding error.", e);
                }
                catch (InvalidKeyException e)
                {
                    throw new CmsException("key inappropriate for algorithm.", e);
                }
                catch (GeneralSecurityException e)
                {
                    throw new CmsException("error making encrypted content.", e);
                }
            }

            EncryptedContentInfo eci = new EncryptedContentInfo(
                PkcsObjectIdentifiers.Data,
                encAlgId,
                encContent);

            Asn1.Cms.ContentInfo contentInfo = new Asn1.Cms.ContentInfo(
                PkcsObjectIdentifiers.EnvelopedData,
                new EnvelopedData(null, new DerSet(recipientInfos), eci, null));

            return(new CmsEnvelopedData(contentInfo));
        }
Example #10
0
        protected Stream Open(
            Stream outStream,
            string encryptionOid,
            KeyParameter encKey,
            Asn1Encodable asn1Params,
            Asn1EncodableVector recipientInfos)
        {
            Asn1Object        asn1Object;
            ICipherParameters cipherParameters;

            if (asn1Params != null)
            {
                asn1Object       = asn1Params.ToAsn1Object();
                cipherParameters = ParameterUtilities.GetCipherParameters(
                    encryptionOid, encKey, asn1Object);
            }
            else
            {
                asn1Object       = DerNull.Instance;
                cipherParameters = encKey;
            }


            try
            {
                AlgorithmIdentifier encAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(encryptionOid),
                    asn1Object);

                //
                // ContentInfo
                //
                BerSequenceGenerator cGen = new BerSequenceGenerator(outStream);

                cGen.AddObject(CmsObjectIdentifiers.EnvelopedData);

                //
                // Encrypted Data
                //
                BerSequenceGenerator envGen = new BerSequenceGenerator(
                    cGen.GetRawOutputStream(), 0, true);

                envGen.AddObject(this.Version);

                DerSet derSet = _berEncodeRecipientSet
                                        ?       new BerSet(recipientInfos)
                                        :       new DerSet(recipientInfos);

                byte[] derSetEncoding = derSet.GetEncoded();

                envGen.GetRawOutputStream().Write(derSetEncoding, 0, derSetEncoding.Length);

                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);

                cipher.Init(true, cipherParameters);

                BerSequenceGenerator eiGen = new BerSequenceGenerator(
                    envGen.GetRawOutputStream());

                eiGen.AddObject(PkcsObjectIdentifiers.Data);

                byte[] tmp = encAlgId.GetEncoded();
                eiGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);

                BerOctetStringGenerator octGen = new BerOctetStringGenerator(
                    eiGen.GetRawOutputStream(), 0, false);

                Stream octetOutputStream = _bufferSize != 0
                                        ?       octGen.GetOctetOutputStream(new byte[_bufferSize])
                                        :       octGen.GetOctetOutputStream();

                CipherStream cOut = new CipherStream(octetOutputStream, null, cipher);

                return(new CmsEnvelopedDataOutputStream(cOut, cGen, envGen, eiGen));
            }
            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);
            }
        }