Beispiel #1
0
        public static byte[] EncryptData(byte[] output)
        {
            //byte[] unicodeBytes = Encoding.UTF8.GetBytes(plaintext);
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Padding = PaddingMode.PKCS7;
                aesAlg.KeySize = 256;
                aesAlg.Key     = AES_KEY;
                aesAlg.IV      = AES_IV;

                ICryptoTransform decryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream encryptedData = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(encryptedData, decryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(output, 0, output.Length);
                        cryptoStream.FlushFinalBlock();
                        return(encryptedData.ToArray());
                    }
                }
            }
        }
Beispiel #2
0
        private string Encrypt(string clearText)
        {  // kullanıcı şifresinin kodlanarak şifrelendiği metotdur.
            // şifreyi kodlanmış  şekilde geri döndürür.
            string EncryptionKey = "MAKV2SPBNI99212";

            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    clearText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return(clearText);
        }
Beispiel #3
0
        public static void PaddedAes_PartialRead_Success()
        {
            using (Aes aes = Aes.Create())
            {
                aes.Mode = CipherMode.CBC;
                aes.Key  = aes.IV = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, };

                var memoryStream = new MemoryStream();
                using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write, leaveOpen: true))
                {
                    cryptoStream.Write("Sample string that's bigger than cryptoAlg.BlockSize" u8);
                    cryptoStream.FlushFinalBlock();
                }

                memoryStream.Position = 0;
                using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
                {
                    cryptoStream.ReadByte(); // Partially read the CryptoStream before disposing it.
                }

                // No exception should be thrown.
            }
        }
Beispiel #4
0
 /// <summary>
 /// 加密字节数组
 /// </summary>
 public static byte[] Encrypt(byte[] decodeBytes, string key, bool needIV = false)
 {
     decodeBytes.CheckNotNull("decodeBytes");
     using (Aes aes = Aes.Create())
     {
         aes.Key     = CheckKey(key);
         aes.Padding = PaddingMode.PKCS7;
         aes.Mode    = CipherMode.ECB;
         byte[] ivBytes = { };
         if (needIV)
         {
             aes.Mode = CipherMode.CBC;
             aes.GenerateIV();
             ivBytes = aes.IV;
         }
         using (ICryptoTransform encryptor = aes.CreateEncryptor())
         {
             byte[] encodeBytes = encryptor.TransformFinalBlock(decodeBytes, 0, decodeBytes.Length);
             aes.Clear();
             return(needIV ? ivBytes.Concat(encodeBytes).ToArray() : encodeBytes);
         }
     }
 }
Beispiel #5
0
        public void Modern_AES_256()
        {
            byte[] key = new byte[] { 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae,
                                      0xf0, 0x85, 0x7d, 0x77, 0x81, 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61,
                                      0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
            byte[] iv = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,   //0x0, 0x0, 0x0, 0x0, 0x0, 0x0
                                     0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }; //, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};

            AES a = new AES();

            a.Key = key;
            a.IV  = iv;
            byte[] test = new byte[48] {
                0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34,
                0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34,
                0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34
            };

            byte[] cipher      = a.Encrypt(test);
            byte[] checkcipher = new byte[test.Length];

            using (Aes check = Aes.Create())
            {
                check.Key = a.Key;
                check.IV  = iv;

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

                encryptor.TransformBlock(test, 0, test.Length, checkcipher, 0);
            }

            CollectionAssert.AreEqual(checkcipher, cipher);

            byte[] clear = a.Decrypt(cipher);

            CollectionAssert.AreEqual(test, clear);
        }
Beispiel #6
0
        public static byte[] CryptMessage2(this byte[] cmessage, bool forEncryption, byte[] m_Key, byte[] iVector)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key     = m_Key;
                aesAlg.IV      = iVector;
                aesAlg.Mode    = CipherMode.CFB;
                aesAlg.Padding = PaddingMode.None;

                if (forEncryption)
                {
                    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                    using (MemoryStream msEncrypt = new MemoryStream())
                    {
                        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        {
                            csEncrypt.Write(cmessage, 0, cmessage.Length);
                            csEncrypt.FlushFinalBlock();
                            return(msEncrypt.ToArray());
                        }
                    }
                }
                else
                {
                    using (ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))
                    {
                        using (MemoryStream ms = new MemoryStream())
                            using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                            {
                                cs.Write(cmessage, 0, cmessage.Length); //here is the exception thrown
                                cs.FlushFinalBlock();
                                return(ms.ToArray());
                            }
                    }
                }
            }
        }
 public byte[] EncryptStringToBytes_Aes(string Jsonstring, byte[] Key, byte[] IV)
 {
     // Check arguments.
     if (Jsonstring == null || Jsonstring.Length <= 0)
     {
         throw new ArgumentNullException("Jsonstring");
     }
     if (Key == null || Key.Length <= 0)
     {
         throw new ArgumentNullException("Key");
     }
     if (IV == null || IV.Length <= 0)
     {
         throw new ArgumentNullException("IV");
     }
     byte[] encrypted;
     using (Aes aes = Aes.Create()){
         aes.Key = Key;
         aes.IV  = IV;
         // Create an Encryptor to perform stream transform
         ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
         // Create the streams used for encryption.
         using (MemoryStream msEncrypt = new MemoryStream())
         {
             using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
             {
                 using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                 {
                     //Write all data to the stream.
                     swEncrypt.Write(Jsonstring);
                 }
                 encrypted = msEncrypt.ToArray();
             }
         }
     }
     return(encrypted);
 }
Beispiel #8
0
        private CryptoStream OpenAesStream(Stream streamObj, bool isEncrypt)
        {
            try
            {
                //Create a new instance of the default Aes implementation class
                // and encrypt the stream.
                Aes aes = Aes.Create();

                byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
                byte[] iv  = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

                if (isEncrypt)
                {
                    //Create a CryptoStream for encrypt, pass it the FileStream, and encrypt
                    //it with the Aes class.
                    CryptoStream cryptStreamEncrypt = new CryptoStream(streamObj, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write);
                    Debug.WriteLine("The encrypted stream is opened. =)");
                    return(cryptStreamEncrypt);
                }
                else
                {
                    //Create a CryptoStream for decrypt, pass it the file stream, and decrypt
                    //it with the Aes class using the key and IV.
                    CryptoStream cryptStreamDecrypt = new CryptoStream(streamObj, aes.CreateDecryptor(key, iv), CryptoStreamMode.Read);
                    Debug.WriteLine("The decrypted stream is opened. =)");
                    return(cryptStreamDecrypt);
                }
            }
            catch
            {
                //Inform the user that an exception was raised.
                Debug.WriteLine("The encryption stream open failed. =(");
                return(null);

                throw;
            }
        }
Beispiel #9
0
        public string Encrypt(string plainText, string key)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }

            byte[] encrypted;
            byte[] IV;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.ASCII.GetBytes(key);
                IV         = aesAlg.IV;
                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

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

            // Return the encrypted bytes from the memory stream.
            return($"{ToHexString(IV)}.{ToHexString(encrypted)}");
        }
Beispiel #10
0
        public byte[] Pack(string key, byte[] data)
        {
            byte[] iv = new byte[16];
            byte[] kb = Encoding.UTF8.GetBytes(key);
            RandomProvider.GetBytes(iv);
            Aes aes = Aes.Create();

            aes.KeySize = 256;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key     = kb;
            aes.IV      = iv;
            using (var encryptor = aes.CreateEncryptor())
            {
                using (var m = new MemoryStream())
                {
                    using (var c = new CryptoStream(m, encryptor, CryptoStreamMode.Write))
                    {
                        using (var w = new BinaryWriter(c))
                        {
                            w.Write(data);
                        }
                        var raw = m.ToArray();
                        using (var hmac = new HMACSHA256(kb))
                        {
                            byte[]      hash   = hmac.ComputeHash(raw);
                            List <byte> buffer = new List <byte>();
                            log.InfoFormat("iv: {0} hash: {1} text: {2}", iv.Length, hash.Length, raw.Length);
                            buffer.AddRange(iv);
                            buffer.AddRange(hash);
                            buffer.AddRange(raw);
                            return(buffer.ToArray());
                        }
                    }
                }
            }
        }
Beispiel #11
0
        private static byte[] EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }

            byte[] encrypted;
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = key;
                aesAlg.IV  = iv;

                var encryptor = aesAlg.CreateEncryptor(aesAlg.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(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return(encrypted);
        }
Beispiel #12
0
        public static byte[] Encrypt(string texto, byte[] key, byte[] IV)
        {
            if (texto == null || texto.Length <= 0)
            {
                throw new ArgumentNullException("texto");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException("IV");
            }
            byte[] encrypted;

            using (Aes aes = Aes.Create())
            {
                aes.Key = key;
                aes.IV  = IV;

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

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(texto);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return(encrypted);
        }
Beispiel #13
0
        private byte[] Encrypt(string data, out byte[] key, out byte[] IV)
        {
            if (data == null || data.Length <= 0)
            {
                throw new ArgumentNullException("data");
            }

            byte[] encrypted;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                key = aesAlg.Key;
                IV  = aesAlg.IV;

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

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

            // Return the encrypted bytes from the memory stream.
            return(encrypted);
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            //byte[] key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xAB, 0xCD, 0xEF, 0x01, 0xCD, 0xEF };
            //byte[] IV = { 0x67, 0x89, 0xAB, 0xAB, 0xCD, 0x01, 0x23, 0x45, 0x67, 0x89, 0x23, 0x45, 0xEF, 0x01, 0xCD, 0xEF };

            if (args.Length != 2)
            {
                Console.WriteLine("usage: dotnet Encrypt <<file name>> <<password>>");
            }

            byte[] IV   = new byte[16];
            byte[] salt = new byte[16];
            RandomNumberGenerator rng = RandomNumberGenerator.Create();

            rng.GetBytes(IV);
            rng.GetBytes(salt);
            string             password = "******";
            Rfc2898DeriveBytes hasher   = new Rfc2898DeriveBytes(password, salt);

            byte[] key = hasher.GetBytes(16);

            using (FileStream inputStream = File.OpenRead(@"Encryptor.cs"))
                using (StreamReader reader = new StreamReader(inputStream))
                {
                    using (Aes algorithm = Aes.Create())
                        using (FileStream outputStream = File.Create(@"..\Encryptor.bin"))
                            using (CryptoStream encryptedStream = new CryptoStream(
                                       outputStream,
                                       algorithm.CreateEncryptor(key, IV),
                                       CryptoStreamMode.Write))
                                using (StreamWriter writer = new StreamWriter(encryptedStream))
                                {
                                    writer.Write(reader.ReadToEnd());
                                }
                }
            Console.WriteLine("You have been encrypted.");
        }
Beispiel #15
0
        /// <summary>
        /// Do not use this function at the moment!
        /// </summary>
        /// <param name="plainText"></param>
        /// <param name="Key"></param>
        /// <param name="IV"></param>
        /// <returns></returns>
        internal static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException(nameof(plainText));
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentNullException(nameof(Key));
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentNullException(nameof(IV));
            }
            byte[] encrypted;

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV  = IV;

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

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return(encrypted);
        }
Beispiel #16
0
        //Encripto un string usand el algporitmo AES, retorno bytes.
        public static byte[] Encrypt(string plainText)
        {
            byte[] Key = KeyToBytes();
            byte[] encrypted;
            byte[] IV;

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;

                aesAlg.GenerateIV();
                IV = aesAlg.IV;

                aesAlg.Mode = CipherMode.CBC;

                var encryptor = aesAlg.CreateEncryptor(aesAlg.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(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            var combinedIvCt = new byte[IV.Length + encrypted.Length];

            Array.Copy(IV, 0, combinedIvCt, 0, IV.Length);
            Array.Copy(encrypted, 0, combinedIvCt, IV.Length, encrypted.Length);

            return(combinedIvCt);
        }
Beispiel #17
0
        private static byte[] AesEncryptStringToBytes(string plainText, byte[] key, byte[] iv)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException($"{nameof(plainText)}");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException($"{nameof(key)}");
            }
            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException($"{nameof(iv)}");
            }

            byte[] encrypted;

            using (Aes aes = Aes.Create())
            {
                aes.Mode    = CipherMode.CBC;    //remember this parameter
                aes.Padding = PaddingMode.PKCS7; //remember this parameter
                aes.Key     = key;
                aes.IV      = iv;

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (ICryptoTransform encryptor = aes.CreateEncryptor())
                        using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                            {
                                streamWriter.Write(plainText);
                            }
                    encrypted = memoryStream.ToArray();
                }
            }
            return(encrypted);
        }
        /// <summary>
        /// Encrypt a string using AES
        /// </summary>
        /// <param name="text">The string to encrypt</param>
        /// <param name="keyString">The secret key</param>
        /// <returns></returns>
        public static string EncryptString(string text, string keyString)
        {
            string result = null;

            using (Aes aes = Aes.Create())
            {
                aes.Padding = PaddingMode.PKCS7;

                // AES-256 uses the same block size as AES-128 (the default) however the key size is larger (32 bytes).

                byte[] key = Encoding.UTF8.GetBytes(keyString.Substring(0, AES_256_KEY_SIZE_BYTES));

                using (var encryptor = aes.CreateEncryptor(key, aes.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 = aes.IV;

                        var decryptedContent = msEncrypt.ToArray();

                        byte[] byteResult = new byte[iv.Length + decryptedContent.Length];

                        Buffer.BlockCopy(iv, 0, byteResult, 0, iv.Length);
                        Buffer.BlockCopy(decryptedContent, 0, byteResult, iv.Length, decryptedContent.Length);

                        result = Convert.ToBase64String(byteResult);
                    }
                }
            }
            return(result);
        }
