コード例 #1
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) });
        }
コード例 #2
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);
        }
コード例 #3
0
        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);
            }
        }
コード例 #4
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);
        }
コード例 #5
0
ファイル: HMacTest.cs プロジェクト: 7763sea/init-param-ripple
        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);
        }
コード例 #6
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));
        }
コード例 #8
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);
		}
コード例 #9
0
ファイル: BaseBlockCipherTest.cs プロジェクト: 894880010/MP
        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");
                }
            }
        }
コード例 #10
0
ファイル: CMSTestUtil.cs プロジェクト: TangoCS/BouncyCastle
 public static KeyParameter MakeAes192Key()
 {
     return(ParameterUtilities.CreateKeyParameter("AES", aes192kg.GenerateKey()));
 }
コード例 #11
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));
        }
コード例 #12
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));
        }
コード例 #13
0
ファイル: TSPTestUtil.cs プロジェクト: ekr/hacrypto
 public static KeyParameter MakeRC264Key()
 {
     return(new RC2Parameters(rc264kg.GenerateKey()));
 }
コード例 #14
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   = 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));
        }
コード例 #15
0
ファイル: CMSTestUtil.cs プロジェクト: TangoCS/BouncyCastle
 public static KeyParameter MakeSeedKey()
 {
     return(ParameterUtilities.CreateKeyParameter("SEED", seedKg.GenerateKey()));
 }
コード例 #16
0
ファイル: TSPTestUtil.cs プロジェクト: ekr/hacrypto
 public static KeyParameter MakeDesede192Key()
 {
     return(new DesEdeParameters(desede192kg.GenerateKey()));
 }
コード例 #17
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));
        }
コード例 #18
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.");
            }
        }
コード例 #19
0
        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
ファイル: GOST28147Test.cs プロジェクト: ekr/hacrypto
        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);
            }
        }
コード例 #21
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));
    }
コード例 #22
0
ファイル: CMSTestUtil.cs プロジェクト: TangoCS/BouncyCastle
 public static KeyParameter MakeDesEde192Key()
 {
     return(ParameterUtilities.CreateKeyParameter("DESEDE", desede192kg.GenerateKey()));
 }
コード例 #23
0
ファイル: CMSTestUtil.cs プロジェクト: TangoCS/BouncyCastle
 public static KeyParameter MakeRC2128Key()
 {
     return(ParameterUtilities.CreateKeyParameter("RC2", rc2128kg.GenerateKey()));
 }
コード例 #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 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));
        }