0 Replies - 1073 Views - Last Post: 15 April 2010 - 12:54 AM

#1 Skaggles  Icon User is offline

  • THE PEN IS MIGHTIER
  • member icon





Reputation: 255
  • View blog
  • Posts: 641
  • Joined: 01-March 09

AES Encryption with F#

Posted 15 April 2010 - 12:54 AM

Description: A little conversion to F# I did of the code that was used by Smurphy's AES Encryption with C# tutorial.Encrypt/Decrypt a string in F# using the .NET AES Encryption tools.
open System
open System.IO
open System.Text
open System.Security.Cryptography

let encoding = ASCIIEncoding ()

// AES Encryption ////
let Encrypt (text : string) (key : byte[]) (IV : byte[]) =
    let textBytes = encoding.GetBytes (text)

    let crypt = RijndaelManaged.Create ()
    crypt.Key <- key
    crypt.IV <- IV

    let encryptor = crypt.CreateEncryptor (crypt.Key, crypt.IV)

    let mstream = new MemoryStream ()

    let cstream = new CryptoStream (mstream, encryptor, CryptoStreamMode.Write)
    cstream.Write (textBytes, 0, textBytes.Length)
    cstream.Close ()

    mstream.Close ()
    mstream.ToArray () // return an array of encrypted bytes

// AES Decryption ////
let Decrypt (text : byte[]) (key : byte[]) (IV : byte[]) =
    let crypt = RijndaelManaged.Create ()
    crypt.Key <- key
    crypt.IV <- IV

    let decryptor = crypt.CreateDecryptor (crypt.Key, crypt.IV)

    let mstream = new MemoryStream (text)
    let cstream = new CryptoStream (mstream, decryptor, CryptoStreamMode.Read)
    let reader = new StreamReader (cstream)
    let txt = reader.ReadToEnd ()

    cstream.Close ()
    mstream.Flush ()
    mstream.Close ()

    txt // return the plain text string after decryption

// Example Use ////
let crypto = RijndaelManaged.Create ()

let plainString =
    Console.Write "Enter a string to encrypt: "
    Console.ReadLine ()

Console.WriteLine ("nEncrypting: {0}", plainString)

// encrypt a string and covnert the encrypted bytes into a string
let encryptedBytes = Encrypt plainString crypto.Key crypto.IV
let encryptedString = encoding.GetString (encryptedBytes)
Console.WriteLine ("Encrypted: {0}", encryptedString)

// decrypt the encrypted bytes
let decryptedString = Decrypt encryptedBytes crypto.Key crypto.IV
Console.WriteLine ("Decrypted: {0}", decryptedString)

// just wait for keypress before quitting
let pauseBeforeQuit =
    Console.Write "nPress any key to continue..."
    Console.ReadKey ()


Is This A Good Question/Topic? 0
  • +

Page 1 of 1