示例#1
0
 public CmsAuthenticatedData Generate(CmsProcessable content, string encryptionOid)
 {
     try
     {
         CipherKeyGenerator keyGenerator = GeneratorUtilities.GetKeyGenerator(encryptionOid);
         keyGenerator.Init(new KeyGenerationParameters(rand, keyGenerator.DefaultStrength));
         return(Generate(content, encryptionOid, keyGenerator));
     }
     catch (SecurityUtilityException e)
     {
         throw new CmsException("can't find key generation algorithm.", e);
     }
 }
示例#2
0
        /**
         * generate an enveloped object that contains an CMS Enveloped Data object
         * @throws IOException
         */
        public Stream Open(
            Stream outStream,
            string encryptionOid)
        {
            try
            {
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                return(Open(outStream, encryptionOid, keyGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
        /// <summary>Generate an enveloped object that contains an CMS Enveloped Data object.</summary>
        public CmsEnvelopedData Generate(
            CmsProcessable content,
            string encryptionOid)
        {
            try
            {
                CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);

                return(Generate(content, encryptionOid, keyGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
        }
        public Stream BcEncryptStream(Stream inputStream)
        {
            CipherKeyGenerator gen = GeneratorUtilities.GetKeyGenerator("ChaCha20-Poly1305");
            var cipher             = CipherUtilities.GetCipher("ChaCha20-Poly1305");

            Key = gen.GenerateKey();
            SecureRandom random = new SecureRandom();

            Iv = new byte[12];
            random.NextBytes(Iv);
            cipher.Init(true, new ParametersWithIV(new KeyParameter(Key), Iv));
            var cs = new CipherStream(inputStream, cipher, null);

            return(cs);
        }
示例#5
0
        public CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, int keySize)
        {
            CmsEnvelopedData result;

            try
            {
                CipherKeyGenerator keyGenerator = GeneratorUtilities.GetKeyGenerator(encryptionOid);
                keyGenerator.Init(new KeyGenerationParameters(this.rand, keySize));
                result = this.Generate(content, encryptionOid, keyGenerator);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("can't find key generation algorithm.", e);
            }
            return(result);
        }
示例#6
0
        public static byte[] generateIV(bool zeros = false)
        {
            byte[] iv;
            if (!zeros)
            {
                CipherKeyGenerator keyGen = new CipherKeyGenerator();
                keyGen.Init(new KeyGenerationParameters(new SecureRandom(), BLOCK_SIZE << 3));
                iv = keyGen.GenerateKey();
            }
            else
            {
                iv = new byte[BLOCK_SIZE];
            }

            return(iv);
        }
示例#7
0
        // Performs AES encryption with Bouncy Castle and returns the encrypted data along with the secret key
        public static string[] Encrypt(string data)
        {
            var keyGenerator = new CipherKeyGenerator();

            keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 256));
            var secretKey = keyGenerator.GenerateKey();

            var dataBytes = Encoding.UTF8.GetBytes(data);
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()));

            cipher.Init(true, new KeyParameter(secretKey));
            var rv  = new byte[cipher.GetOutputSize(dataBytes.Length)];
            var tam = cipher.ProcessBytes(dataBytes, 0, dataBytes.Length, rv, 0);

            cipher.DoFinal(rv, tam);

            return(new[] { Hex.ToHexString(rv), Hex.ToHexString(secretKey) });
        }
示例#8
0
        private void doOidTest()
        {
            string[] oids =
            {
                CryptoProObjectIdentifiers.GostR28147Cbc.Id,
            };

            string[] names =
            {
                "GOST28147/CBC/PKCS7Padding"
            };

            try
            {
                byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
//				IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]);
                byte[] iv = new byte[8];

                for (int i = 0; i != oids.Length; i++)
                {
                    IBufferedCipher c1 = CipherUtilities.GetCipher(oids[i]);
                    IBufferedCipher c2 = CipherUtilities.GetCipher(names[i]);

//					KeyGenerator kg = KeyGenerator.getInstance(oids[i]);
//					SecretKey k = kg.generateKey();
                    CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]);
                    KeyParameter       k  = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey());

                    c1.Init(true, new ParametersWithIV(k, iv));
                    c2.Init(false, new ParametersWithIV(k, iv));

                    byte[] result = c2.DoFinal(c1.DoFinal(data));

                    if (!AreEqual(data, result))
                    {
                        Fail("failed OID test");
                    }
                }
            }
            catch (Exception ex)
            {
                Fail("failed exception " + ex.ToString(), ex);
            }
        }
