Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I base64 encode using Fable (F#)?

Tags:

I use FetchAPI of Fable.PowerPack to make basic authentication application, but I am in trouble because I can not base64 encode.

For example, I wrote such a code,

let base64enc str =
    str
    |> Seq.map byte
    |> Array.ofSeq
    |> System.Convert.ToBase64String

However, the following error occurs.

Error FABLE: Can not find replacement for System.Convert.ToBase64String

Is there any way?

like image 776
Kenji Tokudome Avatar asked May 05 '17 15:05

Kenji Tokudome


People also ask

What is Base64 encoding of a string?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

How do I use Base64 decode?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.

What is Base64 encoded key?

Base64 is purely encoding; you can not use base64 to encrypt or decrypt because encryption by definition is encoding with a secret key, and since you can not use a key with base64, it cannot be encryption of any kind. Base64 is encoding, which is used to transform the data to a new type that anyone can reverse.


1 Answers

I think the JavaScript btoa function does what you need. The easiest and quickest way to make it available in Fable is to use the Emit attribute:

[<Emit("btoa($0)")>]
let toBase64String (bytes:byte[]) : string = failwith "JS"

There might be some slight differences between the .NET method and the JS function, in which case you'll probably need to reimplement those on your own.

Also, this sounds like a thing that Fable could support - the replacements for .NET operations are generally defined in the Replacements.fs file and if you were interested in sending a pull request to add mapping for ToBase64String and others, that would be amazing!

like image 101
Tomas Petricek Avatar answered Sep 24 '22 11:09

Tomas Petricek