GenerateKey() public method

public GenerateKey ( ) : void
return void
Exemplo n.º 1
0
    private static bool TestKeyGeneration()
    {
        try
        {
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {

                // Try creating the other sized keys
                aes.KeySize = 128;
                if (aes.Key.Size != 128)
                    return false;

                // Make sure consecutive reads don't change the key
                aes.GenerateKey();
                byte[] read1 = aes.Key.ExportKey(true);
                byte[] read2 = aes.Key.ExportKey(true);

                if (!CompareBytes(read1, read2))
                    return false;
            }

            return true;
        }
        catch
        {
            return false;
        }
    }
Exemplo n.º 2
0
        private void OnGenerate(object sender, EventArgs e)
        {
            // Create the AES provider.
            using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
            {
                // Generate the IV.
                aesProvider.GenerateIV();
                // Generate the key.
                aesProvider.GenerateKey();

                StringBuilder builder = new StringBuilder();

                foreach (byte b in aesProvider.IV)
                {
                    builder.AppendFormat("0x{0:X2}, ", b);
                }

                this.textBoxIv.Text = builder.ToString();

                builder.Clear();

                foreach(byte b in aesProvider.Key)
                {
                    builder.AppendFormat("0x{0:X2}, ", b);
                }

                this.textBoxKey.Text = builder.ToString();
            }
        }
Exemplo n.º 3
0
        public void Encrypt(string filename)
        {
            FileStream fsInput = new FileStream(filename, FileMode.Open, FileAccess.Read);
            FileStream fsOutput = new FileStream(filename + ".crypt", FileMode.Create, FileAccess.Write);
            AesCryptoServiceProvider Aes = new AesCryptoServiceProvider();

            Aes.KeySize = 128;
            Aes.GenerateIV();
            Aes.GenerateKey();

            byte[] output = _algorithm_asym.Encrypt(Aes.Key, false);
            fsOutput.Write(output, 0, 256);
            output = _algorithm_asym.Encrypt(Aes.IV, false);
            fsOutput.Write(output, 0, 256);

            ICryptoTransform encrypt = Aes.CreateEncryptor();
            CryptoStream cryptostream = new CryptoStream(fsOutput, encrypt, CryptoStreamMode.Write);

            byte[] bytearrayinput = new byte[fsInput.Length - 1];
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

            fsInput.Close();
            fsOutput.Close();
        }
Exemplo n.º 4
0
        bool SessionTest_CloseWithCreateKeyObjects_internal(string svcProvider)
        {
            bool res = true;

            CryptoKey key;

            using (Session sess = new Session(svcProvider, MechanismType.AES_CBC))
            {
                AesCryptoServiceProvider aes = new AesCryptoServiceProvider(sess);

                aes.GenerateKey();

                key = aes.Key;

                SymmetricTestHelper.Test_EncryptUpdate(aes);
            }

            try
            {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider(svcProvider))
                {
                    aes.Key = key;

                    SymmetricTestHelper.Test_EncryptUpdate(aes);
                }

                res = false;
            }
            catch (Exception)
            {
            }

            return res;
        }
Exemplo n.º 5
0
 /// <summary>
 /// Generates an encryption key.
 /// </summary>
 /// <returns>byte[] encryption key. Store it some place
 /// safe.</returns>
 static public byte[] GenerateEncryptionKey()
 {
     //Generate a Key.
     var aesProvider = new AesCryptoServiceProvider();
     aesProvider.GenerateKey();
     return aesProvider.Key;
 }
Exemplo n.º 6
0
        protected void Application_Start()
        {
            //HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.config")));
            GlobalConfig.Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            var container = new Container();
            SimpleInjectorInitializer.InitializeInjector(container);
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

            GlobalConfig.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            GlobalConfig.GadgetTypes = new System.Collections.Concurrent.ConcurrentDictionary<string, Type>();

            LoadGadgets();

            var aesCsp = new AesCryptoServiceProvider();
            aesCsp.GenerateKey();
            aesCsp.GenerateIV();
            GlobalConfig.Encryptor = new SimpleAES(aesCsp.Key, aesCsp.IV);
        }
Exemplo n.º 7
0
 public string GenerateDecryptionKey()
 {
     using (var decr = new AesCryptoServiceProvider())
     {
         decr.GenerateKey();
         return BinaryToHex(decr.Key);
     }
 }
Exemplo n.º 8
0
 public static byte[] CreateAesKey()
 {
     System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
     crypto.KeySize = 256;
     crypto.GenerateKey();
     byte[] key = crypto.Key;
     return(key);
 }
 public void AesTest()
 {
     var symmetricAlgorithm = new AesCryptoServiceProvider();
     symmetricAlgorithm.GenerateKey();
     var key = symmetricAlgorithm.Key;
     Console.WriteLine(symmetricAlgorithm.KeySize);
     Console.WriteLine(symmetricAlgorithm.BlockSize);
     Console.WriteLine(Convert.ToBase64String(key));
 }