示例#9
0
        public void SerpentTest()
        {
            CipherKeyGenerator cipherKeyGenerator = new CipherKeyGenerator();

            cipherKeyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 128));
            byte[] key     = cipherKeyGenerator.GenerateKey();
            string message = "Hello World!";

            // Encrypt the string to an in-memory buffer.

            byte[] encrptedDAta = SerpentAlgo.SerpentEncryption(message, key);

            // Decrypt the buffer back to a string.
            string plainText = SerpentAlgo.SerpentDecryption(encrptedDAta, key);

            // Display the decrypted string to the console.

            Console.WriteLine(plainText);
        }
        private void button9_Click(object sender, RoutedEventArgs e) //Generiraj 3DES ključ
        {
            CipherKeyGenerator generatorKljuča = new CipherKeyGenerator();

            generatorKljuča.Init(new KeyGenerationParameters(new SecureRandom(), 112));

            ključ3DES = generatorKljuča.GenerateKey();
            BigInteger bigInteger = new BigInteger(ključ3DES);

            Microsoft.Win32.SaveFileDialog shrani3DESKljuč = new Microsoft.Win32.SaveFileDialog();
            shrani3DESKljuč.Title  = "Shrani 3DES ključ";
            shrani3DESKljuč.Filter = "txt files(*.txt) | *.txt";

            var naŠestnajstZnakov = bigInteger.ToString(16).Substring(0, 16);

            if (shrani3DESKljuč.ShowDialog() == true)
            {
                File.WriteAllText(shrani3DESKljuč.FileName, naŠestnajstZnakov);
            }
        }
示例#11
0
        public static byte[] generateIV(bool zeros = false)
        {
            byte[] iv;
            if (!zeros)
            {
                CipherKeyGenerator keyGen = new CipherKeyGenerator();
                keyGen.Init(new KeyGenerationParameters(new SecureRandom(), BLOCK_SIZE << 3));
                iv = keyGen.GenerateKey();
            }
            else
            {
                iv = new byte[BLOCK_SIZE];
            }


            ////@todo delete this
            //System.Console.WriteLine("iv: {0}", BitConverter.ToString(iv));

            return(iv);
        }
