locked
Windows.Security.Cryptography - Base64 Decode File RRS feed

  • Question

  • I got a piece of code which reads the files bytes, although it's slow, I want to decode a file which has been base64 encoded....

    I see methods for Windows.Security.Cryptography but what's the best way to read a file & base64 decode the data...then pass the decoded data to a richeditbox for editing...it should only basically include tabs, spaces & actual letters when decoded...

    Then I need to pass the text that's in the RichEditBox to be encoded & saved to file again...

    Here is the code that I can use to read the raw byte info & get a basic file length, although it's slow...

        Private Async Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
            Dim a As New Windows.Storage.Pickers.FileOpenPicker
            a.FileTypeFilter.Add(".sav")
            Dim b As Windows.Storage.StorageFile = Await a.PickSingleFileAsync()
            If Not b Is Nothing Then
                Dim c As New Windows.Storage.Streams.DataReader(Await b.OpenReadAsync)
                Dim d As Integer = c.UnconsumedBufferLength
                Do
                    Await c.LoadAsync(1)
                    If c.UnconsumedBufferLength = d Then
                        Exit Do
                    Else
                        d = c.UnconsumedBufferLength
                    End If
                Loop
                Dim f As New Windows.UI.Popups.MessageDialog(c.UnconsumedBufferLength.ToString)
                Await f.ShowAsync()
            End If
        End Sub

    What's the best way to read an encoded file to be un-encoded using the base64 method & display the result...?

    I still have yet to successfully display it like notepad does but it shows somewhat similar at least now...if I instead use that code to display the data...

    Wednesday, April 4, 2012 6:22 PM

Answers

  • This is something I whipped up this afternoon:

            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                LoadFile();
            }
    
            private async void LoadFile()
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.List;
                openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                openPicker.FileTypeFilter.Add(".b64");
                StorageFile MyEncodedFile = await openPicker.PickSingleFileAsync();
                if (null != MyEncodedFile)
                {
                    // Application now has read/write access to the picked file
                    MyFileName.Text = "Decoded output for " + MyEncodedFile.Name;
                }
                else
                {
                    MyFileName.Text = "File was not returned";
                    return;
                }
                string MyEncodedText = await Windows.Storage.FileIO.ReadTextAsync(MyEncodedFile);
                Before.Text = MyEncodedText;
                IBuffer MyBuffer = CryptographicBuffer.DecodeFromBase64String(MyEncodedText);
                Byte[] MyBytes;
                CryptographicBuffer.CopyToByteArray(MyBuffer, out MyBytes);
                After.Text = System.Text.UTF8Encoding.UTF8.GetString(MyBytes,0,MyBytes.Length);
            }
     <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
            <StackPanel HorizontalAlignment="Left">
                <TextBlock Margin="0 0 0 0" FontSize="25" >Base-64 Decryption:</TextBlock>
                <Button Click="Button_Click_1">Choose File</Button> 
                <TextBlock Margin="0 20 0 0" FontSize="15" x:Name="MyFileName">Decoded output for </TextBlock>
                <StackPanel Orientation="Horizontal"> 
                   <TextBox x:Name="Before" Height="500" Width="400" AcceptsReturn="True" Margin="3 0 10 0" TextWrapping="Wrap"></TextBox>
                    <TextBox x:Name="After" Height="500" Width="400" AcceptsReturn="True" Margin="0 0 0 0" TextWrapping="Wrap"></TextBox>
                </StackPanel>
            </StackPanel>
        </Grid>

    I'm not sure if the encoding is absolutely correct but it worked.

    Base-64 text for the .b64 file:

    SGVsbG8sIHRoaXMgaXMgYSBiYXNlLTY0IGVuY29kZWQgc3RyaW5nLg==



    Matt Small - Microsoft Escalation Engineer - Forum Moderator


    Friday, April 6, 2012 7:46 PM
    Moderator
  • .b64 files are simply text files with base 64-encoded text - I created that extension myself just for this test.  I created the base-64-encoded text using an online converter - there are tons of them on the internet.  Paste your encoded info here and I'll see if it will decode.

    I specifically didn't paste the imported libraries, just the essential code.  Here it is if you still need it.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.Storage.Pickers;
    using Windows.Storage.FileProperties;
    using Windows.Storage;
    using Windows.Security.Cryptography;
    using Windows.Storage.Streams;



    Matt Small - Microsoft Escalation Engineer - Forum Moderator

    • Marked as answer by Maya Key Friday, April 6, 2012 9:35 PM
    Friday, April 6, 2012 9:26 PM
    Moderator
  • I didn't still need it, edited my post a lot, my base64 encoded text must have some different encoding put upon it after base64 or a little bit of custom info along with the base64 encoded data because even in a new c# project with your code it doesn't decode...

    Here's the code for VB that I came up with though...it doesn't work with my data which was encoded with my desktop app & i'll have to see why it's storing data different...

    I guess I need to try to figure out how to save the data that will be changed in my RichEditBox now though & encoded by base64 before being saved...

        Private Async Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
            Dim a As New Windows.Storage.Pickers.FileOpenPicker
            a.FileTypeFilter.Add(".txt")
            Dim b As Windows.Storage.StorageFile = Await a.PickSingleFileAsync()
            If b IsNot Nothing Then
                Dim c As Windows.Storage.Streams.IBuffer = Windows.Security.Cryptography.CryptographicBuffer.DecodeFromBase64String(Await Windows.Storage.FileIO.ReadTextAsync(b))
                Dim d() As Byte
                Windows.Security.Cryptography.CryptographicBuffer.CopyToByteArray(c, d)
                RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, System.Text.UTF8Encoding.UTF8.GetString(d, 0, d.Length))
            End If
        End Sub

    • Marked as answer by Maya Key Friday, April 6, 2012 9:35 PM
    Friday, April 6, 2012 9:32 PM