Exemplo n.º 10
0
 public static byte[] generateKey()
 {
     System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
     crypto.KeySize   = 128;
     crypto.BlockSize = 128;
     crypto.GenerateKey();
     byte[] keyGenerated = crypto.Key;
     return(keyGenerated);
 }
Exemplo n.º 11
0
 public static AesCryptoServiceProvider generateAESKey()
 {
     AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
     aes.KeySize = 256;
     aes.GenerateKey();
     aes.GenerateIV();
     
     return aes;
 }
Exemplo n.º 12
0
		// Create a serialized object of type Key.
		// The key data is created with .NET: AesCryptoServiceProvider.GenerateKey.
		public static string createSerializedKey()
		{
			using (var aes = new AesCryptoServiceProvider())
			{

				aes.GenerateKey();
				/* osu change: uncomment
				Log.I("AESKeySize: {0}".format(aes.KeySize));
				*/
					
				return makeKey(aes).serialize();
			}
		}
Exemplo n.º 13
0
        /// <summary>
        /// Encrypt data with AES algorithm
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        public static byte[] AesEncrypt(byte[] data, out byte[] key, out byte[] iv)
        {
            if (data == null)
                throw new ArgumentNullException("No data to encrypt.");

            using (AesCryptoServiceProvider provider = new AesCryptoServiceProvider())
            {
                provider.GenerateKey();
                provider.GenerateIV();
                key = provider.Key;
                iv = provider.IV;
                return provider.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
            }
        }
Exemplo n.º 14
0
        public TestSymmetricKeyProvider()
        {
            byte[] key;
            byte[] iv;

            using (var provider = new AesCryptoServiceProvider())
            {
                provider.GenerateIV();
                provider.GenerateKey();

                key = provider.Key;
                iv = provider.IV;

                provider.Clear();
            }

            _key = new TestSymmetricKey(key, iv);
        }
        static void Main()
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.GenerateKey();
            aes.GenerateIV();

            //Tworzenie CryptoTransform
            ICryptoTransform En = aes.CreateEncryptor();
            ICryptoTransform De = aes.CreateDecryptor();

            //Tworzenie potrzebnych zmiennych
            byte[] before = Encoding.UTF8.GetBytes("AES");
            byte[] after;
            byte[] end = new byte[1024];
            string result;

            //szyfrowanie
            using (MemoryStream mem = new MemoryStream())
            {
                using (CryptoStream crypt = new CryptoStream(mem, En, CryptoStreamMode.Write))
                {
                    crypt.Write(before, 0, before.Length);
                }
                after = mem.ToArray();
            }

            //deszyfracja
            using (MemoryStream mem = new MemoryStream(after))
            {
                int i;
                using (CryptoStream crypt = new CryptoStream(mem, De, CryptoStreamMode.Read))
                {
                    i = crypt.Read(end, 0, end.Length);
                }
                result = Encoding.UTF8.GetString(end, 0, i);
            }

            //wypisanie na ekran informacji.
            Console.WriteLine("Wiadomość: {0}", Encoding.UTF8.GetString(before));
            Console.WriteLine("Zaszyfrowana wiadomość: {0}", Encoding.UTF8.GetString(after));
            Console.WriteLine("Odszyfrowana wiadomość: {0}", result);
            Console.ReadKey();
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Generate a random AES pass key and securely send it to the server
        ///     <returns>True if successfully authenticated</returns>
        /// </summary>
        public static bool HandShake()
        {
            try
            {
                var keyPath = string.Format("{0}tmp\\public.cer", AppDomain.CurrentDomain.BaseDirectory);
                Communication.DownloadFile("/management/other/ssl/srvpublic.crt", keyPath);

                var aes = new AesCryptoServiceProvider();
                aes.GenerateKey();
                Passkey = aes.Key;
                var token = GetSecurityToken("token.dat");

                var certificate = new X509Certificate2(keyPath);

                if (!Data.RSA.IsFromCA(Data.RSA.GetCACertificate(), certificate))
                    throw new Exception("Certificate is not from FOG CA");

                Log.Entry(LogName, "Cert OK");

                var enKey = Data.Transform.ByteArrayToHexString(Data.RSA.Encrypt(certificate, Passkey));
                var enToken = Data.Transform.ByteArrayToHexString(Data.RSA.Encrypt(certificate, token));

                var response = Communication.Post("/management/index.php?sub=authorize", string.Format("sym_key={0}&token={1}&mac={2}", enKey, enToken, Configuration.MACAddresses()));

                if (!response.Error)
                {
                    Log.Entry(LogName, "Authenticated");
                    SetSecurityToken("token.dat", Data.Transform.HexStringToByteArray(response.GetField("#token")));
                    return true;
                }

                if (response.ReturnCode.Equals("#!ih"))
                    Communication.Contact(string.Format("/service/register.php?hostname={0}", Dns.GetHostName()), true);

            }
            catch (Exception ex)
            {
                Log.Error(LogName, "Could not authenticate");
                Log.Error(LogName, ex);
            }

            return false;
        }
Exemplo n.º 17
0
        public string generateKey()
        {
            string Key;

            try
            {
                System.Security.Cryptography.AesCryptoServiceProvider crypto = new System.Security.Cryptography.AesCryptoServiceProvider();
                crypto.KeySize   = 128;
                crypto.BlockSize = 128;
                crypto.GenerateKey();
                byte[] keyGenerated = crypto.Key;
                Key = Convert.ToBase64String(keyGenerated);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(Key);
        }
        public void Encrypt_Decrypt_RoundTrips()
        {
            // Arrange
            var aes = new AesCryptoServiceProvider();
            aes.GenerateKey();

            var serviceCollection = new ServiceCollection();
            var mockInternalEncryptor = new Mock<IInternalCertificateXmlEncryptor>();
            mockInternalEncryptor.Setup(o => o.PerformEncryption(It.IsAny<EncryptedXml>(), It.IsAny<XmlElement>()))
                .Returns<EncryptedXml, XmlElement>((encryptedXml, element) =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", aes); // use symmetric encryption
                    return encryptedXml.Encrypt(element, "theKey");
                });
            serviceCollection.AddInstance<IInternalCertificateXmlEncryptor>(mockInternalEncryptor.Object);

            var mockInternalDecryptor = new Mock<IInternalEncryptedXmlDecryptor>();
            mockInternalDecryptor.Setup(o => o.PerformPreDecryptionSetup(It.IsAny<EncryptedXml>()))
                .Callback<EncryptedXml>(encryptedXml =>
                {
                    encryptedXml.AddKeyNameMapping("theKey", aes); // use symmetric encryption
                });
            serviceCollection.AddInstance<IInternalEncryptedXmlDecryptor>(mockInternalDecryptor.Object);

            var services = serviceCollection.BuildServiceProvider();
            var encryptor = new CertificateXmlEncryptor(services);
            var decryptor = new EncryptedXmlDecryptor(services);

            var originalXml = XElement.Parse(@"<mySecret value='265ee4ea-ade2-43b1-b706-09b259e58b6b' />");

            // Act & assert - run through encryptor and make sure we get back <EncryptedData> element
            var encryptedXmlInfo = encryptor.Encrypt(originalXml);
            Assert.Equal(typeof(EncryptedXmlDecryptor), encryptedXmlInfo.DecryptorType);
            Assert.Equal(XName.Get("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"), encryptedXmlInfo.EncryptedElement.Name);
            Assert.Equal("http://www.w3.org/2001/04/xmlenc#Element", (string)encryptedXmlInfo.EncryptedElement.Attribute("Type"));
            Assert.DoesNotContain("265ee4ea-ade2-43b1-b706-09b259e58b6b", encryptedXmlInfo.EncryptedElement.ToString(), StringComparison.OrdinalIgnoreCase);

            // Act & assert - run through decryptor and make sure we get back the original value
            var roundTrippedElement = decryptor.Decrypt(encryptedXmlInfo.EncryptedElement);
            XmlAssert.Equal(originalXml, roundTrippedElement);
        }
Exemplo n.º 19
0
        public static byte[] Encrypt(string publicKey, byte[] data)
        {
            using (var aes = new AesCryptoServiceProvider())
            {
                aes.GenerateKey();
                aes.GenerateIV();

                using (var encryptor = aes.CreateEncryptor())
                    using (var ms = new MemoryStream())
                    {
                        ms.Write(Rsa.Encrypt(publicKey, aes.IV), 0, 128);
                        ms.Write(Rsa.Encrypt(publicKey, aes.Key), 0, 128);

                        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                        {
                            cs.Write(data, 0, data.Length);
                        }
                        return(ms.ToArray());
                    }
            }
        }
Exemplo n.º 20
0
        public static byte[] Encrypt(string publicKey, byte[] data)
        {
            using (var aes = new AesCryptoServiceProvider())
            {
                aes.GenerateKey();
                aes.GenerateIV();

                using (var encryptor = aes.CreateEncryptor())
                using (var ms = new MemoryStream())
                {
                    ms.Write(Rsa.Encrypt(publicKey, aes.IV), 0, 128);
                    ms.Write(Rsa.Encrypt(publicKey, aes.Key), 0, 128);

                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                    {
                        cs.Write(data, 0, data.Length);
                    }
                    return ms.ToArray();
                }
            }
        }
        public TestSymmetricKeyProvider(params string[] ids)
        {
            _keys = new Dictionary<string, TestSymmetricKey>();

            foreach (var id in ids.Concat(new[] {"default"}).Distinct())
            {
                byte[] key;
                byte[] iv;

                using (var provider = new AesCryptoServiceProvider())
                {
                    provider.GenerateIV();
                    provider.GenerateKey();

                    key = provider.Key;
                    iv = provider.IV;

                    provider.Clear();
                }

                _keys.Add(id, new TestSymmetricKey(key, iv));
            }
        }
