Implement AES encryption in F # (as per MSDN C # example)

I may have a stupid question, but I can't get it to work. I am doing AES encryption / decryption in F # according to the MSDN example which is in C #:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.aes.aspx

My encryption method is as follows:

let EncryptStringToBytesAes (plainText : string) (key : byte[]) (iv : byte[]) = use aesAlg = Aes.Create() aesAlg.Key <- key aesAlg.IV <- iv // Create a decrytor to perform the stream transform. let encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV) // Create the streams used for encryption. use msEncrypt = new MemoryStream() use csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) use swEncrypt = new StreamWriter(csEncrypt) swEncrypt.Write(plainText) msEncrypt.ToArray() 

The problem is that this method always returns me an empty byte array. I have no exception. The key and IV are the correct byte arrays. It seems that StreamWriter is not working ...

Thank you for your help.

+4
source share
3 answers

To do this, we need to explicitly close StreamWriter and CryptoStream

-2
source

Before you call msEncrypt.ToArray , you must clear all intermediate threads or close them, as they buffer the data.

+2
source

Based on @usr answer ...

The easiest way to make sure the stream is closed is to place the use statements in a block that goes out of scope before the ToArray is ToArray .

 let EncryptStringToBytesAes (plainText : string) (key : byte[]) (iv : byte[]) = use aesAlg = Aes.Create() aesAlg.Key <- key aesAlg.IV <- iv // Create a decrytor to perform the stream transform. let encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV) // Create the streams used for encryption. use msEncrypt = new MemoryStream() ( use csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write) use swEncrypt = new StreamWriter(csEncrypt) swEncrypt.Write(plainText) ) msEncrypt.ToArray() 
+2
source

Source: https://habr.com/ru/post/1500718/