All replies

  • CryptographicBuffer.DecodeFromBase64String.

    http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.cryptographicbuffer.decodefrombase64string.aspx

    Sample at the bottom of the page.


    Matt Small - Microsoft Escalation Engineer - Forum Moderator

    Thursday, April 5, 2012 6:13 PM
    Moderator
  • I know how it's used & what to use, but the question is, how do I read a file & pass it to be decoded & display the result in my RichEditBox?

    It seems that you need to pass the files data(as a string) to be decoded & then you get some type of stream back or whatever that then needs converted back to text so that RichEditBox.Document.SetText() can be used to display the result...

    I am having trouble reading the file in to a string for passing to DecodeFromBase64String() & then getting the result, seemingly as a string, back to a string to be displayed....

    ---Can something more involved than pointing to documentation of a function I know that I should already use but just don't know how to pass it the data from the file & how to get the result from it to show up decoded in my RichEditBox...

    Thursday, April 5, 2012 7:06 PM
  • This is something I whipped up this afternoon:

            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                LoadFile();
            }
    
            private async void LoadFile()
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.List;
                openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                openPicker.FileTypeFilter.Add(".b64");
                StorageFile MyEncodedFile = await openPicker.PickSingleFileAsync();
                if (null != MyEncodedFile)
                {
                    // Application now has read/write access to the picked file
                    MyFileName.Text = "Decoded output for " + MyEncodedFile.Name;
                }
                else
                {
                    MyFileName.Text = "File was not returned";
                    return;
                }
                string MyEncodedText = await Windows.Storage.FileIO.ReadTextAsync(MyEncodedFile);
                Before.Text = MyEncodedText;
                IBuffer MyBuffer = CryptographicBuffer.DecodeFromBase64String(MyEncodedText);
                Byte[] MyBytes;
                CryptographicBuffer.CopyToByteArray(MyBuffer, out MyBytes);
                After.Text = System.Text.UTF8Encoding.UTF8.GetString(MyBytes,0,MyBytes.Length);
            }
     <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
            <StackPanel HorizontalAlignment="Left">
                <TextBlock Margin="0 0 0 0" FontSize="25" >Base-64 Decryption:</TextBlock>
                <Button Click="Button_Click_1">Choose File</Button> 
                <TextBlock Margin="0 20 0 0" FontSize="15" x:Name="MyFileName">Decoded output for </TextBlock>
                <StackPanel Orientation="Horizontal"> 
                   <TextBox x:Name="Before" Height="500" Width="400" AcceptsReturn="True" Margin="3 0 10 0" TextWrapping="Wrap"></TextBox>
                    <TextBox x:Name="After" Height="500" Width="400" AcceptsReturn="True" Margin="0 0 0 0" TextWrapping="Wrap"></TextBox>
                </StackPanel>
            </StackPanel>
        </Grid>

    I'm not sure if the encoding is absolutely correct but it worked.

    Base-64 text for the .b64 file:

    SGVsbG8sIHRoaXMgaXMgYSBiYXNlLTY0IGVuY29kZWQgc3RyaW5nLg==



    Matt Small - Microsoft Escalation Engineer - Forum Moderator


    Friday, April 6, 2012 7:46 PM
    Moderator
  • I guess I will use an online converter or convert it by hand because I use vb, forgot to mention that...but I thank you for writing this up so I will understand how to do it, my main trouble was getting the data types to the types needed to pass to each function & the data to still be intact...not corrupt or in some of my xamples the data passed said there was no equivalent for that binary value as string or whatever...had problems in general...

    Well my code shown was in VB but your code in c# it looks like so although it should've been obvious I guess I will still need to convert it...should work out though...I will post the VB version of the code when I do it...

    ---Actually I used code similar to yours although in VB & readalltext has an error, if I put it to bigendian/little-endian it doesn't seem to be a problem so maybe if I pass the result from that it will read, but I wasn't impressed with that because the output to the RichEditBox or TextBox's doesn't look like it does in notepad...also if base64 uses mostly only letters/numbers, and maybe the = sign then it's showing characters which are far different from anything here, and I know for a fact the files are base64 encoded because the desktop app does the encoding using base64 & I made it...so i'm not sure why there's this difference...

    NOTE: It also seems like you forgot to show the imports because FileOpenPicker is bringing up an error... --- In the case of c# the "using" statements, not import statements...

    I went ahead & added it to a c# project to test it, added the proper "using" statements & everything but it is unable to read it because it says there is no Unicode equivalent for the given character(s)… if I change is to utf16le utf16be than it errors & says that it's invalid & wont decode...

    The windows program can decode it still so it's not corrupted but it simply wont decode...maybe it works differently or passed differently in such a way that the output is different?  I have no idea...but it's not working with my files...

    -As a basic question where did you get or create the .b64 files that your de-crypting anyways...?  Another program, one you made, one that you downloaded, one that comes on windows 8?  or one on the windows store?  im just curious how you created it...

    • Edited by Maya Key Friday, April 6, 2012 9:10 PM
    Friday, April 6, 2012 8:46 PM
  • .b64 files are simply text files with base 64-encoded text - I created that extension myself just for this test.  I created the base-64-encoded text using an online converter - there are tons of them on the internet.  Paste your encoded info here and I'll see if it will decode.

    I specifically didn't paste the imported libraries, just the essential code.  Here it is if you still need it.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    using Windows.Storage.Pickers;
    using Windows.Storage.FileProperties;
    using Windows.Storage;
    using Windows.Security.Cryptography;
    using Windows.Storage.Streams;



    Matt Small - Microsoft Escalation Engineer - Forum Moderator

    • Marked as answer by Maya Key Friday, April 6, 2012 9:35 PM
    Friday, April 6, 2012 9:26 PM
    Moderator
  • I didn't still need it, edited my post a lot, my base64 encoded text must have some different encoding put upon it after base64 or a little bit of custom info along with the base64 encoded data because even in a new c# project with your code it doesn't decode...

    Here's the code for VB that I came up with though...it doesn't work with my data which was encoded with my desktop app & i'll have to see why it's storing data different...

    I guess I need to try to figure out how to save the data that will be changed in my RichEditBox now though & encoded by base64 before being saved...

        Private Async Sub Button_Click_1(sender As Object, e As RoutedEventArgs)
            Dim a As New Windows.Storage.Pickers.FileOpenPicker
            a.FileTypeFilter.Add(".txt")
            Dim b As Windows.Storage.StorageFile = Await a.PickSingleFileAsync()
            If b IsNot Nothing Then
                Dim c As Windows.Storage.Streams.IBuffer = Windows.Security.Cryptography.CryptographicBuffer.DecodeFromBase64String(Await Windows.Storage.FileIO.ReadTextAsync(b))
                Dim d() As Byte
                Windows.Security.Cryptography.CryptographicBuffer.CopyToByteArray(c, d)
                RichEditBox1.Document.SetText(Windows.UI.Text.TextSetOptions.None, System.Text.UTF8Encoding.UTF8.GetString(d, 0, d.Length))
            End If
        End Sub

    • Marked as answer by Maya Key Friday, April 6, 2012 9:35 PM
    Friday, April 6, 2012 9:32 PM