示例#12
0
        public void doTestHMac(
            string hmacName,
            byte[]  output)
        {
            KeyParameter key = new KeyParameter(keyBytes); //, hmacName);

            IMac mac = MacUtilities.GetMac(hmacName);

            mac.Init(key);

            mac.Reset();

            mac.BlockUpdate(message, 0, message.Length);

//			byte[] outBytes = mac.DoFinal();
            byte[] outBytes = new byte[mac.GetMacSize()];
            mac.DoFinal(outBytes, 0);

            if (!AreEqual(outBytes, output))
            {
                Fail("Failed - expected "
                     + Hex.ToHexString(output) + " got "
                     + Hex.ToHexString(outBytes));
            }

            // no key generator for the old algorithms
            if (hmacName.StartsWith("Old"))
            {
                return;
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(hmacName);

            mac.Init(new KeyParameter(kGen.GenerateKey())); // hmacName

            mac.BlockUpdate(message, 0, message.Length);

//			outBytes = mac.DoFinal();
            outBytes = new byte[mac.GetMacSize()];
            mac.DoFinal(outBytes, 0);
        }
        private Stream Open(Stream outStream, string encryptionOid, CipherKeyGenerator keyGen)
        {
            byte[]              array        = keyGen.GenerateKey();
            KeyParameter        keyParameter = ParameterUtilities.CreateKeyParameter(encryptionOid, array);
            Asn1Encodable       asn1Params   = GenerateAsn1Parameters(encryptionOid, array);
            ICipherParameters   cipherParameters;
            AlgorithmIdentifier algorithmIdentifier = GetAlgorithmIdentifier(encryptionOid, keyParameter, asn1Params, out cipherParameters);
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientInfoGenerators).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    RecipientInfoGenerator recipientInfoGenerator = (RecipientInfoGenerator)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand));
                    }
                    catch (InvalidKeyException e)
                    {
                        throw new CmsException("key inappropriate for algorithm.", e);
                    }
                    catch (GeneralSecurityException e2)
                    {
                        throw new CmsException("error making encrypted content.", e2);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            return(Open(outStream, algorithmIdentifier, cipherParameters, asn1EncodableVector));
        }
        /// <summary>
        /// Generate an enveloped object that contains an CMS Enveloped Data
        /// object using the passed in key generator.
        /// </summary>
        private Stream Open(
            Stream outStream,
            string encryptionOid,
            CipherKeyGenerator keyGen)
        {
            byte[]       encKeyBytes = keyGen.GenerateKey();
            KeyParameter encKey      = ParameterUtilities.CreateKeyParameter(encryptionOid, encKeyBytes);

            Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);

            ICipherParameters   cipherParameters;
            AlgorithmIdentifier encAlgID = GetAlgorithmIdentifier(
                encryptionOid, encKey, asn1Params, out cipherParameters);

            Asn1EncodableVector recipientInfos = new Asn1EncodableVector();

            foreach (RecipientInf recipient in recipientInfs)
            {
                try
                {
                    recipientInfos.Add(recipient.ToRecipientInfo(encKey, rand));
                }
                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);
                }
            }

            return(Open(outStream, encAlgID, cipherParameters, recipientInfos));
        }
示例#15
0
        protected void oidTest(
            string[]        oids,
            string[]        names,
            int groupSize)
        {
            byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };

            for (int i = 0; i != oids.Length; i++)
            {
                IBufferedCipher    c1 = CipherUtilities.GetCipher(oids[i]);
                IBufferedCipher    c2 = CipherUtilities.GetCipher(names[i]);
                CipherKeyGenerator kg = GeneratorUtilities.GetKeyGenerator(oids[i]);

                KeyParameter k = ParameterUtilities.CreateKeyParameter(oids[i], kg.GenerateKey());

                ICipherParameters cp = k;
                if (names[i].IndexOf("/ECB/") < 0)
                {
                    cp = new ParametersWithIV(cp, new byte[16]);
                }

                c1.Init(true, cp);
                c2.Init(false, cp);

                byte[] result = c2.DoFinal(c1.DoFinal(data));

                if (!AreEqual(data, result))
                {
                    Fail("failed OID test");
                }

                if (k.GetKey().Length != (16 + ((i / groupSize) * 8)))
                {
                    Fail("failed key length test");
                }
            }
        }
示例#16
0
        static CmsTestUtil()
        {
            try
            {
                rand = new SecureRandom();

                aes192kg = GeneratorUtilities.GetKeyGenerator("AES");
                aes192kg.Init(new KeyGenerationParameters(rand, 192));

                desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
                desede128kg.Init(new KeyGenerationParameters(rand, 112));

                desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
                desede192kg.Init(new KeyGenerationParameters(rand, 168));

                rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc240kg.Init(new KeyGenerationParameters(rand, 40));

                rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc264kg.Init(new KeyGenerationParameters(rand, 64));

                rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
                rc2128kg.Init(new KeyGenerationParameters(rand, 128));

                aesKg = GeneratorUtilities.GetKeyGenerator("AES");

                seedKg = GeneratorUtilities.GetKeyGenerator("SEED");

                camelliaKg = GeneratorUtilities.GetKeyGenerator("Camellia");

                serialNumber = BigInteger.One;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
示例#17
0
		/**
		* generate an enveloped object that contains an CMS Enveloped Data
		* object using the given provider and the passed in key generator.
		* @throws java.io.IOException
		*/
		private Stream Open(
			Stream				outStr,
			string				macOid,
			CipherKeyGenerator	keyGen)
		{
			// FIXME Will this work for macs?
			byte[] encKeyBytes = keyGen.GenerateKey();
			KeyParameter encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);

			Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);

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

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

			// FIXME Only passing key at the moment
//			return Open(outStr, macAlgId, cipherParameters, recipientInfos);
			return Open(outStr, macAlgId, encKey, recipientInfos);
		}
