F# Base64 encode and strict decode
F#
open System
open System.Text
let encode (text: string) =
text |> Encoding.UTF8.GetBytes |> Convert.ToBase64String
let tryDecode (encoded: string) =
try
let bytes = Convert.FromBase64String encoded
let text = Encoding.UTF8.GetString bytes
// round-trip check rejects malformed UTF-8 payloads
if Encoding.UTF8.GetByteCount text = bytes.Length then Ok text
else Error "payload is not valid UTF-8"
with :? FormatException -> Error "payload is not valid Base64"