public static byte[] EncryptData(byte[] publickey, byte[] data)
    {
        using (System.Security.Cryptography.Aes myAes = System.Security.Cryptography.Aes.Create())
        {
            System.Security.Cryptography.ICryptoTransform encryptor = myAes.CreateEncryptor(myAes.Key, myAes.IV);
            using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
            {
                using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    System.IO.MemoryStream headerms = new System.IO.MemoryStream();
                    System.IO.BinaryWriter headerbw = new System.IO.BinaryWriter(headerms);
                    using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(csEncrypt))
                    {
                        System.Security.Cryptography.RSACryptoServiceProvider public_key = new System.Security.Cryptography.RSACryptoServiceProvider(1024);
                        public_key.ImportCspBlob(publickey);
                        byte[] encryptedkey = public_key.Encrypt(Combine(myAes.Key, myAes.IV), false);
                        headerbw.Write(encryptedkey.Length);
                        headerbw.Write(myAes.Key.Length);
                        headerbw.Write(myAes.IV.Length);
                        headerbw.Write(encryptedkey);
                        headerbw.Flush();
                        bw.Write(data);
                    }

                    byte[] result = Combine(headerms.ToArray(), msEncrypt.ToArray());
                    headerbw.Close();
                    return(result);
                }
            }
        }
    }
        //암호화
        public static byte[] Encrypt(byte[] plainText, byte[] Key, byte[] IV)
        {
            byte[] cipherText;
            //byte[] plain = { 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 };


            // Create an Aes object
            // with the specified key and IV.
            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.BlockSize = 128;
                aesAlg.Key       = Key;
                aesAlg.IV        = IV;
                aesAlg.Mode      = System.Security.Cryptography.CipherMode.CBC;
                aesAlg.Padding   = System.Security.Cryptography.PaddingMode.PKCS7;

                // Create an encryptor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                cipherText = encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
            }

            return(cipherText);

            //byte[] result = new byte[newPlain.Length];
            //System.Buffer.BlockCopy(cipherText, 0, result, 0, newPlain.Length);

            //// Return the encrypted bytes from the memory stream.
            //return result;
        }
        /// <summary>
        /// 加密(二进制)
        /// </summary>
        /// <param name="data">需要加密的数据。</param>
        /// <param name="password">密钥</param>
        /// <returns>返回加密后的数据。</returns>
        public static byte[] Encrypt(byte[] data, byte[] password)
        {
#if netcore
            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
#else
            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create("AES");
#endif
            aes.Mode = System.Security.Cryptography.CipherMode.ECB;
            aes.Key  = password;
            System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor();
            return(encryptor.TransformFinalBlock(data, 0, data.Length));
        }
Example #4
0
 internal static byte[] AES256Encrypt(byte[] block, byte[] key)
 {
     using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
     {
         aes.Key     = key;
         aes.Mode    = System.Security.Cryptography.CipherMode.ECB;
         aes.Padding = System.Security.Cryptography.PaddingMode.None;
         using (System.Security.Cryptography.ICryptoTransform encryptor = aes.CreateEncryptor())
         {
             return(encryptor.TransformFinalBlock(block, 0, block.Length));
         }
     }
 }
