Skip to content

Instantly share code, notes, and snippets.

@Thorium
Created May 25, 2016 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thorium/5019479d760222baa7aea8f400646ec8 to your computer and use it in GitHub Desktop.
Save Thorium/5019479d760222baa7aea8f400646ec8 to your computer and use it in GitHub Desktop.
Encrypting a Rijndael string, counter part for https://gist.github.com/Thorium/1972253
open System
open System.IO
open System.Security.Cryptography
open System.Text
open System.Diagnostics.Contracts
let EncryptStringWith (plain:string) (key:string) (iv:string) =
let enc = new ASCIIEncoding()
use encrypted = new MemoryStream()
use encode = new ToBase64Transform()
let errdesc = "Failure when encrypting the string: " + plain + "\r\n"
try
use encryptor = Rijndael.Create().CreateEncryptor(enc.GetBytes(key), enc.GetBytes(iv))
use tmpcrypt = new CryptoStream(encrypted, encryptor, CryptoStreamMode.Write)
use encodestream = new CryptoStream(tmpcrypt, encode, CryptoStreamMode.Write)
let encryptedbytes = enc.GetBytes(plain);
encodestream.Write(encryptedbytes, 0, encryptedbytes.Length);
encodestream.Close() // lazy, has to close explicitly before use. use is not enough.
with
| :? CryptographicException as ex -> failwith(errdesc + ex.ToString())
| :? FormatException as ex -> failwith(errdesc + ex.ToString())
encrypted.ToArray() |> Convert.ToBase64String
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment