Decoding Android Base64 URL SAFE and NO WRAP in C# - c#

I have an Android App which uses a C# web service.
Now i need to send some data from the app to the web service.
I want to do this with a Base64, but to let it work, i have to
use Base64.URL_SAFE|Base64.NO_WRAP, or else the web service won't be called.
So in my Android Code i do:
String dataToSend = "Some text"
byte[] data = dataToSend.getBytes();
Base64.encodeToString((data), Base64.URL_SAFE|Base64.NO_WRAP);
This works okay, but the problem is that i can't decode it in C#. In the web service
i do:
String data; // received data from Android
byte[] output = Convert.FromBase64String(data);
But if i run the code i get an error in C#:
System.FormatException{"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters"}
I know it's because of the URL Safe and No Wrap, but i need it to send the data.
Is there a way to convert the data to a default Base64 String in C#? Or do i have replace/strip some things in the received Base64 String?

Related

In C#, how to convert the javascript's base64 string into a file

In angular, I am making a form like this,
form = this.fb.group({
product_Id: [0]
product_Name: [''],
product_Image: ['']
})
Now I want to pass the product image in base64 string. So I have converted it using below,
fileSelected(files: FileList)
{
let file = <File>files[0]
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onloadend = () => {
this.form.get('product_Image').setValue(reader.result)
}
}
On asp.net core side, I have implemented below logic,
var path = Directory.GetCurrentDirectory() + "wwwroot\\Product\\test.jpg";
await File.WriteAllBytesAsync(path, Convert.FromBase64String(vm.Product_Image));
Now the asp.net core is giving me error: "The given format is not a valid base 64 string"
PS: I have also reader.readAsBinaryString(file) but the error is the same.
The Error: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
I don't know what wrong?
As per the MDN page for readAsDataURL, you must remove the URI part before decoding. I quote:
Note: The blob's result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:*/*;base64, from the result.
try remove "data:image/jpeg;base64," from vm.Product_Image string before
await File.WriteAllBytesAsync(path, Convert.FromBase64String(vm.Product_Image));
Sample base 64string as below
/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKC...

SendGrid inbound parse nordic chars

Completely stuck on a problem related to the inbound parse webhook functionality offered by SendGrid: https://sendgrid.com/docs/for-developers/parsing-email/setting-up-the-inbound-parse-webhook/
First off everything is working just fine with retrieving the mail sent to my application endpoint. Using Request.Form I'm able to retrieve the data and work with it.
The problem is that we started noticing question mark symbols instead of letters when recieving some mails (written in swedish using Å Ä and Ö). This occured both when sending plaintext mails, and mails with an HTML-body.
However, this only happens every now and then. After a lot of searching I found out that if the mail is sent from e.g. Postbox or Outlook (or the like), and the application has the charset set to iso-8859-1 that's when Å Ä Ö is replaced by question marks.
To replicate the error and be able to debug it I set up a HTML page with a form using the iso-8859-1 encoding, sending a similar payload as the one seen in the link above (the default one). And after that been through testing a multitude of things trying to get it to work.
As of now I'm trying to recode the input, without success. Code I'm testing:
Encoding wind1252 = Encoding.GetEncoding(1252);
Encoding utf8 = Encoding.UTF8;
byte[] wind1252Bytes = wind1252.GetBytes(Request.Form.["html"]);
byte[] utf8Bytes = Encoding.Convert(wind1252, utf8,wind1252Bytes);
string utf8String = Encoding.UTF8.GetString(utf8Bytes);
This only results in the utf8String producing the same result with "???" where Å Ä Ö should be. My guess here is that perhaps it's due to the Request.Form["html"] returning a UTF-16 string, of the content that is encoded already in the wrong encoding iso-8859-1.
The method for fetching the POST is as follows
public async Task<InboundParseModel> FetchMail(IFormCollection form)
{
InboundParseModel _em = new InboundParseModel
{
To = form["to"].SingleOrDefault(),
From = form["from"].SingleOrDefault(),
Subject = form["subject"].SingleOrDefault(),
Html = form["html"].SingleOrDefault(),
Text = System.Net.WebUtility.HtmlEncode(form["text"].SingleOrDefault()),
Envelope = form["envelope"].SingleOrDefault()
};
}
Called from another method that the POST is done to by FetchMail(Request.Form);
Project info: ASP.NET Core 2.2, C#
So as stated earlier, I am completely stuck and don't really have any ideas on how to solve this. Any help would be much appreciated!

