Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <summary>
- /// Encrypt a byte array using AES 128
- /// </summary>
- /// <param name="key">128 bit key</param>
- /// <param name="secret">byte array that need to be encrypted</param>
- /// <returns>Encrypted array</returns>
- public static byte[] EncryptByteArray(byte[] key, byte[] secret)
- {
- using (MemoryStream ms = new MemoryStream())
- using (AesManaged cryptor = new AesManaged())
- {
- cryptor.Mode = CipherMode.CBC;
- cryptor.Padding = PaddingMode.PKCS7;
- cryptor.KeySize = 128;
- cryptor.BlockSize = 128;
- //We use the random generated iv created by AesManaged
- byte[] iv = cryptor.IV;
- using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateEncryptor(key, iv), CryptoStreamMode.Write))
- {
- cs.Write(secret, 0, secret.Length);
- }
- byte[] encryptedContent = ms.ToArray();
- //Create new byte array that should contain both unencrypted iv and encrypted data
- byte[] result = new byte[iv.Length + encryptedContent.Length];
- //copy our 2 array into one
- System.Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
- System.Buffer.BlockCopy(encryptedContent, 0, result, iv.Length, encryptedContent.Length);
- return result;
- }
- }
- /// <summary>
- /// Decrypt a byte array using AES 128
- /// </summary>
- /// <param name="key">key in bytes</param>
- /// <param name="secret">the encrypted bytes</param>
- /// <returns>decrypted bytes</returns>
- public static byte[] DecryptByteArray(byte[] key, byte[] secret)
- {
- byte[] iv = new byte[16]; //initial vector is 16 bytes
- byte[] encryptedContent = new byte[secret.Length - 16]; //the rest should be encryptedcontent
- //Copy data to byte array
- System.Buffer.BlockCopy(secret, 0, iv, 0, iv.Length);
- System.Buffer.BlockCopy(secret, iv.Length, encryptedContent, 0, encryptedContent.Length);
- using (MemoryStream ms = new MemoryStream())
- using (AesManaged cryptor = new AesManaged())
- {
- cryptor.Mode = CipherMode.CBC;
- cryptor.Padding = PaddingMode.None;
- cryptor.KeySize = 128;
- cryptor.BlockSize = 128;
- using (CryptoStream cs = new CryptoStream(ms, cryptor.CreateDecryptor(key, iv), CryptoStreamMode.Write))
- {
- cs.Write(encryptedContent, 0, encryptedContent.Length);
- }
- return ms.ToArray();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement