Example #1
0
        // ========================================
        // static field
        // ========================================
        public static string EncryptString(string str, string password)
        {
            var aes = new System.Security.Cryptography.AesCryptoServiceProvider();

            var data = System.Text.Encoding.UTF8.GetBytes(str);

            var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);

            aes.Key = ResizeBytesArray(passwordBytes, aes.Key.Length);
            aes.IV  = ResizeBytesArray(passwordBytes, aes.IV.Length);

            var stream      = new System.IO.MemoryStream();
            var encryptor   = aes.CreateEncryptor();
            var cryptStream = new System.Security.Cryptography.CryptoStream(
                stream,
                encryptor,
                System.Security.Cryptography.CryptoStreamMode.Write
                );

            try {
                cryptStream.Write(data, 0, data.Length);
                cryptStream.FlushFinalBlock();
                var encrypted = stream.ToArray();
                return(System.Convert.ToBase64String(encrypted));
            } finally {
                cryptStream.Close();
                stream.Close();
            }
        }
Example #2
0
        public byte[] Encrypt(string plainText, out byte[] keyBytes, out byte[] ivBytes)
        {
            if (plainText == null || plainText.Length <= 0)
            {
                throw new ArgumentNullException("plainText");
            }

            System.IO.MemoryStream memoryStream;

            using (System.Security.Cryptography.AesCryptoServiceProvider csp = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                csp.GenerateKey();
                csp.GenerateIV();

                keyBytes = csp.Key;
                ivBytes  = csp.IV;
                //csp.CreateEncryptor

                // Create an encryptor to perform the stream transform.
                System.Security.Cryptography.ICryptoTransform cryptoTransformer = csp.CreateEncryptor(csp.Key, csp.IV);

                // Create the streams used for encryption.
                using (memoryStream = new System.IO.MemoryStream())
                    using (System.Security.Cryptography.CryptoStream cryptoStream = new System.Security.Cryptography.CryptoStream(memoryStream, cryptoTransformer, System.Security.Cryptography.CryptoStreamMode.Write))
                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(cryptoStream))
                        {
                            sw.AutoFlush = true;
                            sw.Write(plainText);
                        }
            }

            return(memoryStream.ToArray());
        }
Example #3
0
 public static byte[] AESEncrypt(byte[] input)
 {
     using (var aes = new System.Security.Cryptography.AesCryptoServiceProvider())
     {
         aes.Key = aeskey;
         aes.IV  = aesvector;
         using (var ms = new System.IO.MemoryStream())
         {
             var cs = new System.Security.Cryptography.CryptoStream(ms, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
             if (cs == null)
             {
                 return(null);
             }
             cs.Write(input, 0, input.Length);
             cs.FlushFinalBlock();
             return(ms.ToArray());
         }
     }
 }
Example #4
0
        private string Encrypt256(string text)
        {
            // AesCryptoServiceProvider
            System.Security.Cryptography.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider();
            aes.BlockSize = 128;
            aes.KeySize = 256;
            aes.IV = System.Text.Encoding.UTF8.GetBytes(AesIV256);
            aes.Key = System.Text.Encoding.UTF8.GetBytes(AesKey256);
            aes.Mode = System.Security.Cryptography.CipherMode.CBC;
            aes.Padding = System.Security.Cryptography.PaddingMode.PKCS7;

            // Convert string to byte array
            byte[] src = System.Text.Encoding.Unicode.GetBytes(text);

            // encryption
            using (System.Security.Cryptography.ICryptoTransform encrypt = aes.CreateEncryptor())
            {
                byte[] dest = encrypt.TransformFinalBlock(src, 0, src.Length);

                // Convert byte array to Base64 strings
                return Convert.ToBase64String(dest);
            }
        }
Example #5
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.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                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 #6
0
        public static string aesEncryptBase64(string SourceStr, ulong Key)
        {
            string encrypt = "";

            try
            {
                var    aes    = new System.Security.Cryptography.AesCryptoServiceProvider();
                var    md5    = new System.Security.Cryptography.MD5CryptoServiceProvider();
                var    sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
                byte[] key    = sha256.ComputeHash(BitConverter.GetBytes(Key));
                byte[] iv     = md5.ComputeHash(BitConverter.GetBytes(Key));
                aes.Key = key;
                aes.IV  = iv;

                byte[] dataByteArray = Encoding.UTF8.GetBytes(SourceStr);
                using (var ms = new System.IO.MemoryStream())
                    using (var cs = new System.Security.Cryptography.CryptoStream(ms, aes.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write))
                    {
                        cs.Write(dataByteArray, 0, dataByteArray.Length);
                        cs.FlushFinalBlock();
                        encrypt = Convert.ToBase64String(ms.ToArray());
                    }
            }
            catch (Exception e)
            {
            }
            return(encrypt);
        }
    public static string Encrypt_Aes(this object value, string aesKey, string aesIV)
    {
        string plainText = value as string;
            byte[] Key = GetBytes(aesKey);
            byte[] IV = GetBytes(aesIV);
            // Check arguments.
            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;
            // Create an AesCryptoServiceProvider object
            // with the specified key and IV.
            using (System.Security.Cryptography.AesCryptoServiceProvider aesAlg = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // 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 encrypted.GetString();
    }
Example #8
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.AesCryptoServiceProvider aes = new System.Security.Cryptography.AesCryptoServiceProvider())
            {
                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);
            }
        }