Beispiel #19
0
        /// <summary>
        /// AES 加密
        /// </summary>
        /// <param name="plainText">明文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string Encrypt(string plainText, string key)
        {
            string cipherText = string.Empty;

            try
            {
                // Create an Aes object
                // with the specified key and IV.
                using (Aes aesAlg = Aes.Create())
                {
                    aesAlg.Key = Encoding.UTF8.GetBytes(key);
                    aesAlg.IV  = IV;

                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                    // Create the streams used for encryption.
                    using (MemoryStream msEncrypt = new MemoryStream())
                    {
                        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                            {
                                // Write all data to the stream.
                                swEncrypt.Write(plainText);
                            }
                            cipherText = Convert.ToBase64String(msEncrypt.ToArray());
                        }
                    }
                }
            }
            catch
            {
                cipherText = string.Empty;
            }
            return(cipherText);
        }
        public static string EncryptStringHex(string text, string keyString)
        {
            string result = null;

            using (Aes aes = Aes.Create())
            {
                aes.Padding = PaddingMode.PKCS7;
                byte[] key = Encoding.UTF8.GetBytes(keyString.Substring(0, AES_256_KEY_SIZE_BYTES));

                using (var encryptor = aes.CreateEncryptor(key, aes.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 = aes.IV;

                        byte[] data = msEncrypt.ToArray();

                        byte[] byteResult = new byte[iv.Length + data.Length];

                        Buffer.BlockCopy(iv, 0, byteResult, 0, iv.Length);
                        Buffer.BlockCopy(data, 0, byteResult, iv.Length, data.Length);

                        result = BitConverter.ToString(byteResult).Replace("-", "");
                    }
                }
            }
            return(result);
        }
Beispiel #21
0
        public byte[] Encrypt(string Text, byte[] Key, byte[] IV)
        {
            if (Text == null || Text.Length <= 0)
            {
                throw new ArgumentException("Text");
            }
            if (Key == null || Key.Length <= 0)
            {
                throw new ArgumentException("Key");
            }
            if (IV == null || IV.Length <= 0)
            {
                throw new ArgumentException("IV");
            }

            byte[] eData;

            //Aes object
            using (Aes aes = Aes.Create())
            {
                aes.Key = Key;
                aes.IV  = IV;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(aes.Key, aes.IV), CryptoStreamMode.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(cs))
                        {
                            sw.Write(Text);
                        }

                        eData = ms.ToArray();
                    }
                }
            }
            return(eData);
        }
Beispiel #22
0
        private static string DecryptPrivateKey(string content, string password)
        {
            byte[] passwordHash = GenerateHash(password);
            byte[] contentBytes = Convert.FromBase64String(content);

            byte[] decrypted;
            int    decryptedByteCount = 0;

            byte[] initialVector = new byte[16];
            using (MemoryStream from = new MemoryStream(contentBytes)) {
                from.Read(initialVector, 0, 16);

                using (Aes aes = Aes.Create()) {
                    try {
                        aes.Key  = passwordHash;
                        aes.IV   = initialVector;
                        aes.Mode = CipherMode.ECB;
                        aes.CreateEncryptor(aes.Key, aes.IV);

                        try {
                            using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV)) {
                                using (CryptoStream reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) {
                                    decrypted          = new byte[content.Length];
                                    decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length);
                                }
                            }
                        } catch (Exception e) {
                            return(string.Empty);
                        }
                    } finally {
                        aes.Clear();
                    }
                }
            }

            return(Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount));
        }
