Created
May 25, 2016 09:06
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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