Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing AES encryption in F# (according to MSDN C# example)

Probably I have a stupid question, but I am not able to make it working. I am doing the 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 array of bytes. I do not have any exception. Key and IV are proper arrays of bytes. Seems like the StreamWriter is not working...

Thank you for help.

like image 656
user2323704 Avatar asked Sep 05 '13 12:09

user2323704


People also ask

How is AES algorithm implemented?

AES implementation in Java In our class, we will create an init method. This method will create the encryption keys. In this method, using a key generator, we will generate one key. We will get the key generator instance of AES and assign it to keyGenerator .

How do you encrypt using AES?

The AES Encryption algorithm (also known as the Rijndael algorithm) is a symmetric block cipher algorithm with a block/chunk size of 128 bits. It converts these individual blocks using keys of 128, 192, and 256 bits. Once it encrypts these blocks, it joins them together to form the ciphertext.

What are the steps of the AES encryption process?

For encryption, each round consists of the following four steps: 1) Substitute bytes, 2) Shift rows, 3) Mix columns, and 4) Add round key. The last step consists of XORing the output of the previous three steps with four words from the key schedule.


1 Answers

Building on @usr's answer...

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

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()
like image 124
Daniel Avatar answered Oct 12 '22 11:10

Daniel