Beispiel #23
0
        /// <summary>
        /// AES加密算法(ECB)
        /// </summary>
        /// <param name="plainText">明文字符串</param>
        /// <param name="privateKey">16位密钥</param>
        /// <param name="en">编码,默认Utf8</param>
        /// <returns>将加密后的密文转换为Base64编码,以便显示</returns>
        public static string AESEncrypt(string plainText, string privateKey, Encoding en)
        {
            // password = ShortMD5(password, charsetName);
            byte[] plainBytes = en.GetBytes(plainText);
            byte[] keyBytes   = en.GetBytes(privateKey);
            Aes    kgen       = Aes.Create("AES");

            kgen.Mode = CipherMode.ECB;
            kgen.Key  = keyBytes;
            ICryptoTransform cTransform = kgen.CreateEncryptor();

            byte[] resultArray = cTransform.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
            return(Convert.ToBase64String(resultArray, 0, resultArray.Length));


            ////分组加密算法
            //Aes des = Aes.Create("AES");
            //des.Mode = CipherMode.ECB;
            ////SymmetricAlgorithm des = Rijndael.Create();
            //byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组
            ////设置密钥及密钥向量
            //des.Key = Encoding.UTF8.GetBytes(privateKey);
            ////des.IV = _key1;
            //byte[] cipherBytes = null;
            //using (MemoryStream ms = new MemoryStream())
            //{
            //    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            //    {
            //        cs.Write(inputByteArray, 0, inputByteArray.Length);
            //        cs.FlushFinalBlock();
            //        cipherBytes = ms.ToArray();//得到加密后的字节数组
            //        cs.Close();
            //        ms.Close();
            //    }
            //}
            //return Convert.ToBase64String(cipherBytes);
        }
Beispiel #24
0
        // encriptar y desencriptar adaptados de https://docs.microsoft.com/es-es/dotnet/api/system.security.cryptography.aes?redirectedfrom=MSDN&view=netframework-4.7.2

        private static byte[] EncriptarStringABytes_Aes(string pTextoPlano)
        {
            // Revisar parámetro
            if (pTextoPlano == null || pTextoPlano.Length <= 0)
            {
                throw new ArgumentNullException("pTextoPlano");
            }

            byte[] encriptado;

            // Crear un objeto Aes con la clave y vector de inicializacion especificados
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = KEY;
                aesAlg.IV  = IV;

                // Crear un encriptador para realizar la transformación del stream
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Crear streams usados en la encriptacion
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //escribir datos en el stream
                            swEncrypt.Write(pTextoPlano);
                        }
                        encriptado = msEncrypt.ToArray();
                    }
                }
            }

            // devolver los bytes encriptados del stream de memoria
            return(encriptado);
        }
Beispiel #25
0
        static byte[] EncryptAES(string plainText, byte[] Key)
        {
            byte[] encrypted;
            byte[] IV;

            // Create a new Aes
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.GenerateIV();
                IV          = aesAlg.IV;
                aesAlg.Mode = CipherMode.CBC;
                // Create encryptor
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.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(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            var combinedIvCt = new byte[IV.Length + encrypted.Length];

            Array.Copy(IV, 0, combinedIvCt, 0, IV.Length);
            Array.Copy(encrypted, 0, combinedIvCt, IV.Length, encrypted.Length);

            // Return the encrypted bytes from the memory stream.
            return(combinedIvCt);
        }
        /// <summary>
        /// AES encrypt ( no IV)
        /// </summary>
        /// <param name="data">Raw data</param>
        /// <param name="key">Key, requires 32 bits</param>
        /// <returns>Encrypted string</returns>
        public static string AESEncrypt(string data, string key)
        {
            Check.Argument.IsNotEmpty(data, nameof(data));

            Check.Argument.IsNotEmpty(key, nameof(key));
            Check.Argument.IsNotOutOfRange(key.Length, 32, 32, nameof(key));

            using (MemoryStream Memory = new MemoryStream())
            {
                using (Aes aes = Aes.Create())
                {
                    byte[] plainBytes = Encoding.UTF8.GetBytes(data);
                    Byte[] bKey       = new Byte[32];
                    Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(bKey.Length)), bKey, bKey.Length);

                    aes.Mode    = CipherMode.ECB;
                    aes.Padding = PaddingMode.PKCS7;
                    aes.KeySize = 128;
                    //aes.Key = _key;
                    aes.Key = bKey;
                    //aes.IV = _iV;
                    using (CryptoStream cryptoStream = new CryptoStream(Memory, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        try
                        {
                            cryptoStream.Write(plainBytes, 0, plainBytes.Length);
                            cryptoStream.FlushFinalBlock();
                            return(Convert.ToBase64String(Memory.ToArray()));
                        }
                        catch (Exception ex)
                        {
                            return(null);
                        }
                    }
                }
            }
        }
