Ejemplo n.º 1
0
 /// Generates a unique encryption vector
 public static byte[] GenerateEncryptionVector()
 {
     //Generate a Vector
     RijndaelManaged rm = new RijndaelManaged();
     rm.GenerateIV();
     return rm.IV;
 }
Ejemplo n.º 2
0
	static void Main(string[] args)
	{
		using (var rijndael = new RijndaelManaged())
		using (var hmacsha256 = new HMACSHA256())
		{
			rijndael.GenerateKey();
			rijndael.GenerateIV();
			hmacsha256.Initialize();
			Console.WriteLine(template,	new SoapHexBinary(rijndael.Key), new SoapHexBinary(rijndael.IV), new SoapHexBinary(hmacsha256.Key));
		}

		Console.WriteLine("press any key to exit...");
		Console.ReadKey();
	}
Ejemplo n.º 3
0
    // create Rijndael initialization vector
    private static byte[] CreateRijndaelIv()
    {
        byte[] rijndaelIv;
        using (var myRijndael = new RijndaelManaged())
        {
            myRijndael.Mode = CipherMode.CBC;
            myRijndael.KeySize = 256;
            myRijndael.BlockSize = 256;
            myRijndael.Padding = PaddingMode.Zeros;
            myRijndael.GenerateIV();
            rijndaelIv = myRijndael.IV;
        }

        return rijndaelIv;
    }
Ejemplo n.º 4
0
        public static string Encrypt(string input, string keyy)
        {
            byte[] key, data = System.Text.Encoding.UTF8.GetBytes(input), encdata;

            try
            {
                using (var md5 = new MD5CryptoServiceProvider())
                {
                    key = md5.ComputeHash(Encoding.UTF8.GetBytes(keyy));
                }

                using (var ms = new MemoryStream())
                {
                    using (var rd = new RijndaelManaged())
                    {
                        rd.Key = key;
                        rd.GenerateIV();
                        byte[] iv = rd.IV;

                        using (var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            ms.Write(iv, 0, iv.Length); // write first 16 bytes IV, followed by encrypted message
                            cs.Write(data, 0, data.Length);
                            cs.FlushFinalBlock();
                        }

                        iv = null;
                    }

                    encdata = ms.ToArray();
                }

                return(Convert.ToBase64String(encdata));
            }
            catch
            {
                return(string.Empty);
            }
            finally
            {
                encdata = null;
                data    = null;
                key     = null;
            }
        }
Ejemplo n.º 5
0
        public void RijndaelExample()
        {
            string original = "Here is some data to encrypt!";

            // Create a new instance of the RijndaelManaged
            // class.  This generates a new key and initialization
            // vector (IV).
            using (var myRijndael = new RijndaelManaged()) {
                myRijndael.GenerateKey();
                myRijndael.GenerateIV();

                // Encrypt the string to an array of bytes.
                byte[] encrypted;
                var    encryptor = myRijndael.CreateEncryptor(myRijndael.Key, myRijndael.IV);

                // Create the streams used for encryption.
                using (var msEncrypt = new MemoryStream()) {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
                        using (var swEncrypt = new StreamWriter(csEncrypt)) {
                            //Write all data to the stream.
                            swEncrypt.Write(original);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }

                // Decrypt the bytes to a string.
                string plaintext = null;
                var    decryptor = myRijndael.CreateDecryptor(myRijndael.Key, myRijndael.IV);

                // Create the streams used for decryption.
                using (var msDecrypt = new MemoryStream(encrypted)) {
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) {
                        using (var srDecrypt = new StreamReader(csDecrypt)) {
                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

                //Display the original data and the decrypted data.
                Assert.AreEqual(plaintext, original);
            }
        }
Ejemplo n.º 6
0
        public static byte[] Encrypt(byte[] input, byte[] keyy)
        {
            byte[] key, data = input, encdata;

            try
            {
                using (var md5 = new MD5CryptoServiceProvider())
                {
                    key = md5.ComputeHash(keyy);
                }

                using (var ms = new MemoryStream())
                {
                    using (var rd = new RijndaelManaged())
                    {
                        rd.Key = key;
                        rd.GenerateIV();
                        byte[] iv = rd.IV;

                        using (var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            ms.Write(iv, 0, iv.Length); // write first 16 bytes IV, followed by encrypted message
                            cs.Write(data, 0, data.Length);
                            cs.FlushFinalBlock();
                        }

                        iv = null;
                    }

                    encdata = ms.ToArray();
                }

                return(encdata);
            }
            catch
            {
                return(new byte[0]);
            }
            finally
            {
                encdata = null;
                data    = null;
                key     = null;
            }
        }
        /// <summary>
        /// Encrypts and encodes a string value.
        /// </summary>
        /// <param name="data">The string you wish to encrypt.</param>
        /// <returns>The encrypted and encoded string.</returns>
        public string encrypt(string data)
        {
            string encrypted_text = "";

            byte[] encrypted_bytes = new byte[0];

            switch (this.cipher)
            {
            case CIPHER_AES128:
                RijndaelManaged myRijndael = new RijndaelManaged();

                // setting the key here lets Rijndael know how many bits to use for the IV
                myRijndael.Key = this.key;
                // create a random IV
                myRijndael.GenerateIV();

                // encrypt our data string
                byte[] aes = encryptAES128(data, myRijndael.Key, myRijndael.IV);

                // concatenate the IV and the encrypted bytes so PHP can decrypt them later
                encrypted_bytes = new byte[myRijndael.IV.Length + aes.Length];
                Buffer.BlockCopy(myRijndael.IV, 0, encrypted_bytes, 0, myRijndael.IV.Length);
                Buffer.BlockCopy(aes, 0, encrypted_bytes, myRijndael.IV.Length, aes.Length);
                break;

            case CIPHER_RC4:
                encrypted_bytes = encryptRC4(data, this.key);
                break;
            }

            // encode our concatenated byte array to the apropriate string format
            switch (this.encoder)
            {
            case ENCODE_HEX:
                encrypted_text = bin2hex(encrypted_bytes);
                break;

            case ENCODE_BASE64:
                encrypted_text = Convert.ToBase64String(encrypted_bytes);
                break;
            }

            // return the string
            return(encrypted_text);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 获得初始向量IV
        /// </summary>
        /// <returns>初试向量IV</returns>
        private static byte[] GetLegalIV()
        {
            string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";

            mobjCryptoService.GenerateIV();
            byte[] bytTemp  = mobjCryptoService.IV;
            int    IVLength = bytTemp.Length;

            if (sTemp.Length > IVLength)
            {
                sTemp = sTemp.Substring(0, IVLength);
            }
            else if (sTemp.Length < IVLength)
            {
                sTemp = sTemp.PadRight(IVLength);
            }
            return(ASCIIEncoding.ASCII.GetBytes(sTemp));
        }
 public EncryptedMessage Encrypt <T>(T obj)
 {
     _aes.GenerateIV();
     using (MemoryStream memoryStream = new MemoryStream())
     {
         using (CryptoStream cryptoStream = new CryptoStream(memoryStream, _aes.CreateEncryptor(), CryptoStreamMode.Write))
         {
             byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj));
             cryptoStream.Write(bytes, 0, bytes.Length);
             cryptoStream.FlushFinalBlock();
             return(new EncryptedMessage
             {
                 IV = _aes.IV,
                 CipherText = memoryStream.ToArray()
             });
         }
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Encrypts a message with AES with a given key and a random salt that gets encoded as the first 16 bytes of the encrypted buffer
        /// </summary>
        /// <param name="clearStream">The stream to be encrypted</param>
        /// <param name="clientId">The clientId whose AES key to use</param>
        /// <returns>The encrypted stream with encoded salt</returns>
        public static Stream EncryptStream(Stream clearStream, uint clientId)
        {
            using (RijndaelManaged aes = new RijndaelManaged())
            {
                aes.Key = NetworkingManager.singleton.isServer ? NetworkingManager.singleton.ConnectedClients[clientId].AesKey : NetworkingManager.singleton.clientAesKey;
                aes.GenerateIV();

                using (CryptoStream cs = new CryptoStream(clearStream, aes.CreateEncryptor(), CryptoStreamMode.Read))
                {
                    using (PooledBitStream outStream = PooledBitStream.Get())
                    {
                        outStream.Write(aes.IV, 0, 16);
                        outStream.CopyFrom(cs);
                        return(outStream);
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public (byte[] IV, byte[] Key) GenerateKeys(bool overwriteInstanceKeys)
        {
            using (var rijndaelManaged = new RijndaelManaged())
            {
                Configurate(rijndaelManaged);

                rijndaelManaged.GenerateIV();
                rijndaelManaged.GenerateKey();

                if (overwriteInstanceKeys)
                {
                    _settings.IV  = rijndaelManaged.IV;
                    _settings.Key = rijndaelManaged.Key;
                }

                return(rijndaelManaged.IV, rijndaelManaged.Key);
            }
        }
Ejemplo n.º 12
0
    public static string EncryptMessage(byte[] text, string key)
    {
        RijndaelManaged aes = new RijndaelManaged();
        aes.KeySize = 256;
        aes.BlockSize = 256;
        aes.Padding = PaddingMode.Zeros;
        aes.Mode = CipherMode.CBC;

        aes.Key = Encoding.Default.GetBytes(key);
        aes.GenerateIV();

        string IV = ("-[--IV-[-" + Encoding.Default.GetString(aes.IV));

        ICryptoTransform AESEncrypt = aes.CreateEncryptor(aes.Key, aes.IV);
        byte[] buffer = text;

        return Convert.ToBase64String(Encoding.Default.GetBytes(Encoding.Default.GetString(AESEncrypt.TransformFinalBlock(buffer, 0, buffer.Length)) + IV));
    }
Ejemplo n.º 13
0
        public byte[] GenerateAesKeys()
        {
            try
            {
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {
                    myRijndael.GenerateIV();
                    this.initializationVector = myRijndael.IV;
                    this.GetAESKey(myRijndael);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }

            return(this.initializationVector);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 获得初始向量IV
        /// </summary>
        /// <returns>初试向量IV</returns>
        private static byte[] GetLegalIV()
        {
            string sTemp = IV;

            myRijndael.GenerateIV();
            byte[] bytTemp  = myRijndael.IV;
            int    IVLength = bytTemp.Length;

            if (sTemp.Length > IVLength)
            {
                sTemp = sTemp.Substring(0, IVLength);
            }
            else if (sTemp.Length < IVLength)
            {
                sTemp = sTemp.PadRight(IVLength, ' ');
            }
            return(ASCIIEncoding.ASCII.GetBytes(sTemp));
        }
Ejemplo n.º 15
0
        //Prevoius
        //public string EncryptString(string text)
        //{
        //    try
        //    {
        //        var key = Encoding.UTF8.GetBytes(keyString);

        //        using (var aesAlg = Aes.Create())
        //        {
        //            using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
        //            {
        //                using (var msEncrypt = new MemoryStream())
        //                {
        //                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
        //                    using (var swEncrypt = new StreamWriter(csEncrypt))
        //                    {
        //                        swEncrypt.Write(text);
        //                    }

        //                    var iv = aesAlg.IV;

        //                    var decryptedContent = msEncrypt.ToArray();

        //                    var result = new byte[iv.Length + decryptedContent.Length];

        //                    Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
        //                    Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);

        //                    return Convert.ToBase64String(result);
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return ex.Message;
        //    }
        //}

        //// Previous
        //public string DecryptString(string cipherText)
        //{
        //    try
        //    {
        //        var fullCipher = Convert.FromBase64String(cipherText);

        //        var iv = new byte[16];
        //        var cipher = new byte[16];

        //        Buffer.BlockCopy(fullCipher, 0, iv, 0, iv.Length);
        //        Buffer.BlockCopy(fullCipher, iv.Length, cipher, 0, iv.Length);
        //        var key = Encoding.UTF8.GetBytes(keyString);

        //        using (var aesAlg = Aes.Create())
        //        {
        //            using (var decryptor = aesAlg.CreateDecryptor(key, iv))
        //            {
        //                string result;
        //                using (var msDecrypt = new MemoryStream(cipher))
        //                {
        //                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        //                    {
        //                        using (var srDecrypt = new StreamReader(csDecrypt))
        //                        {
        //                            result = srDecrypt.ReadToEnd();
        //                        }
        //                    }
        //                }

        //                return result;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        return ex.Message;
        //    }
        //}

        public string GenerateKey(int iKeySize)
        {
            RijndaelManaged aesEncryption = new RijndaelManaged();

            aesEncryption.KeySize   = iKeySize;
            aesEncryption.BlockSize = 128;
            aesEncryption.Mode      = CipherMode.CBC;
            //aesEncryption.Padding = PaddingMode.PKCS7;
            aesEncryption.Padding = PaddingMode.ISO10126;
            aesEncryption.GenerateIV();
            string ivStr = Convert.ToBase64String(aesEncryption.IV);

            aesEncryption.GenerateKey();
            string keyStr      = Convert.ToBase64String(aesEncryption.Key);
            string completeKey = ivStr + "," + keyStr;

            return(Convert.ToBase64String(ASCIIEncoding.UTF8.GetBytes(completeKey)));
        }
Ejemplo n.º 16
0
        /// <summary>
        ///
        /// </summary>
        public static AesKey GetNewAesKey(
            int keySize             = 256,
            int blockSize           = 128,
            CipherMode cipherMode   = CipherMode.CBC,
            PaddingMode paddingMode = PaddingMode.PKCS7)
        {
            using (var key = new RijndaelManaged())
            {
                key.Mode      = cipherMode;
                key.Padding   = paddingMode;
                key.KeySize   = keySize;
                key.BlockSize = blockSize;

                key.GenerateKey();
                key.GenerateIV();
                return(new AesKey(key));
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Encrypts the given array of bytes, using the configured key. Returns an <see cref="EncryptedData"/> containing the encrypted
        /// bytes and the generated salt.
        /// </summary>
        public EncryptedData Encrypt(byte[] bytes)
        {
            using (var rijndael = new RijndaelManaged())
            {
                rijndael.GenerateIV();
                rijndael.Key = _key;

                using (var encryptor = rijndael.CreateEncryptor())
                    using (var destination = new MemoryStream())
                        using (var cryptoStream = new CryptoStream(destination, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(bytes, 0, bytes.Length);
                            cryptoStream.FlushFinalBlock();

                            return(new EncryptedData(destination.ToArray(), rijndael.IV));
                        }
            }
        }
 static void Main(string[] args)
 {
     using (RijndaelManaged myRijndael = new RijndaelManaged())
     {
         myRijndael.GenerateKey();
         myRijndael.GenerateIV();
         // Encrypt the string to an array of bytes.
         var key = Convert.ToBase64String(myRijndael.Key);
         var Iv  = Convert.ToBase64String(myRijndael.IV);
         Console.WriteLine(" Key and IV Generator");
         Console.WriteLine();
         Console.WriteLine(" KEY" + " - " + Convert.ToBase64String(myRijndael.Key));
         Console.WriteLine(" IV" + " - " + Convert.ToBase64String(myRijndael.IV));
         Console.WriteLine();
         Console.WriteLine("-----------Press enter key to close-------------");
     }
     Console.ReadLine();
 }
Ejemplo n.º 19
0
        private void btnAesKeyIv_Click(object sender, EventArgs e)
        {
            RijndaelManaged aesEncryption = new RijndaelManaged();

            aesEncryption.KeySize   = 256;
            aesEncryption.BlockSize = 128;
            aesEncryption.Mode      = CipherMode.CBC;
            aesEncryption.Padding   = PaddingMode.PKCS7;
            aesEncryption.GenerateIV();
            string ivStr = Convert.ToBase64String(aesEncryption.IV);

            aesEncryption.GenerateKey();
            string keyStr      = Convert.ToBase64String(aesEncryption.Key);
            string completeKey = string.Format("IV: {0}\r\nKey: {1}", ivStr, keyStr);


            txtEncodingOutput.Text = completeKey;
        }
Ejemplo n.º 20
0
        public string MakeWebCacheRequest(WebCache cache, string request)
        {
            try
            {
                RijndaelManaged crypt = new RijndaelManaged();
                crypt.BlockSize = 256;
                crypt.Padding   = PaddingMode.Zeros;
                crypt.GenerateIV();
                crypt.Key = cache.AccessKey;

                byte[] data      = ASCIIEncoding.ASCII.GetBytes(request);
                byte[] encrypted = crypt.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);


                // php decode requests
                byte[] ivEnc = Utilities.CombineArrays(crypt.IV, encrypted);
                string get   = Convert.ToBase64String(ivEnc);

                string response = Utilities.WebDownloadString(cache.Address + "?get=" + Uri.EscapeDataString(get));

                if (response == null || response == "")
                {
                    throw new Exception("Access key not accepted");
                }

                // php encode response
                byte[] decoded = Convert.FromBase64String(response);

                // decode response
                crypt.IV = Utilities.ExtractBytes(decoded, 0, 32);

                data = Utilities.ExtractBytes(decoded, 32, decoded.Length - 32);
                byte[] decrypted = crypt.CreateDecryptor().TransformFinalBlock(data, 0, data.Length);

                response = ASCIIEncoding.ASCII.GetString(decrypted);
                response = response.Trim('\0');

                return(response);
            }
            catch (Exception ex)
            {
                return("error: " + ex.Message);
            }
        }
Ejemplo n.º 21
0
        public override byte[] Encrypt(byte[] source)
        {
            using (RijndaelManaged myRijndael = new RijndaelManaged())
            {
                if (Key == null)
                {
                    myRijndael.GenerateKey();
                    Key     = myRijndael.Key;
                    KeySize = myRijndael.KeySize;
                }
                else
                {
                    myRijndael.Key = Key;
                }

                if (IV == null)
                {
                    myRijndael.GenerateIV();
                    IV = myRijndael.IV;
                }
                else
                {
                    myRijndael.IV = IV;
                }

                // Encrypt the string to an array of bytes.
                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = myRijndael.CreateEncryptor(myRijndael.Key, myRijndael.IV);

                byte[] encrypted;
                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(source, 0, source.Length);
                        csEncrypt.FlushFinalBlock();
                        encrypted = msEncrypt.ToArray();
                    }
                }

                return(encrypted);
            }
        }
Ejemplo n.º 22
0
        public static byte[] Encrypt <T>(T data, bool lz4 = false, bool index = false)
        {
            if (data == null)
            {
                return(null);
            }

            var array = ConvertByte(data);

            if (lz4)
            {
                var array2 = LZ4Codec.EncodeHC(array, 0, array.Length);
                if (array2.Length > 0)
                {
                    var value = array.Length;
                    array = new byte[array2.Length + 4];
                    Buffer.BlockCopy(BitConverter.GetBytes(value), 0, array, 0, 4);
                    Buffer.BlockCopy(array2, 0, array, 4, array2.Length);
                }
                else
                {
                    MessageBox.Show(@"圧縮失敗!: " + data);
                }
            }

            using (var rhinelandManaged = new RijndaelManaged())
            {
                rhinelandManaged.BlockSize = 128;
                rhinelandManaged.KeySize   = 128;
                rhinelandManaged.Key       = index ? PrivateKey : IndexKey;
                rhinelandManaged.Mode      = CipherMode.CBC;
                rhinelandManaged.Padding   = PaddingMode.PKCS7;
                rhinelandManaged.GenerateIV();
                var iV = rhinelandManaged.IV;
                using (var cryptoTransform = rhinelandManaged.CreateEncryptor())
                {
                    var array2 = cryptoTransform.TransformFinalBlock(array, 0, array.Length);
                    var array3 = new byte[iV.Length + array2.Length];
                    Buffer.BlockCopy(iV, 0, array3, 0, 16);
                    Buffer.BlockCopy(array2, 0, array3, 16, array2.Length);
                    return(array3);
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 获得初始向量IV
        /// </summary>
        /// <returns>初试向量IV</returns>
        private byte[] GetLegalIV(string strVI)
        {
            SymmetricAlgorithm mobjCryptoService = new RijndaelManaged();
            string             sTemp             = strVI;

            mobjCryptoService.GenerateIV();
            byte[] bytTemp  = mobjCryptoService.IV;
            int    IVLength = bytTemp.Length;

            if (sTemp.Length > IVLength)
            {
                sTemp = sTemp.Substring(0, IVLength);
            }
            else if (sTemp.Length < IVLength)
            {
                sTemp = sTemp.PadRight(IVLength, ' ');
            }
            return(ASCIIEncoding.ASCII.GetBytes(sTemp));
        }
Ejemplo n.º 24
0
        public static byte[] EncryptBytes(byte[] data, byte[] key)
        {
            RijndaelManaged crypt = new RijndaelManaged();

            crypt.Key = key;
            crypt.GenerateIV();
            crypt.Padding = PaddingMode.PKCS7;

            ICryptoTransform encryptor = crypt.CreateEncryptor();

            byte[] transformed = encryptor.TransformFinalBlock(data, 0, data.Length);

            byte[] final = new byte[crypt.IV.Length + transformed.Length];

            crypt.IV.CopyTo(final, 0);
            transformed.CopyTo(final, crypt.IV.Length);

            return(final);
        }
        public static string AesEncrypt(string key, string iv, string plainText)
        {
            // with the specified key and IV.
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.GenerateIV();
                rijAlg.GenerateKey();

                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                using MemoryStream msEncrypt = new MemoryStream();
                using CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
                using StreamWriter swEncrypt = new StreamWriter(csEncrypt);

                swEncrypt.Write(plainText);

                return(Convert.ToBase64String(msEncrypt.ToArray()));
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Encrypts a string using AES 256-bit encryption
        /// </summary>
        public static string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                return("");
            }

            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            var keyBytes       = GetEncryptionKey();

            var aes = new RijndaelManaged();

            aes.KeySize = KeySize;
            aes.Mode    = CipherMode.CBC;
            aes.GenerateIV();               // We use a generated IV

            var ivBytes = aes.IV;

            byte[] cipherTextBytes = null;

            using (var encryptor = aes.CreateEncryptor(keyBytes, ivBytes)) {
                using (var ms = new MemoryStream()) {
                    using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) {
                        // Prepend the IV to the encrypted bytes, so that we can
                        // retrieve it later when decrypting. (The IV is used to
                        // randomize the encryption process, so that the same password
                        // encrypted twice generates a different cipher text each time).
                        // As it is only used for randomisation on encryption, it does
                        // not matter that it can be extracted easily from the cipher
                        // text; without the encryption key, the IV is useless.
                        ms.Write(ivBytes, 0, aes.IV.Length);
                        cs.Write(plainTextBytes, 0, plainTextBytes.Length);
                        cs.FlushFinalBlock();
                        cipherTextBytes = ms.ToArray();
                        ms.Close();
                        cs.Close();
                    }
                }
            }
            aes.Clear();

            return(Convert.ToBase64String(cipherTextBytes));
        }
Ejemplo n.º 27
0
        public static byte[] Encrypt(byte[] input, byte[] key)
        {
            if (key == null || key.Length == 0)
            {
                throw new Exception("Key can not be empty.");
            }
            if (input == null || input.Length == 0)
            {
                throw new ArgumentException("Input can not be empty.");
            }

            using (var md5 = new MD5CryptoServiceProvider())
            {
                key = md5.ComputeHash(key);
            }

            byte[] data = input, encdata = new byte[0];

            try
            {
                using (var ms = new MemoryStream())
                {
                    using (var rd = new RijndaelManaged {
                        Key = key
                    })
                    {
                        rd.GenerateIV();

                        using (var cs = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            ms.Write(rd.IV, 0, rd.IV.Length); // write first 16 bytes IV, followed by encrypted message
                            cs.Write(data, 0, data.Length);
                        }
                    }

                    encdata = ms.ToArray();
                }
            }
            catch
            {
            }
            return(encdata);
        }
Ejemplo n.º 28
0
        public String Encrypt(String StringToEncrypt, String Key32)
        {
            if (Key32.Length != 32)
            {
                return(String.Empty);
            }
            if (StringToEncrypt == String.Empty)
            {
                return(String.Empty);
            }
            RijndaelManaged myRijndael = new RijndaelManaged();

            myRijndael.Key = str_to_bytes(Key32);
            myRijndael.GenerateIV();
            String encrypted = Convert.ToBase64String(encryptStringToBytes_AES(StringToEncrypt, myRijndael.Key, myRijndael.IV), Base64FormattingOptions.None);
            String iv        = Convert.ToBase64String(myRijndael.IV, Base64FormattingOptions.None);

            return(iv + "|" + encrypted);
        }
Ejemplo n.º 29
0
        protected override void SerializeMessage(Stream output, object message)
        {
            using (var rijndael = new RijndaelManaged())
            {
                rijndael.Key  = this.encryptionKey;
                rijndael.Mode = CipherMode.CBC;
                rijndael.GenerateIV();

                using (var encryptor = rijndael.CreateEncryptor())
                    using (var outputWrapper = new UndisposableStream(output))
                        using (var encryptionStream = new CryptoStream(outputWrapper, encryptor, CryptoStreamMode.Write))
                        {
                            outputWrapper.Write(rijndael.IV, 0, rijndael.IV.Length);
                            this.inner.Serialize(encryptionStream, message);
                            encryptionStream.Flush();
                            encryptionStream.FlushFinalBlock();
                        }
            }
        }
Ejemplo n.º 30
0
        public virtual void Serialize <T>(Stream output, T graph)
        {
            using (var rijndael = new RijndaelManaged())
            {
                rijndael.Key  = this.encryptionKey;
                rijndael.Mode = CipherMode.CBC;
                rijndael.GenerateIV();

                using (var encryptor = rijndael.CreateEncryptor())
                    using (var wrappedOutput = new IndisposableStream(output))
                        using (var encryptionStream = new CryptoStream(wrappedOutput, encryptor, CryptoStreamMode.Write))
                        {
                            wrappedOutput.Write(rijndael.IV, 0, rijndael.IV.Length);
                            this.inner.Serialize(encryptionStream, graph);
                            encryptionStream.Flush();
                            encryptionStream.FlushFinalBlock();
                        }
            }
        }
Ejemplo n.º 31
0
        public string Encrypt(string strToEncrypt, SecureString strSecret)
        {
            if (strToEncrypt == "" || strSecret.Length == 0)
            {
                return(strToEncrypt);
            }

            try
            {
                var rd = new RijndaelManaged();

                var md5 = new MD5CryptoServiceProvider();
                var key = md5.ComputeHash(Encoding.UTF8.GetBytes(strSecret.ConvertToUnsecureString()));

                md5.Clear();
                rd.Key = key;
                rd.GenerateIV();

                var iv = rd.IV;
                var ms = new MemoryStream();

                ms.Write(iv, 0, iv.Length);

                var cs   = new CryptoStream(ms, rd.CreateEncryptor(), CryptoStreamMode.Write);
                var data = Encoding.UTF8.GetBytes(strToEncrypt);

                cs.Write(data, 0, data.Length);
                cs.FlushFinalBlock();

                var encdata = ms.ToArray();
                cs.Close();
                rd.Clear();

                return(Convert.ToBase64String(encdata));
            }
            catch (Exception ex)
            {
                Runtime.MessageCollector.AddMessage(MessageClass.ErrorMsg,
                                                    string.Format(Language.strErrorEncryptionFailed, ex.Message));
            }

            return(strToEncrypt);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Create a new AES helper given a password
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static AesHelper CreateFromPassword(string password)
        {
            var phasher    = new Rfc2898DeriveBytes(password, 8);
            var psalt      = phasher.Salt;
            var datakeykey = phasher.GetBytes(16); // 128 bits
            var phashsalt  = new byte[8];

            using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                rngCsp.GetBytes(phashsalt);
            }
            var phashhasher = new Rfc2898DeriveBytes(datakeykey, phashsalt, 8192);
            var phashhash   = phashhasher.GetBytes(IVSize);

            RijndaelManaged dataKeyAesProvider = CreateDataKeyAesProvider(datakeykey);

            dataKeyAesProvider.GenerateIV();
            return(new AesHelper(datakeykey, psalt, phashhash, phashsalt, dataKeyAesProvider, dataKeyAesProvider.IV));
        }
Ejemplo n.º 33
0
        internal static string Encrypt(string data)
        {
            if (string.IsNullOrEmpty(data) || string.IsNullOrWhiteSpace(data))
            {
                return(string.Empty);
            }

            try {
                using (RijndaelManaged myRijndael = new RijndaelManaged()) {
                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    return(Convert.ToBase64String(EncryptStringToBytes(data, myRijndael.Key, myRijndael.IV)));
                }
            }
            catch (Exception e) {
                Logger.Exception(e);
                return(string.Empty);
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Sets the encrypted CharacterName to the given SecureString, if possible
        /// </summary>
        /// <param name="CharacterName"></param>
        void SetEncryptedCharacterName(System.Security.SecureString CharacterName)
        {
            if (!App.Settings.UseMasterKey || CharacterName == null)
            {
                ClearEncryptedCharacterName();
                return;
            }

            if (!App.Settings.RequestMasterPassword())
            {
                System.Windows.MessageBox.Show("Your configured Master Password is required in order to save EVE Account Character Names and passwords. It can be reset or disabled by un-checking 'Save passwords (securely)', and then all currently saved EVE Account Character Names will be lost.");
                return;
            }

            using (RijndaelManaged rjm = new RijndaelManaged())
            {
                if (string.IsNullOrEmpty(EncryptedCharacterNameIV))
                {
                    rjm.GenerateIV();
                    EncryptedCharacterNameIV = Convert.ToBase64String(rjm.IV);
                }
                else
                {
                    rjm.IV = Convert.FromBase64String(EncryptedCharacterNameIV);
                }

                using (SecureBytesWrapper sbwKey = new SecureBytesWrapper(App.Settings.PasswordMasterKey, true))
                {
                    rjm.Key = sbwKey.Bytes;

                    using (ICryptoTransform encryptor = rjm.CreateEncryptor())
                    {
                        using (SecureStringWrapper ssw2 = new SecureStringWrapper(CharacterName, Encoding.Unicode))
                        {
                            byte[] inblock   = ssw2.ToByteArray();
                            byte[] encrypted = encryptor.TransformFinalBlock(inblock, 0, inblock.Length);
                            EncryptedCharacterName = Convert.ToBase64String(encrypted);
                        }
                    }
                }
            }
        }