Example #5
0
        } // End Function GenerateKey

        public static string Encrypt(string strPlainText)
        {
            byte[] baCipherTextBuffer = null;

            // System.Text.Encoding enc = System.Text.Encoding.ASCII;
            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                byte[] baPlainTextBuffer      = null;
                byte[] baEncryptionKey        = null;
                byte[] baInitializationVector = null;

                // Create a new key and initialization vector.
                // aes.GenerateKey()
                // aes.GenerateIV()
                aes.Key = HexStringToByteArray(strKey);
                aes.IV  = HexStringToByteArray(strIV);


                // Get the key and initialization vector.
                baEncryptionKey        = aes.Key;
                baInitializationVector = aes.IV;
                // strKey = ByteArrayToHexString(baEncryptionKey)
                // strIV = ByteArrayToHexString(baInitializationVector)

                // Get an encryptor.
                System.Security.Cryptography.ICryptoTransform ifaceAESencryptor = aes.CreateEncryptor(baEncryptionKey, baInitializationVector);

                // Encrypt the data.
                using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, ifaceAESencryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        //Convert the data to a byte array.
                        baPlainTextBuffer = enc.GetBytes(strPlainText);

                        //Write all data to the crypto stream and flush it.
                        csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                        csEncrypt.FlushFinalBlock();

                        //Get encrypted array of bytes.
                        baCipherTextBuffer = msEncrypt.ToArray();
                    }
                }
            }
            return(ByteArrayToHexString(baCipherTextBuffer));
        } // End Function Encrypt
        public static string Encrypt(string plainText)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }
            if (aesProperties.Key == null || aesProperties.Key.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (aesProperties.InitializationVector == null || aesProperties.InitializationVector.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            // Create an Aes object
            // with the specified key and IV.
            byte[] encrypted = null;

            using (System.Security.Cryptography.Aes aesAlg = System.Security.Cryptography.Aes.Create())
            {
                aesAlg.Key = aesProperties.Key;
                aesAlg.IV  = aesProperties.InitializationVector;

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

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            return(Convert.ToBase64String(encrypted));
        }
Example #7
0
        public bool Encrypt(byte[] src, out byte[] dst)
        {
            dst = new byte[src.Length];

            if (key == null)
            {
                key = GetAssemblyHash();
            }

            System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create();
            System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create();
            aes.Key = key;

            System.Security.Cryptography.ICryptoTransform ict = aes.CreateEncryptor();

            for (int l = 0; l < src.Length;)
            {
                l += ict.TransformBlock(src, l, l + bufferSize < src.Length? bufferSize: src.Length - l, dst, l);
            }

            return(true);
        }
Example #8
0
 public byte[] Encrypt(byte[] inBytes)
 {
     return(Crypt(inBytes, aes.CreateEncryptor()));
 }
Example #9
0
        /// <summary>
        /// Construct a keyed universal hash function.
        ///
        /// An instance of a universal hash function needs to store on the order of RandomKeyVectorLengthInBytes values upon construction,
        /// so it is best not to initialize this function for large strings (e.g., those over 32k).
        ///
        /// </summary>
        /// <param name="keyOf16Or24Or32Bytes">A key that should not be known to those who might try to create collisions, provided as an array of 16, 24, or 32 bytes.</param>
        /// <param name="randomKeyVectorLengthInBytes">The length of the random key vector used for hashing.  Should be twice the length of the longest value you expect to hash,
        /// unless you hash values bigger than you would want to keep in memory.  If hashing a value longer than this, the universal hash properties may not hold.</param>
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            // Generate enough random bytes to fill the RandomKeyVector and 4 extra for the InitialRandomKey
            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Key  = keyOf16Or24Or32Bytes;
                aes.IV   = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                // Encrypt a null message with the key using CBC and InitializationVector=0
                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            // Round to next 128-bit boundary since we're using AES 128-bit blocks to generate randomness
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                        // Ensure all bytes are flushed.
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                // Create the random key vector and fill it with random bytes
                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                {
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                }
                // Fill the initial random key with the last remaining 8 bytes
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }
Example #10
0
        public static string Encrypt(string plainText, string encryptionKey)
        {
            //string EncryptionKey = "tahaahat";

            if (plainText == null)
            {
                return(string.Empty);
            }

            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(plainText);

            using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    plainText = HttpServerUtility.UrlTokenEncode(ms.ToArray());
                }
            }
            return(plainText);
        }
Example #11
0
        public string EncryptPassword(string clearText)
        {
            string encryptedText = "";


            string EncryptionKey = "Xavier";

            byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
            using (System.Security.Cryptography.Aes encryptor = System.Security.Cryptography.Aes.Create())
            {
                System.Security.Cryptography.Rfc2898DeriveBytes pdb = new System.Security.Cryptography.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 (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, encryptor.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(clearBytes, 0, clearBytes.Length);
                        cs.Close();
                    }
                    encryptedText = Convert.ToBase64String(ms.ToArray());
                }
            }


            return(encryptedText);
        }
Example #12
0
        /// <summary>
        /// Saves the dataset encrypted in specified file
        /// </summary>
        /// <param name="dataset">Dataset to save</param>
        /// <param name="username">Username for encryption</param>
        /// <param name="password">Password for encryption</param>
        /// <param name="fileName">File name where to save</param>
        /// <param name="compress">Should the file be compressed</param>
        internal static void EncryptDataSet(System.Data.DataSet dataset, string username, string password, string fileName, bool compress)
        {
            // Check the parameters
            if (dataset == null ||
                string.IsNullOrEmpty(username) ||
                string.IsNullOrEmpty(password) ||
                string.IsNullOrEmpty(fileName))
            {
                throw new System.ArgumentNullException("All arguments must be supplied.");
            }

            // Save the dataset as encrypted
            using (System.Security.Cryptography.Aes aes = Cryptography.InitAes(username, password)) {
                using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)) {
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(fileStream, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write)) {
                        if (compress)
                        {
                            // when compression is requested, use GZip
                            using (System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(cryptoStream, System.IO.Compression.CompressionMode.Compress)) {
                                dataset.WriteXml(zipStream, System.Data.XmlWriteMode.WriteSchema);
                                zipStream.Flush();
                            }
                        }
                        else
                        {
                            dataset.WriteXml(cryptoStream, System.Data.XmlWriteMode.WriteSchema);
                            cryptoStream.FlushFinalBlock();
                        }
                    }
                }
            }
        }
Example #13
0
        } // End Function GenerateKey

        public string Encrypt(string plainText)
        {
            string retValue = null;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                byte[] baCipherTextBuffer     = null;
                byte[] baPlainTextBuffer      = null;
                byte[] baEncryptionKey        = HexStringToByteArray(this.m_key);
                byte[] baInitializationVector = HexStringToByteArray(this.m_iv);


                aes.Key = baEncryptionKey;
                aes.IV  = baInitializationVector;


                //Get an encryptor.
                using (System.Security.Cryptography.ICryptoTransform transform =
                           aes.CreateEncryptor(baEncryptionKey, baInitializationVector))
                {
                    //Encrypt the data.
                    using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream csEncrypt =
                                   new System.Security.Cryptography.CryptoStream(
                                       msEncrypt
                                       , transform
                                       , System.Security.Cryptography.CryptoStreamMode.Write
                                       )
                               )
                        {
                            //Convert the data to a byte array.
                            baPlainTextBuffer = this.m_encoding.GetBytes(plainText);

                            //Write all data to the crypto stream and flush it.
                            csEncrypt.Write(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                            csEncrypt.FlushFinalBlock();

                            //Get encrypted array of bytes.
                            baCipherTextBuffer = msEncrypt.ToArray();
                            csEncrypt.Clear();
                        } // End Using csEncrypt
                    }     // End Using msEncrypt
                }         // End Using transform


                retValue = ByteArrayToHexString(baCipherTextBuffer);

                System.Array.Clear(baCipherTextBuffer, 0, baCipherTextBuffer.Length);
                System.Array.Clear(baPlainTextBuffer, 0, baPlainTextBuffer.Length);
                System.Array.Clear(baEncryptionKey, 0, baEncryptionKey.Length);
                System.Array.Clear(baInitializationVector, 0, baInitializationVector.Length);

                baCipherTextBuffer     = null;
                baPlainTextBuffer      = null;
                baEncryptionKey        = null;
                baInitializationVector = null;
            } // End Using aes

            return(retValue);
        } // End Function Encrypt
Example #14
0
        } // End Function GenerateKey

        public static string Encrypt(string plainText)
        {
            string retValue = null;

            if (plainText == null)
            {
                return(null);
            }

            System.Text.Encoding enc = System.Text.Encoding.UTF8;

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                // Create a new key and initialization vector.
                // aes.GenerateKey();
                // aes.GenerateIV();
                aes.Key = HexStringToByteArray(s_key);
                aes.IV  = HexStringToByteArray(s_IV);


                // Get the key and initialization vector.
                byte[] encryptionKey        = aes.Key;
                byte[] initializationVector = aes.IV;
                // strKey = ByteArrayToHexString(encryptionKey)
                // strIV = ByteArrayToHexString(initializationVector)

                // Get an encryptor.
                using (System.Security.Cryptography.ICryptoTransform aesEncryptor = aes.CreateEncryptor(encryptionKey, initializationVector))
                {
                    //Encrypt the data.
                    using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
                    {
                        using (System.Security.Cryptography.CryptoStream csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, aesEncryptor, System.Security.Cryptography.CryptoStreamMode.Write))
                        {
                            //Convert the data to a byte array.
                            byte[] plainTextBuffer = enc.GetBytes(plainText);

                            //Write all data to the crypto stream and flush it.
                            csEncrypt.Write(plainTextBuffer, 0, plainTextBuffer.Length);
                            csEncrypt.FlushFinalBlock();

                            //Get encrypted array of bytes.
                            byte[] cipherTextBuffer = msEncrypt.ToArray();
                            retValue = ByteArrayToHexString(cipherTextBuffer);
                            System.Array.Clear(cipherTextBuffer, 0, cipherTextBuffer.Length);
                            cipherTextBuffer = null;

                            System.Array.Clear(plainTextBuffer, 0, plainTextBuffer.Length);
                            plainTextBuffer = null;
                        } // End Using csEncrypt
                    }     // End Using msEncrypt
                }         // End Using aesEncryptor

                System.Array.Clear(encryptionKey, 0, encryptionKey.Length);
                encryptionKey = null;

                System.Array.Clear(initializationVector, 0, initializationVector.Length);
                initializationVector = null;
            } // End Using aes

            return(retValue);
        } // End Function Encrypt
Example #15
0
        public UniversalHashFunction(byte[] keyOf16Or24Or32Bytes, int randomKeyVectorLengthInBytes = 256)
        {
            int numberOfRandomBytesToGenerate = SetVectorLengthAndGetNumberOfRandomBytesNeeded(randomKeyVectorLengthInBytes);

            using (System.Security.Cryptography.Aes aes = System.Security.Cryptography.Aes.Create())
            {
                aes.Key  = keyOf16Or24Or32Bytes;
                aes.IV   = new byte[16];
                aes.Mode = System.Security.Cryptography.CipherMode.CBC;

                byte[] pseudoRandomBytes;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ciphertext, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        if (numberOfRandomBytesToGenerate % 16 != 0)
                        {
                            numberOfRandomBytesToGenerate += 16 - (numberOfRandomBytesToGenerate % 16);
                        }
                        cs.Write(new byte[numberOfRandomBytesToGenerate], 0, numberOfRandomBytesToGenerate);
                    }
                    pseudoRandomBytes = ciphertext.ToArray();
                }

                _randomKeyVector = new ulong[randomKeyVectorLengthInBytes / 8];
                for (int i = 0; i < _randomKeyVector.Length; i++)
                {
                    _randomKeyVector[i] = BitConverter.ToUInt64(pseudoRandomBytes, i * 8);
                }
                _initialRandomKey = BitConverter.ToUInt64(pseudoRandomBytes, randomKeyVectorLengthInBytes);
            }
        }