GenerateKey() public method

public GenerateKey ( ) : byte[]
return byte[]
コード例 #1
0
ファイル: Encryptor.cs プロジェクト: Legend1991/SecureBox_WPF
        public static byte[] GenerateKey()
        {
            SecureRandom sr = new SecureRandom();

            KeyGenerationParameters kgp = new KeyGenerationParameters(sr, keySize);

            CipherKeyGenerator kg = new CipherKeyGenerator();
            kg.Init(kgp);

            return kg.GenerateKey();
        }
コード例 #2
0
ファイル: Serpent.cs プロジェクト: rzymek01/bsk-serpent
        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;
        }
コード例 #3
0
ファイル: CryptManager.cs プロジェクト: ReezeBL/MinecraftEmu
        public static void DecodePublicKey(byte[] data)
        {
            /*TcpClient Client = new TcpClient();
            Client.Connect(IPAddress.Parse("127.0.0.1"), 3128);
            BinaryWriter bwr = new BinaryWriter(Client.GetStream());
            bwr.Write((byte)1);
            bwr.Write(data, 0, 162);*/

            AsymmetricKeyParameter kp = PublicKeyFactory.CreateKey(data);
            Key = (RsaKeyParameters)kp;
            PublicKey = new byte[data.Length];
            data.CopyTo(PublicKey,0);

            //Console.WriteLine("Exponent: " + Key.Exponent + "\nModulus: " + Key.Modulus);

            CipherKeyGenerator keygen = new CipherKeyGenerator();
            keygen.Init(new KeyGenerationParameters(new SecureRandom(), 128));
            SecretKey = keygen.GenerateKey();
        }
コード例 #4
0
        private void HandleEncryptionRequest(EncryptionRequestPacket packet)
        {
            if(Authorized)
                return;

            if (AuthorizationStatus.HasFlag(AuthorizationStatus.EncryprionEnabled))
            {
                var generator = new CipherKeyGenerator();
                generator.Init(new KeyGenerationParameters(new SecureRandom(), 16 * 8));
                var sharedKey = generator.GenerateKey();

                var pkcs = new PKCS1Signer(packet.PublicKey);
                var signedSecret = pkcs.SignData(sharedKey);
                var signedVerify = pkcs.SignData(packet.VerificationToken);

                SendPacket(new EncryptionResponsePacket { SharedSecret = signedSecret, VerificationToken = signedVerify });

                Stream.InitializeEncryption(sharedKey);

                SendPacket(new AuthorizationPasswordPacket { PasswordHash = Password.Hash });
            }
            else
                throw new SCONException("Encryption was not enabled!");
        }
コード例 #5
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);
		}
コード例 #6
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);
		}
コード例 #7
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)
        {
            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
        /// <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
            {
                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);
        }
コード例 #9
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);

                cOut.Dispose();

                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);
        }
コード例 #10
0
        private void HandleEncryptionRequest(EncryptionRequestPacket packet)
        {
            var generator = new CipherKeyGenerator();
            generator.Init(new KeyGenerationParameters(new SecureRandom(), 16 * 8));
            var sharedKey = generator.GenerateKey();

            var pkcs = new PKCS1Signer(packet.PublicKey);
            var signedSecret = pkcs.SignData(sharedKey);
            var signedVerify = pkcs.SignData(packet.VerificationToken);

            SendPacketDirect(new EncryptionResponsePacket { SharedSecret = signedSecret, VerificationToken = signedVerify });

            Stream.InitializeEncryption(sharedKey);

            State |= JoinState.JoinedGame;
        }
コード例 #11
0
ファイル: Serpent.cs プロジェクト: rzymek01/bsk-serpent
        public static KeyParameter generateKey(int keySize)
        {
            // walidacja parametru keySize
            //@todo

            CipherKeyGenerator keyGen = new CipherKeyGenerator();
            keyGen.Init(new KeyGenerationParameters(new SecureRandom(), keySize));
            byte[] sessionKey = keyGen.GenerateKey();
            var param = generateKeyFromBytes(sessionKey);

            return param;
        }
コード例 #12
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);
        }
コード例 #13
0
 public static SecretKey GenerateAESPrivateKey()
 {
     CipherKeyGenerator var0 = new CipherKeyGenerator();
     var0.Init(new KeyGenerationParameters(new Org.BouncyCastle.Security.SecureRandom(), 128));
     return new SecretKeySpec(var0.GenerateKey(), "AES");
 }