Exemplo n.º 22
0
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[16000];

        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
           // Console.ReadLine();
        string answer = null;
        byte[] aesKey = null;
        answer = Console.ReadLine();
        if (answer == "gen")
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
            string rsaKey = rsa.ToXmlString(true);
            File.WriteAllText("c:\\private.txt", rsaKey);
            Console.Write("Ключи RSA были успешно сгенерированы и сохранены.\n\n");
        }
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
        answer = Console.ReadLine();
        if (answer == "enc")
        {
            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Ожидание соединения...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;
                    Console.Write("Нажмите Enter, чтобы выбрать файл для отправки");
                    Console.Read();
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.AddExtension = true;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                        {
                            myAes.KeySize = 256;
                            myAes.GenerateKey();
                           // myAes.Padding = PaddingMode.None;
                            aesKey = myAes.Key;
                            Console.WriteLine(dlg.FileName);
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                            rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
                            byte[] df = rsa.Encrypt(myAes.Key, false);
                            byte[] mes = Encoding.ASCII.GetBytes("{Key}");

                            byte[] newArray = new byte[df.Length + mes.Length];
                            Array.Copy(mes, 0, newArray, 0, mes.Length);
                            Array.Copy(df, 0, newArray, mes.Length, df.Length);
                            handler.Send(newArray);
                        }
                    }
                    Thread.Sleep(1000);
                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);

                        data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("Ключ") > -1)
                        {
                            Console.Write("\nКлюч был успешно отправлен!\n");
                            byte[] encMes = EncryptFile(dlg.FileName, aesKey);
                            handler.Send(encMes);
                            Console.Write("\nФайл был успешно зашифрован и отправлен!\n");
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            break;
                        }
                    }
                    //Thread.Sleep(1000);

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }
        Console.WriteLine("\nНажмите Enter для продолжения\n");
        Console.Read();
    }
Exemplo n.º 23
0
        public void TestEncrypteDatadHeader()
        {
            EncryptedDataHeader encryptedHeader = new EncryptedDataHeader(FILE_NAME, USER_ID_SRCE);

            encryptedHeader.Application = APP_NOTEPAD;
            encryptedHeader.EncryptionAlgorithm = ALGO_AES;
            encryptedHeader.MIME = MIME_TEXT;

            AesCryptoServiceProvider aesServiceProvider = new AesCryptoServiceProvider();
            aesServiceProvider.KeySize = 256;
            aesServiceProvider.GenerateKey();
            aesServiceProvider.GenerateIV();

            byte[] key = aesServiceProvider.Key;
            byte[] iv = aesServiceProvider.IV;

            byte[] aesKeyAndIV = new byte[key.Length + iv.Length];
            Buffer.BlockCopy(key, 0, aesKeyAndIV, 0, key.Length);
            Buffer.BlockCopy(iv, 0, aesKeyAndIV, key.Length, iv.Length);

            // Encrypt the AES key with the public key of the OlivierCodepro certificate
            RSACryptoServiceProvider rsaProviderOlivierCodepro = new RSACryptoServiceProvider();
            DigestData rsaDigestEncrypt = new RSAOAEPEncryptor(rsaProviderOlivierCodepro);
            ((IDigestEncryptor)rsaDigestEncrypt).Encrypt(aesKeyAndIV);

            EncryptedKey encryptedAesKeyForOlivierCodepro = new EncryptedKey(USER_ID_DEST1, rsaDigestEncrypt);
            encryptedHeader.EncryptedKeys = new EncryptedKey[] { encryptedAesKeyForOlivierCodepro };

            // Sign the test BEFORE it is encrypted using OlivierRouit private key
            byte[] byteText = ASCIIEncoding.ASCII.GetBytes(TEXT_TO_SIGN);

            RSACryptoServiceProvider rsaProviderOlivierRouit = new RSACryptoServiceProvider();
            DigestData rsaDigestSigned = new RSASHA1Signature(rsaProviderOlivierRouit);

            ((IDigestSignature)rsaDigestSigned).Sign(byteText);

            encryptedHeader.Signature = rsaDigestSigned;

            string jsonSerialized = JsonConvert.SerializeObject(encryptedHeader);

            EncryptedDataHeader encryptedHeaderDeserialized = JsonConvert.DeserializeObject<EncryptedDataHeader>(jsonSerialized);

            // Process the Signature DigestData
            IDigestSignature signDigest = RSADigestFactory.CreateDigestData(encryptedHeaderDeserialized.Signature, rsaProviderOlivierRouit) as IDigestSignature;
            bool verified = signDigest.Verify(byteText);
            Assert.IsTrue(verified);

            // Process the encrypted DigestData
            IDigestEncryptor encryptDigest = RSADigestFactory.CreateDigestData(encryptedHeaderDeserialized.EncryptedKeys.Where(k => k.UserID == USER_ID_DEST1).First().Encrypted, rsaProviderOlivierCodepro) as IDigestEncryptor;
            byte[] decryptedKeyAndIV = encryptDigest.Decrypt();
            bool equals = aesKeyAndIV.HasSameContent(decryptedKeyAndIV);
            Assert.IsTrue(equals);
        }