How to send an SMS in Urdu language using third party API from a C# application?

I have an application which is developed using C#. I am using a third party API (Telnore Corporate SMS) for sending SMS to users. When I write my message in English (I am using a textbox for writing SMS) then the message delivered to mobile is fine and readable. But when I use the Urdu language instead, then it becomes something unreadable:
I consulted multiple tutorials and techniques of UTF-8 encoding, etc., but when I used the UTF-8 encoding the delivered message still wasn't readable (everything turned to question marks in this case).
This is what I have tried so far.
string s = themessage.Text;//themessage is my textbox name
//utf8
byte[] utf = System.Text.Encoding.UTF8.GetBytes(s);
string s2 = System.Text.Encoding.UTF8.GetString(utf);
//ASCII
byte[] utf = System.Text.Encoding.ASCII.GetBytes(s);
string s2 = System.Text.Encoding.ASCII.GetString(utf);
//Unicode
byte[] utf = System.Text.Encoding.Unicode.GetBytes(s);
string s2 = System.Text.Encoding.Unicode.GetString(utf);
I don't know what I am doing wrong. After getting the string s2 I am passing it to a method that is sending the message.

Send UTF-8 string from Android to C#

I've been trying to accomplish a simple text transmission from my Android app to my C# server (asmx server), sending the simplest string - and for some reason it never works. My Android code is as following (assume that the variable 'message' holds the string as received from an EditText, which is UTF-16 as far as I'm concerned):
httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(POST_MESSAGE_ADDRESS);
byte[] messageBytes = message.getBytes("utf-8");
builder.addPart("message", new StringBody(messageBytes.toString()));
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
So I get something simple for my message, say a 10 bytes array. In my server, I have a function set to that specific address; its code is:
string message = HttpContext.Current.Request.Form["message"];
byte[] test = System.Text.Encoding.UTF8.GetBytes(message);
Now after that line the byte array ('test') has the exact same value as the result of the ToString() function I called in the app. Question is, how do I convert it to normal UTF-8 text to display?
Note: I have tried sending the string normally as a string content, but as far as I understood the default coding is ASCII so I got a lot of question marks.
Edit: Now I'm looking for some conversions solutions and trying them, but my question is also if there's a simpler way to do that (perhaps BinaryBody in the android, or different coding?)
Problem is in following lines:
byte[] messageBytes = message.getBytes("utf-8");
builder.addPart("message", new StringBody(messageBytes.toString()));
First you are transforming your UTF-16 string message into UTF-8 encoded messageBytes only to convert them back to UTF-16 string in next line. And there you are using StringBody constructor that will use ASCII encoding as default.
You should replace those lines with:
builder.addPart("message", new StringBody(message, Charset.forName("UTF-8")));

Sending quotation marks in a GCM Payload (and other special characters that break syntax)

I'm struggling finding a feasible solution to this. I've tried looking around but can't find any documentation regarding this issue. If a customer sends out a message with quote(s), it break the payload syntax and android spits me back a 400 Bad Request error.
The only solution I can think of is by doing my own translations and validations. Allow only the basics, and for the restricted do my own "parsing" Ie take a quote, replace them with "/q" and then replace "/q" on the App when received. I don't like this solution because it involves logic on the App that if, I forget something. I want to be able to change it immediately rather then update everyones phone, app, etc.
I'm looking for an existing encoding I could apply that is processed correctly by the GCM servers. Allowing them to be accepted then broadcasted. Received by the phone with the characters intact.
Base64 encoding should get rid of the special characters. Just encode it before sending and decode it again on receiving:
Edit: sorry, just got a java/android sample here, I don't know how exactly xamarin works and what functions it provides:
// before sending
byte[] data = message.getBytes("UTF-8");
String base64Message = Base64.encodeToString(data, Base64.DEFAULT);
// on receiving
byte[] data = Base64.decode(base64Message , Base64.DEFAULT);
String message= new String(data, "UTF-8");
.Net translation of #tknell solution
Decode:
Byte[] data = System.Convert.FromBase64String(encodedString);
String decoded = System.Text.Encoding.UTF8.GetString(data);
Encode:
Byte[] data = System.Text.Encoding.UTF8.GetBytes(decodedString);
String encoded = System.Convert.ToBase64String(data);

Categories