示例#18
0
        private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen)
        {
            //IL_0039: Unknown result type (might be due to invalid IL or missing references)
            //IL_0040: Expected O, but got Unknown
            //IL_009f: Expected O, but got Unknown
            KeyParameter        keyParameter;
            AlgorithmIdentifier algorithmIdentifier;
            Asn1OctetString     content2;
            Asn1OctetString     mac2;

            try
            {
                byte[] array = keyGen.GenerateKey();
                keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array);
                Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, array);
                algorithmIdentifier = GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out var _);
                IMac mac = MacUtilities.GetMac(macOid);
                mac.Init(keyParameter);
                MemoryStream val  = new MemoryStream();
                Stream       val2 = (Stream)(object)new TeeOutputStream((Stream)(object)val, (Stream)(object)new MacOutputStream(mac));
                content.Write(val2);
                Platform.Dispose(val2);
                content2 = new BerOctetString(val.ToArray());
                byte[] str = MacUtilities.DoFinal(mac);
                mac2 = new DerOctetString(str);
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e2)
            {
                throw new CmsException("key invalid in message.", e2);
            }
            catch (IOException val3)
            {
                IOException e3 = val3;
                throw new CmsException("exception decoding algorithm parameters.", (global::System.Exception)(object) e3);
            }
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientInfoGenerators).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    RecipientInfoGenerator recipientInfoGenerator = (RecipientInfoGenerator)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand));
                    }
                    catch (InvalidKeyException e4)
                    {
                        throw new CmsException("key inappropriate for algorithm.", e4);
                    }
                    catch (GeneralSecurityException e5)
                    {
                        throw new CmsException("error making encrypted content.", e5);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2);
            ContentInfo contentInfo         = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null));

            return(new CmsAuthenticatedData(contentInfo));
        }
        private CmsAuthenticatedData Generate(CmsProcessable content, string macOid, CipherKeyGenerator keyGen)
        {
            KeyParameter        keyParameter;
            AlgorithmIdentifier algorithmIdentifier;
            Asn1OctetString     content2;
            Asn1OctetString     mac2;

            try
            {
                byte[] array = keyGen.GenerateKey();
                keyParameter = ParameterUtilities.CreateKeyParameter(macOid, array);
                Asn1Encodable     asn1Params = this.GenerateAsn1Parameters(macOid, array);
                ICipherParameters cipherParameters;
                algorithmIdentifier = this.GetAlgorithmIdentifier(macOid, keyParameter, asn1Params, out cipherParameters);
                IMac mac = MacUtilities.GetMac(macOid);
                mac.Init(keyParameter);
                MemoryStream memoryStream = new MemoryStream();
                Stream       stream       = new TeeOutputStream(memoryStream, new MacOutputStream(mac));
                content.Write(stream);
                stream.Close();
                memoryStream.Close();
                content2 = new BerOctetString(memoryStream.ToArray());
                byte[] str = MacUtilities.DoFinal(mac);
                mac2 = new DerOctetString(str);
            }
            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("exception decoding algorithm parameters.", e3);
            }
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(new Asn1Encodable[0]);

            foreach (RecipientInfoGenerator recipientInfoGenerator in this.recipientInfoGenerators)
            {
                try
                {
                    asn1EncodableVector.Add(new Asn1Encodable[]
                    {
                        recipientInfoGenerator.Generate(keyParameter, this.rand)
                    });
                }
                catch (InvalidKeyException e4)
                {
                    throw new CmsException("key inappropriate for algorithm.", e4);
                }
                catch (GeneralSecurityException e5)
                {
                    throw new CmsException("error making encrypted content.", e5);
                }
            }
            ContentInfo encapsulatedContent = new ContentInfo(CmsObjectIdentifiers.Data, content2);
            ContentInfo contentInfo         = new ContentInfo(CmsObjectIdentifiers.AuthenticatedData, new AuthenticatedData(null, new DerSet(asn1EncodableVector), algorithmIdentifier, null, encapsulatedContent, null, mac2, null));

            return(new CmsAuthenticatedData(contentInfo));
        }