Beispiel #27
0
        public static string EncryptString(string text, string key)
        {
            return(text);

            if (text == null || text.Length <= 0)
            {
                throw new ArgumentNullException("text is null");
            }
            byte[] encrypted;

            var keyBytes = Encoding.UTF8.GetBytes(key);

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = keyBytes;
                var iv = aesAlg.IV;

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

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            // write iv
                            msEncrypt.Write(iv, 0, iv.Length);
                            //Write all data to the stream.
                            swEncrypt.Write(text);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            return(Convert.ToBase64String(encrypted));
        }
Beispiel #28
0
        public static byte[] Crypt(string plainText)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException(nameof(plainText));
            }
            byte[] encrypted;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Cle;
                aesAlg.IV  = Iv;

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

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

            // Return the encrypted bytes from the memory stream.
            return(encrypted);
        }
Beispiel #29
0
        /// <summary>
        ///     Method to encrypt plain text using AES
        /// </summary>
        /// <param name="plain">Plain text</param>
        /// <param name="key">Secret key used to encrypt</param>
        /// <param name="keySize">Size of the secret key</param>
        /// <returns>Cipher and IV</returns>
        public Tuple <byte[], byte[]> Encrypt(string plain, string key, int keySize = 256)
        {
            byte[] encrypted;
            byte[] hash;
            byte[] iv;

            using (Aes aes = Aes.Create())
            {
                // Set AES algorithm properties to match the one used in front-end
                aes.KeySize   = keySize;
                aes.BlockSize = aes.KeySize / 2;

                Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(key, 16, 1000);
                hash = rfc2898DeriveBytes.GetBytes(32);
                iv   = rfc2898DeriveBytes.Salt;

                aes.Mode    = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                aes.Key     = hash;
                aes.IV      = iv;

                ICryptoTransform aesEncryptor = aes.CreateEncryptor(aes.Key, aes.IV);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                        {
                            streamWriter.Write(plain);
                        }
                        encrypted = memoryStream.ToArray();
                    }
                }
            }

            return(new Tuple <byte[], byte[]>(encrypted, iv));
        }
        public static string EncryptData(string inputText)
        {
            string EncryptionKey = "MAKV2SPBNI99212";

            byte[] clearBytes = Encoding.Unicode.GetBytes(inputText);
            var    returnText = "";

            using (Aes encryptor = Aes.Create())
            {
                Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
                encryptor.Key = pdb.GetBytes(32);
                encryptor.IV  = pdb.GetBytes(16);
                using (MemoryStream ms = new MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    returnText = Convert.ToBase64String(ms.ToArray());
                }
            }
            return(returnText);
        }
Beispiel #31
0
        private static byte[] AesEncryptDirectKey(Aes aes, byte[] key, byte[] iv, byte[] plainBytes)
        {
            using (MemoryStream output = new MemoryStream())
            using (CryptoStream cryptoStream = new CryptoStream(output, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainBytes, 0, plainBytes.Length);
                cryptoStream.FlushFinalBlock();

                return output.ToArray();
            }
        }
Beispiel #32
0
        private static void RandomKeyRoundtrip(Aes aes)
        {
            byte[] decryptedBytes;
            byte[] encryptedBytes;

            using (MemoryStream input = new MemoryStream(s_multiBlockBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateEncryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                encryptedBytes = output.ToArray();
            }

            Assert.NotEqual(s_multiBlockBytes, encryptedBytes);

            using (MemoryStream input = new MemoryStream(encryptedBytes))
            using (CryptoStream cryptoStream = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read))
            using (MemoryStream output = new MemoryStream())
            {
                cryptoStream.CopyTo(output);
                decryptedBytes = output.ToArray();
            }

            Assert.Equal(s_multiBlockBytes, decryptedBytes);
        }