Crypto.CryptoManager.EncryptAES C# (CSharp) Method

EncryptAES() public method

Encrypts the un-cyphered data as an array of bytes
public EncryptAES ( byte clearPayload, CryptoLevel keysize = CryptoLevel.AES256 ) : byte[]
clearPayload byte The un-ciphered data to be encrypted
keysize CryptoLevel
return byte[]
        public byte[] EncryptAES(byte[] clearPayload, CryptoLevel keysize = CryptoLevel.AES256)
        {
            // if the key strength requested is different from the instance
            if (KeySize != KeySize)
            {
                KeySize = keysize;
                // re-calculate the encryption hash using the encryption level requested
                SetEncryptionLevel(KeySize);
            }

            // Check arguments.
            if (clearPayload == null || clearPayload.Length <= 0)
            {
                throw new ArgumentNullException("clearPayload");
            }
            if (key_array == null || key_array.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }
            if (iv_array == null || iv_array.Length <= 0)
            {
                throw new ArgumentNullException("Key");
            }

            // declare the output object.
            byte[] encrypted;
            // Create an Aes object
            // with the specified key and IV.
            using (Aes aes = Aes.Create())
            {
                aes.Key = key_array;
                aes.IV = iv_array;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;

                // Create a decrytor to perform the 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))
                    {
                        csEncrypt.Write(clearPayload, 0, clearPayload.Length);
                        csEncrypt.FlushFinalBlock();
                        encrypted = msEncrypt.ToArray();
                    }
                    msEncrypt.Close();
                }
            }
            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }

Usage Example

示例#1
0
 public static byte[] SqlEncrypt(string json, int strength)
 {
     CryptoManager crypto = new CryptoManager();
     return crypto.EncryptAES(Encoding.UTF8.GetBytes(json), (CryptoLevel)Convert.ToByte(strength));
 }