示例#20
0
        private CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen)
        {
            //IL_0045: Unknown result type (might be due to invalid IL or missing references)
            //IL_004c: Expected O, but got Unknown
            //IL_0096: Expected O, but got Unknown
            AlgorithmIdentifier algorithmIdentifier = null;
            KeyParameter        keyParameter;
            Asn1OctetString     encryptedContent;

            try
            {
                byte[] array = keyGen.GenerateKey();
                keyParameter = ParameterUtilities.CreateKeyParameter(encryptionOid, array);
                Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, array);
                algorithmIdentifier = GetAlgorithmIdentifier(encryptionOid, keyParameter, asn1Params, out var cipherParameters);
                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);
                cipher.Init(forEncryption: true, new ParametersWithRandom(cipherParameters, rand));
                MemoryStream val          = new MemoryStream();
                CipherStream cipherStream = new CipherStream((Stream)(object)val, null, cipher);
                content.Write((Stream)(object)cipherStream);
                Platform.Dispose((Stream)(object)cipherStream);
                encryptedContent = new BerOctetString(val.ToArray());
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e2)
            {
                throw new CmsException("key invalid in message.", e2);
            }
            catch (IOException val2)
            {
                IOException e3 = val2;
                throw new CmsException("exception decoding algorithm parameters.", (global::System.Exception)(object) e3);
            }
            Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

            global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)recipientInfoGenerators).GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    RecipientInfoGenerator recipientInfoGenerator = (RecipientInfoGenerator)enumerator.get_Current();
                    try
                    {
                        asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand));
                    }
                    catch (InvalidKeyException e4)
                    {
                        throw new CmsException("key inappropriate for algorithm.", e4);
                    }
                    catch (GeneralSecurityException e5)
                    {
                        throw new CmsException("error making encrypted content.", e5);
                    }
                }
            }
            finally
            {
                global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            EncryptedContentInfo encryptedContentInfo = new EncryptedContentInfo(CmsObjectIdentifiers.Data, algorithmIdentifier, encryptedContent);
            Asn1Set unprotectedAttrs = null;

            if (unprotectedAttributeGenerator != null)
            {
                Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());
                unprotectedAttrs = new BerSet(attributes.ToAsn1EncodableVector());
            }
            ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(asn1EncodableVector), encryptedContentInfo, unprotectedAttrs));

            return(new CmsEnvelopedData(contentInfo));
        }