Exemplo n.º 24
0
        public ActionResult GenerateKey()
        {
            var crypto = new AesCryptoServiceProvider();
            crypto.GenerateKey();

            var key = Convert.ToBase64String(crypto.Key);
            var salt = Current.GenerateSalt();
            var hmac = Convert.ToBase64String(Current.Random(64));

            var ret =
                Newtonsoft.Json.JsonConvert.SerializeObject(
                    new KeyStore.Key
                        {
                            Version = 255,
                            Encryption = key,
                            Salt = salt,
                            HMAC = hmac
                        });

            return TextPlain(ret);
        }
Exemplo n.º 25
0
        public string DecryptFile(byte[] data)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.GenerateIV();
            byte[] iv = aes.IV;
            aes.GenerateKey();
            byte[] key = aes.Key;
            ICryptoTransform cryptoTransform = aes.CreateEncryptor();
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write);
            StreamWriter streamWriter = new StreamWriter(cryptoStream);
            memoryStream = new MemoryStream(data);
            cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
            StreamReader streamReader = new StreamReader(cryptoStream);
            string decryptText = streamReader.ReadToEnd();
            streamWriter.Dispose();
            cryptoStream.Dispose();
            memoryStream.Dispose();

            return decryptText;
        }
Exemplo n.º 26
0
        public byte[] EncryptFile(string text)
        {
            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
            aes.GenerateIV();
            byte[] iv = aes.IV;
            aes.GenerateKey();
            byte[] key = aes.Key;
            ICryptoTransform cryptoTransform = aes.CreateEncryptor();
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write);
            StreamWriter streamWriter = new StreamWriter(cryptoStream);
            streamWriter.Write(text);
            byte[] enryptText = memoryStream.ToArray();
            streamWriter.Dispose();
            cryptoStream.Dispose();
            memoryStream.Dispose();

            return enryptText;
        }
Exemplo n.º 27
0
        /// <summary>
        ///     Generate a random AES pass key and securely send it to the server
        /// </summary>
        /// <returns>True if successfully authenticated</returns>
        public static bool HandShake()
        {
            try
            {
                Log.Entry(LogName, "Waiting for authentication timeout to pass");
                CanAuth.WaitOne();
                EventTimer.Start();

                // Obtain a public key from the server
                var keyPath = Path.Combine(Settings.Location, "tmp", "public.cer");
                Communication.DownloadFile("/management/other/ssl/srvpublic.crt", keyPath);
                Log.Debug(LogName, "KeyPath = " + keyPath);
                var certificate = new X509Certificate2(keyPath);

                // Ensure the public key came from the pinned server
                if (!Data.RSA.IsFromCA(Data.RSA.ServerCertificate(), certificate))
                    throw new Exception("Certificate is not from FOG CA");
                Log.Entry(LogName, "Cert OK");

                // Generate a random AES key
                var aes = new AesCryptoServiceProvider();
                aes.GenerateKey();
                Passkey = aes.Key;

                // Get the security token from the last handshake
                var tokenPath = Path.Combine(Settings.Location, "token.dat");

                try
                {
                    if (!File.Exists(tokenPath) && File.Exists("token.dat"))
                    {
                        File.Copy("token.dat", tokenPath);
                    }
                }
                catch (Exception)
                {
                }

                var token = GetSecurityToken(tokenPath);
                // Encrypt the security token and AES key using the public key
                var enKey = Transform.ByteArrayToHexString(RSA.Encrypt(certificate, Passkey));
                var enToken = Transform.ByteArrayToHexString(RSA.Encrypt(certificate, token));
                // Send the encrypted data to the server and get the response
                var response = Communication.Post("/management/index.php?sub=requestClientInfo&authorize&newService",
                    $"sym_key={enKey}&token={enToken}&mac={Configuration.MACAddresses()}");

                // If the server accepted the token and AES key, save the new token
                if (!response.Error && response.Encrypted)
                {
                    Log.Entry(LogName, "Authenticated");
                    SetSecurityToken(tokenPath, Transform.HexStringToByteArray(response.GetField("token")));
                    return true;
                }

                // If the server does not recognize the host, register it
                if (response.ReturnCode.Equals("ih"))
                    Communication.Contact($"/service/register.php?hostname={Dns.GetHostName()}", true);
            }
            catch (Exception ex)
            {
                Log.Error(LogName, "Could not authenticate");
                Log.Error(LogName, ex);
            }

            return false;
        }
Exemplo n.º 28
0
        public void TestEncryptDecryptKey()
        {
            AesCryptoServiceProvider aesServiceProvider = new AesCryptoServiceProvider();
            aesServiceProvider.KeySize = 256;
            aesServiceProvider.GenerateKey();
            aesServiceProvider.GenerateIV();

            byte[] key = aesServiceProvider.Key;
            byte[] iv = aesServiceProvider.IV;

            byte[] aesKeyAndIV = new byte[key.Length + iv.Length];
            Buffer.BlockCopy(key, 0, aesKeyAndIV, 0, key.Length);
            Buffer.BlockCopy(iv, 0, aesKeyAndIV, key.Length, iv.Length);

            RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
            DigestData rsaDigestEncrypt = new RSAOAEPEncryptor(rsaProvider);
            ((IDigestEncryptor)rsaDigestEncrypt).Encrypt(aesKeyAndIV);

            string jsonSerialized = JsonConvert.SerializeObject(rsaDigestEncrypt);

            DigestData rsaJsonDigest = (DigestData)JsonConvert.DeserializeObject(jsonSerialized, typeof(DigestData));

            IDigestEncryptor rsaDigestDecryp = RSADigestFactory.CreateDigestData(rsaJsonDigest, rsaProvider) as IDigestEncryptor;
            Assert.IsNotNull(rsaDigestDecryp);
            byte[] decryptedKeyAndIV = rsaDigestDecryp.Decrypt();
            bool equals = aesKeyAndIV.HasSameContent(decryptedKeyAndIV);
            Assert.IsTrue(equals);
        }
        /**
         * Common payload content encryption method which is called after sanity
         * checks, and after any content signing is performed.
         *
         * @throws Exception
         */
        private void doEncryption()
        {
            // Make the one-time symmetric key, and encrypt the payload content using it.
            String cipherData = null;
            byte[] key = null;
            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.KeySize = AESKEYSIZE;
                aes.GenerateKey();
                key = aes.Key;
                aes.IV = getInitialisationVector();
                cipherData = doAESEncryption(aes);
            }

            // Start constructing the XML Encryption "EncryptedData" element. The main
            // payload encryption is AES-256/CBC
            //
            StringBuilder sb = new StringBuilder("<xenc:EncryptedData xmlns:xenc=\"http://www.w3.org/2001/04/xmlenc#\">");
            sb.Append("<xenc:EncryptionMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#aes256-cbc\"/>");

            // And then the KeyInfo which is the symmetric key byte[] encrypted for each
            // reader certificate.
            //
            sb.Append("<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">");
            foreach (X509Certificate2 x in readerCerts)
            {
                sb.Append(doRSASymmetricKeyEncryption(x, key));
            }
            sb.Append("</ds:KeyInfo>");
            sb.Append(cipherData);
            sb.Append("</xenc:EncryptedData>");

            // Set the payloadBody to the EncryptedData, and the "encrypted" flag to "true".
            // Note that "base64" and "compressed" apply to the *cleartext*, and so are not
            // altered by this operation. The same goes for the mime type. Receiving systems
            // that decrypt the payload will need these other data set correctly in order to
            // convert the encrypted and possibly otherwise-processed content into something
            // they can use.
            //
            payloadBody = sb.ToString();
            encrypted = true;

            // Make sure we overwrite the key byte[] before we leave, and mark the
            // one-time secret key null.
            //
            for (int i = 0; i < key.Length; i++)
            {
                key[i] = 0;
            }
            key = null;
        }
Exemplo n.º 30
0
 /// <summary>
 /// A helper function to convert an unencrypted HotDocs package stream to an encrypted HotDocs package stream.
 /// </summary>
 /// <param name="ms">The unencrypted HotDocs package file/stream.</param>
 /// <param name="rsaParamsXml">RSA key serialized to XML.</param>
 /// <returns>If rsaParamsXml is null or empty, the input stream ms is simply returned. Otherwise, the input stream ms is being copied and encrypted to the returned output stream. The output stream will contain a 4 byte signature at the beginning identifying it as a HotDocs package followed by encrypted AES keys and the encrypted data.</returns>
 public static MemoryStream Encrypt(MemoryStream ms, string rsaParamsXml)
 {
     byte[] encryptedAesKey;
     byte[] decryptedAesKey;
     byte[] encryptedAesIV;
     byte[] decryptedAesIV;
     MemoryStream s;
     //
     if (string.IsNullOrEmpty(rsaParamsXml))
         return ms;
     s = new MemoryStream();
     using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
     {
         aes.GenerateKey(); decryptedAesKey = aes.Key;
         aes.GenerateIV(); decryptedAesIV = aes.IV;
         using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
         {
             rsa.FromXmlString(rsaParamsXml);
             encryptedAesKey = rsa.Encrypt(decryptedAesKey, false);
             encryptedAesIV = rsa.Encrypt(decryptedAesIV, false);
         }
         s.Write(HDSig, 0, 4);
         s.WriteByte(0); // Version number
         s.WriteByte((byte)encryptedAesKey.Length);
         s.Write(encryptedAesKey, 0, encryptedAesKey.Length);
         s.WriteByte((byte)encryptedAesIV.Length);
         s.Write(encryptedAesIV, 0, encryptedAesIV.Length);
         MemoryStream temps = new MemoryStream();
         using (CryptoStream cs = new CryptoStream(temps, aes.CreateEncryptor(), CryptoStreamMode.Write))
         {
             ms.Position = 0;
             CopyStream(cs, ms);
             cs.FlushFinalBlock();
             cs.Flush();
             temps.Position = 0;
             CopyStream(s, temps);
         }
     }
     /* --- Doesn't work. RSA Encrypt function can only encrypt up to 245 bytes!
      * See http://social.msdn.microsoft.com/forums/en-US/clr/thread/4e3ada0a-bcaf-4c67-bdef-a6b15f5bfdce/
     byte[] encryptedData;
     byte[] decryptedData;
     int len = (int)ms.Length;
     using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
     {
         rsa.FromXmlString(rsaParamsXml);
         decryptedData = new byte[len];
         ms.Position = 0;
         ms.Read(decryptedData, 0, len);
         encryptedData = rsa.Encrypt(decryptedData, false);
         s.Write(HDSig, 0, 4);
         s.Write(encryptedData, 0, encryptedData.Length);
     }
     */
     s.Position = 0;
     return s;
 }