示例#21
0
        /**
         * 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);

                mOut.Close();
                bOut.Close();

                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));
        }
        static TspTestUtil()
        {
            rand = new SecureRandom();

            kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpg.Init(new RsaKeyGenerationParameters(
                         BigInteger.ValueOf(0x10001), rand, 1024, 25));

            desede128kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
            desede128kg.Init(new KeyGenerationParameters(rand, 112));

            desede192kg = GeneratorUtilities.GetKeyGenerator("DESEDE");
            desede192kg.Init(new KeyGenerationParameters(rand, 168));

            rc240kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc240kg.Init(new KeyGenerationParameters(rand, 40));

            rc264kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc264kg.Init(new KeyGenerationParameters(rand, 64));

            rc2128kg = GeneratorUtilities.GetKeyGenerator("RC2");
            rc2128kg.Init(new KeyGenerationParameters(rand, 128));

            serialNumber = BigInteger.One;

            AddEntries(NistObjectIdentifiers.DsaWithSha224, "SHA224", "DSA");
            AddEntries(NistObjectIdentifiers.DsaWithSha256, "SHA256", "DSA");
            AddEntries(NistObjectIdentifiers.DsaWithSha384, "SHA384", "DSA");
            AddEntries(NistObjectIdentifiers.DsaWithSha512, "SHA512", "DSA");
            AddEntries(OiwObjectIdentifiers.DsaWithSha1, "SHA1", "DSA");
            AddEntries(OiwObjectIdentifiers.MD4WithRsa, "MD4", "RSA");
            AddEntries(OiwObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
            AddEntries(OiwObjectIdentifiers.MD5WithRsa, "MD5", "RSA");
            AddEntries(OiwObjectIdentifiers.Sha1WithRsa, "SHA1", "RSA");
            AddEntries(PkcsObjectIdentifiers.MD2WithRsaEncryption, "MD2", "RSA");
            AddEntries(PkcsObjectIdentifiers.MD4WithRsaEncryption, "MD4", "RSA");
            AddEntries(PkcsObjectIdentifiers.MD5WithRsaEncryption, "MD5", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha1WithRsaEncryption, "SHA1", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha224WithRsaEncryption, "SHA224", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha256WithRsaEncryption, "SHA256", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha384WithRsaEncryption, "SHA384", "RSA");
            AddEntries(PkcsObjectIdentifiers.Sha512WithRsaEncryption, "SHA512", "RSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha1, "SHA1", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha224, "SHA224", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha256, "SHA256", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha384, "SHA384", "ECDSA");
            AddEntries(X9ObjectIdentifiers.ECDsaWithSha512, "SHA512", "ECDSA");
            AddEntries(X9ObjectIdentifiers.IdDsaWithSha1, "SHA1", "DSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_1, "SHA1", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_224, "SHA224", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_256, "SHA256", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_384, "SHA384", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_ECDSA_SHA_512, "SHA512", "ECDSA");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_1, "SHA1", "RSA");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_v1_5_SHA_256, "SHA256", "RSA");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_1, "SHA1", "RSAandMGF1");
            AddEntries(EacObjectIdentifiers.id_TA_RSA_PSS_SHA_256, "SHA256", "RSAandMGF1");

            encryptionAlgs.Add(X9ObjectIdentifiers.IdDsa.Id, "DSA");
            encryptionAlgs.Add(PkcsObjectIdentifiers.RsaEncryption.Id, "RSA");
            encryptionAlgs.Add(TeleTrusTObjectIdentifiers.TeleTrusTRsaSignatureAlgorithm.Id, "RSA");
            encryptionAlgs.Add(X509ObjectIdentifiers.IdEARsa.Id, "RSA");
            encryptionAlgs.Add(EncryptionRsaPss, "RSAandMGF1");
            encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x94.Id, "GOST3410");
            encryptionAlgs.Add(CryptoProObjectIdentifiers.GostR3410x2001.Id, "ECGOST3410");
            encryptionAlgs.Add("1.3.6.1.4.1.5849.1.6.2", "ECGOST3410");
            encryptionAlgs.Add("1.3.6.1.4.1.5849.1.1.5", "GOST3410");

            digestAlgs.Add(PkcsObjectIdentifiers.MD2.Id, "MD2");
            digestAlgs.Add(PkcsObjectIdentifiers.MD4.Id, "MD4");
            digestAlgs.Add(PkcsObjectIdentifiers.MD5.Id, "MD5");
            digestAlgs.Add(OiwObjectIdentifiers.IdSha1.Id, "SHA1");
            digestAlgs.Add(NistObjectIdentifiers.IdSha224.Id, "SHA224");
            digestAlgs.Add(NistObjectIdentifiers.IdSha256.Id, "SHA256");
            digestAlgs.Add(NistObjectIdentifiers.IdSha384.Id, "SHA384");
            digestAlgs.Add(NistObjectIdentifiers.IdSha512.Id, "SHA512");
            digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD128.Id, "RIPEMD128");
            digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD160.Id, "RIPEMD160");
            digestAlgs.Add(TeleTrusTObjectIdentifiers.RipeMD256.Id, "RIPEMD256");
            digestAlgs.Add(CryptoProObjectIdentifiers.GostR3411.Id, "GOST3411");
            digestAlgs.Add("1.3.6.1.4.1.5849.1.2.1", "GOST3411");

            digestAliases.Add("SHA1", new string[] { "SHA-1" });
            digestAliases.Add("SHA224", new string[] { "SHA-224" });
            digestAliases.Add("SHA256", new string[] { "SHA-256" });
            digestAliases.Add("SHA384", new string[] { "SHA-384" });
            digestAliases.Add("SHA512", new string[] { "SHA-512" });

            noParams.Add(EncryptionDsa);
            //noParams.Add(EncryptionECDsa);
            noParams.Add(EncryptionECDsaWithSha1);
            noParams.Add(EncryptionECDsaWithSha224);
            noParams.Add(EncryptionECDsaWithSha256);
            noParams.Add(EncryptionECDsaWithSha384);
            noParams.Add(EncryptionECDsaWithSha512);

            ecAlgorithms.Add(DigestSha1, EncryptionECDsaWithSha1);
            ecAlgorithms.Add(DigestSha224, EncryptionECDsaWithSha224);
            ecAlgorithms.Add(DigestSha256, EncryptionECDsaWithSha256);
            ecAlgorithms.Add(DigestSha384, EncryptionECDsaWithSha384);
            ecAlgorithms.Add(DigestSha512, EncryptionECDsaWithSha512);
        }
        /// <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));
        }
示例#24
0
        /// <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;
            Asn1OctetString     encContent;

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

                Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, encKeyBytes);

                ICipherParameters cipherParameters;
                encAlgId = GetAlgorithmIdentifier(
                    encryptionOid, encKey, asn1Params, out cipherParameters);

                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);
                cipher.Init(true, new ParametersWithRandom(cipherParameters, rand));

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

                content.Write(cOut);

                Platform.Dispose(cOut);

                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 (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);
                }
            }

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

            Asn1Set unprotectedAttrSet = null;

            if (unprotectedAttributeGenerator != null)
            {
                Asn1.Cms.AttributeTable attrTable = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());

                unprotectedAttrSet = new BerSet(attrTable.ToAsn1EncodableVector());
            }

            ContentInfo contentInfo = new ContentInfo(
                CmsObjectIdentifiers.EnvelopedData,
                new EnvelopedData(null, new DerSet(recipientInfos), eci, unprotectedAttrSet));

            return(new CmsEnvelopedData(contentInfo));
        }
示例#25
0
        private void doRunTest(
            string name,
            int ivLength)
        {
            string lCode = "ABCDEFGHIJKLMNOPQRSTUVWXY0123456789";

            string baseName = name;

            if (name.IndexOf('/') >= 0)
            {
                baseName = name.Substring(0, name.IndexOf('/'));
            }

            CipherKeyGenerator kGen = GeneratorUtilities.GetKeyGenerator(baseName);

            IBufferedCipher inCipher  = CipherUtilities.GetCipher(name);
            IBufferedCipher outCipher = CipherUtilities.GetCipher(name);
            KeyParameter    key       = ParameterUtilities.CreateKeyParameter(baseName, kGen.GenerateKey());
            MemoryStream    bIn       = new MemoryStream(Encoding.ASCII.GetBytes(lCode), false);
            MemoryStream    bOut      = new MemoryStream();

            // In the Java build, this IV would be implicitly created and then retrieved with getIV()
            ICipherParameters cipherParams = key;

            if (ivLength > 0)
            {
                cipherParams = new ParametersWithIV(cipherParams, new byte[ivLength]);
            }

            inCipher.Init(true, cipherParams);

            // TODO Should we provide GetIV() method on IBufferedCipher?
            //if (inCipher.getIV() != null)
            //{
            //	outCipher.Init(false, new ParametersWithIV(key, inCipher.getIV()));
            //}
            //else
            //{
            //	outCipher.Init(false, key);
            //}
            outCipher.Init(false, cipherParams);

            CipherStream cIn  = new CipherStream(bIn, inCipher, null);
            CipherStream cOut = new CipherStream(bOut, null, outCipher);

            int c;

            while ((c = cIn.ReadByte()) >= 0)
            {
                cOut.WriteByte((byte)c);
            }

            cIn.Close();

            cOut.Flush();
            cOut.Close();

            byte[] bs  = bOut.ToArray();
            string res = Encoding.ASCII.GetString(bs, 0, bs.Length);

            if (!res.Equals(lCode))
            {
                Fail("Failed - decrypted data doesn't match.");
            }
        }
示例#26
0
        /// <summary>
        /// Generate an enveloped object that contains an CMS Enveloped Data
        /// object using the passed in key generator.
        /// </summary>
        private Stream Open(
            Stream outStream,
            string encryptionOid,
            CipherKeyGenerator keyGen)
        {
            Asn1Encodable asn1Params = null;

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

            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
            }


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

            return(Open(outStream, encryptionOid, encKey, asn1Params, recipientInfos));
        }
示例#27
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);
            }
        }
示例#28
0
    private CmsEnvelopedData Generate(CmsProcessable content, string encryptionOid, CipherKeyGenerator keyGen)
    {
        AlgorithmIdentifier algorithmIdentifier = null;
        KeyParameter        keyParameter;
        Asn1OctetString     encryptedContent;

        try
        {
            byte[] array = keyGen.GenerateKey();
            keyParameter = ParameterUtilities.CreateKeyParameter(encryptionOid, array);
            Asn1Encodable asn1Params = GenerateAsn1Parameters(encryptionOid, array);
            algorithmIdentifier = GetAlgorithmIdentifier(encryptionOid, keyParameter, asn1Params, out ICipherParameters cipherParameters);
            IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);
            cipher.Init(forEncryption: true, new ParametersWithRandom(cipherParameters, rand));
            MemoryStream memoryStream = new MemoryStream();
            CipherStream cipherStream = new CipherStream(memoryStream, null, cipher);
            content.Write(cipherStream);
            Platform.Dispose(cipherStream);
            encryptedContent = new BerOctetString(memoryStream.ToArray());
        }
        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("exception decoding algorithm parameters.", e3);
        }
        Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector();

        foreach (RecipientInfoGenerator recipientInfoGenerator in recipientInfoGenerators)
        {
            try
            {
                asn1EncodableVector.Add(recipientInfoGenerator.Generate(keyParameter, rand));
            }
            catch (InvalidKeyException e4)
            {
                throw new CmsException("key inappropriate for algorithm.", e4);
            }
            catch (GeneralSecurityException e5)
            {
                throw new CmsException("error making encrypted content.", e5);
            }
        }
        EncryptedContentInfo encryptedContentInfo = new EncryptedContentInfo(CmsObjectIdentifiers.Data, algorithmIdentifier, encryptedContent);
        Asn1Set unprotectedAttrs = null;

        if (unprotectedAttributeGenerator != null)
        {
            Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unprotectedAttributeGenerator.GetAttributes(Platform.CreateHashtable());
            unprotectedAttrs = new BerSet(attributes.ToAsn1EncodableVector());
        }
        ContentInfo contentInfo = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, new EnvelopedData(null, new DerSet(asn1EncodableVector), encryptedContentInfo, unprotectedAttrs));

        return(new CmsEnvelopedData(contentInfo));
    }