Exemplo n.º 31
0
        public static bool DoAesTest()
        {
            CipherMode[] cipherModes = new CipherMode[] { CipherMode.ECB, CipherMode.CBC };
            PaddingMode[] paddingModes = new PaddingMode[] { PaddingMode.None, PaddingMode.PKCS7 }; //, PaddingMode.Zeros, PaddingMode.ANSIX923, PaddingMode.ISO10126 };

            try
            {
                using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
                using (AesCryptoServiceProvider baseline = new AesCryptoServiceProvider("Emulator_Crypto"))
                {
                    foreach (KeySizes keySize in aes.LegalKeySizes)
                    {
                        aes.KeySize = keySize.MinSize;
                        do
                        {
                            aes.GenerateKey();
                            aes.GenerateIV();
                            aes.FeedbackSize = 64;

                            baseline.KeySize = aes.KeySize;
                            baseline.Key = aes.Key;
                            baseline.IV = aes.IV;
                            baseline.FeedbackSize = aes.FeedbackSize;

                            foreach (CipherMode cipherMode in cipherModes)
                            {
                                foreach (PaddingMode paddingMode in paddingModes)
                                {
                                    aes.Mode = cipherMode;
                                    aes.Padding = paddingMode;

                                    baseline.Mode = cipherMode;
                                    baseline.Padding = paddingMode;

                                    if (!Test(aes, baseline))
                                    {
                                        return false;
                                    }
                                }
                            }

                            aes.KeySize = aes.KeySize + keySize.SkipSize;
                        } while (aes.KeySize != keySize.MaxSize && keySize.SkipSize != 0);
                    }
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
        private void NegotiateAuthentication(string streamPassword, bool client)
        {
            int oldReadTimeout = baseStream.ReadTimeout;

                baseStream.ReadTimeout = 5000;

                RSACryptoServiceProvider localKeys;
                RSACryptoServiceProvider remoteKey;

                // Generate and send public key
                {
                    localKeys = new RSACryptoServiceProvider();
                    byte[] publicBlob = localKeys.ExportCspBlob(false);
                    baseStream.Write(BitConverter.GetBytes(publicBlob.Length), 0, 4);
                    baseStream.Write(publicBlob, 0, publicBlob.Length);
                }

                // Receive remote public key
                try
                {
                    byte[] blobLen = new byte[4];
                    StreamHelper.ForceReadAll(baseStream, blobLen, 0, 4);

                    byte[] remoteBlob = new byte[BitConverter.ToInt32(blobLen, 0)];
                    StreamHelper.ForceReadAll(baseStream, remoteBlob, 0, remoteBlob.Length);

                    remoteKey = new RSACryptoServiceProvider();
                    remoteKey.ImportCspBlob(remoteBlob);
                } catch (Exception) {
                    throw new EncryptedNetworkStreamException(EncryptedNetworkStreamException.Reason.NetworkError);
                }

                rsaStream = new RSAStream(baseStream, localKeys, remoteKey);

                AesCryptoServiceProvider aesKey = new AesCryptoServiceProvider();
                aesKey.KeySize = 256;

                // Authenticate client/server
                byte[] passwordHash = MD5.Create().ComputeHash(ASCIIEncoding.UTF8.GetBytes(streamPassword));

                if (client)
                {
                    // If we're the client, send the password hash (encrypted)
                    rsaStream.Write(passwordHash, 0, 16);

                    // Read AES key
                    byte[] lenBuffer = new byte[4];
                    StreamHelper.ForceReadAll(rsaStream, lenBuffer, 0, 4);

                    byte[] aesKeyBuffer = new Byte[BitConverter.ToInt32(lenBuffer, 0)];
                    StreamHelper.ForceReadAll(rsaStream, aesKeyBuffer, 0, aesKeyBuffer.Length);

                    StreamHelper.ForceReadAll(rsaStream, lenBuffer, 0, 4);

                    byte[] aesIVBuffer = new Byte[BitConverter.ToInt32(lenBuffer, 0)];
                    StreamHelper.ForceReadAll(rsaStream, aesIVBuffer, 0, aesIVBuffer.Length);

                    aesKey.Key = aesKeyBuffer;
                    aesKey.IV = aesIVBuffer;

                } else {
                    // If we're the server, wait for them to send the password (encrypted)
                    byte[] receivedPasswordHash = new byte[16];
                    StreamHelper.ForceReadAll(rsaStream, receivedPasswordHash, 0, 16);

                    if (! passwordHash.SequenceEqual(receivedPasswordHash))
                        throw new EncryptedNetworkStreamException(EncryptedNetworkStreamException.Reason.InvalidAuthentication);

                    // Generate/send AES key
                    aesKey.GenerateKey();
                    aesKey.GenerateIV();

                    // Group length and key togeather to lower overhead

                    byte[] keyDataBuffer = SerializedArray.ToNetworkBytes(aesKey.Key);
                    rsaStream.Write(keyDataBuffer, 0, keyDataBuffer.Length);

                    byte[] keyIVBuffer = SerializedArray.ToNetworkBytes(aesKey.IV);
                    rsaStream.Write(keyIVBuffer, 0, keyIVBuffer.Length);
                }

                aesStream = new AESStream(baseStream, aesKey);

                baseStream.ReadTimeout = oldReadTimeout;
        }
Exemplo n.º 33
0
        /// <summary>
        /// Handles a newly accepted TCP client from the listener
        /// </summary>
        /// <param name="c">The client to handle</param>
        internal static void HandleClient(TcpClient c)
        {
            var rep = c.Client.RemoteEndPoint;
            try {
                // Get a networkstream to work with
                var s = c.GetStream();
                // Initialize a new RSA class to exchange the symetrical keys
                var rsa = new RSACryptoServiceProvider();
                // Get the RSA public key from the client
                var pk = GetPublicKey(s);
                // If the public key was null (e.g. the stream closed), toss out this client
                if (pk == null) {
                    return;
                }
                // If the key wasn't null, import it as the new key for the RSA class
                rsa.ImportCspBlob(pk);
                // Generate a new AES provider with a 256-bit key
                var aes = new AesCryptoServiceProvider {KeySize = 256};
                // Generate the Key and Initialization vector
                aes.GenerateKey();
                aes.GenerateIV();

                // Encrypt the AES Key and IV for transportation to the client
                var aeskey = Encryption.RSAEncrypt(aes.Key, rsa.ExportParameters(false), false);
                var aesiv = Encryption.RSAEncrypt(aes.IV, rsa.ExportParameters(false), false);

                // Write the key and iv to the stream
                s.Write(new[] {(byte) aeskey.Length}, 0, 1);
                s.Write(aeskey, 0, aeskey.Length);
                s.Write(new[] {(byte) aesiv.Length}, 0, 1);
                s.Write(aesiv, 0, aesiv.Length);

                // Read the username and password from the client
                var r = new byte[4096];
                var br = s.Read(r, 0, 4096);
                if (br == 0) return;
                var userpass = Encryption.DecryptStringFromBytesAes(r, br, aes.Key, aes.IV, e);

                // Split the data in two at the first colon to seperate username from password
                var userpass_ = userpass.Split(new[]{':'}, 2);

                // Turn the username and password into their own variables
                var user = userpass_[0];
                var pass = userpass_[1];

                // Attempt to authenticate the user
                var uar = Authentication.Authenticate(user, pass);

                // If the authentication wasn't successful...
                if (uar != UserAuthResult.Success) {
                    if (uar == UserAuthResult.Banned) {
                        // If the user was banned, tell them they are banned
                        var banm = Encryption.EncryptStringToBytesAes("USER_BANNED", aes.Key, aes.IV, e);
                        s.Write(banm, 0, banm.Length);
                    } else {
                        // If the user does not exist or the password was wrong, tell them they had bad credentials
                        var buop = Encryption.EncryptStringToBytesAes("BAD_CRED", aes.Key, aes.IV, e);
                        s.Write(buop, 0, buop.Length);
                    }

                    // Finally, send the client packing
                    c.Close();
                    return;
                }

                var smes = Encryption.EncryptStringToBytesAes("IM_OLD_GREGG__PLEASED_TO_MEET_YA", aes.Key, aes.IV, e);
                s.Write(smes, 0, smes.Length);

                Console.WriteLine("{0} authenticated successfully as {1}", rep, user);

                // Pass the client on to the sustainable client class
                var h = new Client(c, user, aes);
                h.Start();
            }
            catch (Exception exception) {
                // If there was an IO exception, write it to the console
                Console.WriteLine("Exception occured in client handler.\nClient: {1}\nDetails: {0}\n{2}",
                                  exception.GetType(), rep, exception.Message);
                if (c.Connected) c.Close();
            }
        }
 /// <summary>
 /// Generates a random 256 bit key
 /// </summary>
 /// <returns>256 bit key</returns>
 public static byte[] GenerateKey()
 {
     using (var crypto = new AesCryptoServiceProvider())
     {
         crypto.GenerateKey();
         return crypto.Key;
     }
 }