Receiving base64 string in web api - web

I am trying to receive a base64 string (which is an image) in my web api web service.
The issue I am having is with the length of the string, is there a way I can set the limit of of incoming strings to allow for a string of a massive size? The string has already been encoded for url use. From what I can tell this is my issue. Right now if I call the function it gives me an 404 error. However if I remove the base64string and put in just a normal string it works.
This is my function
public int userLogin(string identifier, string name, string hometown, string photo)
{
da = new SqlDataAdapter();
ds = new DataSet();
command = new SqlCommand("p_userLogin", connection);
command.Parameters.AddWithValue("#userInfo", identifier);
command.Parameters.AddWithValue("#name", name);
command.Parameters.AddWithValue("#hometown", hometown);
command.Parameters.AddWithValue("#photo", photo);
command.CommandType = CommandType.StoredProcedure;
da.SelectCommand = command;
da.Fill(ds);
int userID = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
return userID;
}
And this is the base 64 string I am trying to send
%2F9j%2F4AAQSkZJRgABAgAAAQABAAD%2F%2FgAEKgD%2F4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNtcwIQAABtbnRyUkdCIFhZWiAH3AABABkAAwApADlhY3NwQVBQTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9tYAAQAAAADTLWxjbXMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAApkZXNjAAAA%2FAAAAF5jcHJ0AAABXAAAAAt3dHB0AAABaAAAABRia3B0AAABfAAAABRyWFlaAAABkAAAABRnWFlaAAABpAAAABRiWFlaAAABuAAAABRyVFJDAAABzAAAAEBnVFJDAAABzAAAAEBiVFJDAAABzAAAAEBkZXNjAAAAAAAAAANjMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB0ZXh0AAAAAEZCAABYWVogAAAAAAAA9tYAAQAAAADTLVhZWiAAAAAAAAADFgAAAzMAAAKkWFlaIAAAAAAAAG%2BiAAA49QAAA5BYWVogAA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aEQEAAwEBAQAAAAAAAAAAAAABABEhEDEg%2F9oACAECEQE%2FEIPAUuBY%2BKjAXA0imzXztyoRE7MjwdTJdTJMqIOS%2Bf%2FEACARAAIABQUBAAAAAAAAAAAAAAABEBEhMeEgcZGh8EH%2F2gAIAQERAT8QiwRp1hKLsOqYregkJ%2FsCnMbIlBeeQ6bd4HMt7gSlt3g294Ni5wf%2FxAAnEAEAAgIABgICAgMAAAAAAAABABEhMUFRYXGBkRDwIKGxwdHh8f%2FaAAgBAAABPxD8bHBvyAtgSxubWaeyjq3OWmhRcWa5BGuE702QdPYj5fh%2BWLBlL3GAokoQq7dXgYYJuyUWKCqNrMBct19ib7rYxnGmY9RPIjrFx7qNJlNYUH8x%2FB3OmW8%2FjJkUoBss3jSnmAoWwqwwvHHq6hStcYl5NWiZyjeWGrZBwArVeX3DtqbgEUuQIPEflgkW35Ciyo7Zf1cIFq8yPv8AzGvE029aczugohlJgKoQa78%2FEfik06SiWQbYMy7BGLHsHL4gMPQBHKEsC1PEqUcDUxvtcBUBzdDnAkkL4UwK4bOJu%2Be%2Fhm0Uxt5VHo3t5%2B2IQxVlnJLe4J1imuUmbyK8C%2BssiZbu8VuFIDhX79QPiMEE2tf8QNTVZsL61sHKznGcZ7JWSigchks6B6VCjzgL6NBh8RtB77jjuODlgMIAlDSf1cGoiTwUbXGsNrdpqgAKcRoBCmkrYDTV3DM1O5T2Fd25g4SuNI9OxqACkmq5A4jCbarwqbiXHdl%2Fo8RcALYRTkcwgTUNq9x3BYURVZikFM1dPgiGZ1v%2FAHxRft94XAh3ojx6zGRwwGliiTcA5LTESZAtbwDiXeAq%2FwC8QFpj75gF%2Bn5hS%2Bn5n%2F%2FZ
Any input on this would be appreciated.

I don't know whether you got the answer or not, because question had posted long time back.
I also faced same problem,resolved my issue using
below link may help you to find the answer #Ken
ASP.NET Web API does not allow Lengthy base64 URI

Related

Error trying to attach an image to an Azure DevOps wiki page

I have successfully used the Azure DevOps API to create multiple wiki pages, via a standalone C# desktop app. Now I'm trying to attach an image (currently stored locally) to the wiki (as per https://learn.microsoft.com/en-us/rest/api/azure/devops/wiki/attachments/create?view=azure-devops-rest-6.0), but get an error
The wiki attachment creation failed with message : 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.
This is the code that I use to read the image file and convert it to a Base64 string - is this correct?
string base64String = null;
string img = File.ReadAllText(att.Value);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(img);
base64String= Convert.ToBase64String(byteCredentials);
Then I create the "content" for the API call as
string data = #"{""content"": """ + base64String + #"""}";
and run the API call
string url = "https://dev.azure.com/{organization}/{project}/_apis/wiki/wikis/{wikiIdentifier}/attachments?name=Image.png&api-version=6.0";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.ContentType = "application/octet-stream";
request.Method = "PUT";
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", "AzurePAT"))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Can anyone see anything wrong with any of this? The concept of setting up a "content" JSON with an encoded Base64 string doesn't seem to be documented, so have I done it correctly?
Any help or advice gladly appreciated, thanks
An image file does not contain text, it is a binary file, calling File.ReadAllText probably messes up the encoding. Try:
var img = File.ReadAllBytes(att.Value);
var base64String = Convert.ToBase64String(img);
In addition, the request expects the body to just be a string. You are passing JSON. Your code should look like this:
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(base64String);
}

Validate webhook request using HMAC security with REST API

I am using DocusSign connect webhook service and want to use HMAC Security to validate the request. To do this I have followed the instructions mentioned in
https://developers.docusign.com/esign-rest-api/guides/connect-hmac that is:
On our account on DocuSign, I have set for Connect the Include HMAC Signature and created a Connect Authentication Key.
Received the Connect message from Docusign connect containing the header with the data hashed with the application’s defined HMAC keys.
But facing the issue in 3rd step i.e. validating the HMAC signature using below code -
// x-docusign-signature headers
String headerSign = request.getHeader("X-DocuSign-Signature-1");
String secret = "....";
-------
public static boolean HashIsValid(String secret, String payload,
String headerSign)
throws InvalidKeyException, NoSuchAlgorithmException,
UnsupportedEncodingException {
String computedHash = ComputeHash(secret, payload);
boolean isEqual =
MessageDigest.isEqual(computedHash.getBytes("UTF-8"),
headerSign.getBytes("UTF-8"));
return isEqual;
}
------
public static String ComputeHash(String secret, String payload)
throws InvalidKeyException, NoSuchAlgorithmException {
String digest = "HmacSHA256";
Mac mac = Mac.getInstance(digest);
mac.init(new SecretKeySpec(secret.getBytes(), digest));
String base64Hash = new String(
Base64.getEncoder().encode(mac.doFinal(payload.getBytes())));
return base64Hash;
}
But it always returns false.
Anyone who has any idea why my hash code is different from the one received from DocuSign?
Either your comparison test is wrong or your payload variable is including too much or too little.
To test your comparison, print out computedHash and headerSign.
To test your payload value, print it out and check that it is the entire body of the POST request to your listener (your server).
Also check that you have exactly one X-DocuSign-Signature header. One way is to confirm that there is no value for header X-DocuSign-Signature-2
I've filed internal bug report DEVDOCS-4874 since the Java example has a bug.

How to change 'new String(Base64.encodeBase64("ABCD".getBytes())); (java)' into Node.js?

In Java, I have below code
String plainCredentials = "ABCD";
String base64Credentials = new String(Base64.encodeBase64(plainCredentials.getBytes()));
I'd like to change it into Node.js
This is how I am trying
var authentication = new Buffer.from("ABCD");
base64Credentials = authentication.toString('base64');
But the result is coming wrong.
How can I change the above Java code into Node.js code ?
Well I think, below code should give you the correct result (Its the same one as yours just one liner).
const base64Credentials = Buffer.from('ABCD').toString('base64');
Output: QUJDRA==
If not then please edit your question and post the string which you are getting in your java program.

What is the correct way to encode SAML request to the Azure AD endpoint?

I am using the following code to encode the SAMLRequest value to the endpoint, i.e. the XYZ when calling https://login.microsoftonline.com/common/saml2?SAMLRequest=XYZ.
Is this the correct way to encode it?
private static string DeflateEncode(string val)
{
var memoryStream = new MemoryStream();
using (var writer = new StreamWriter(new DeflateStream(memoryStream, CompressionMode.Compress, true), new UTF8Encoding(false)))
{
writer.Write(val);
writer.Close();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length, Base64FormattingOptions.None);
}
}
If you just want to convert string to a base64 encoded string, then you can use the following way:
var encoded = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(val));
Console.WriteLine(encoded);
return encoded;
Yes, that looks correct for the Http Redirect binding.
But don't do this yourself unless you really know what you are doing. Sending the AuthnRequest is the simple part. Correctly validating the received response, including guarding for Xml signature wrapping attacks is hard. Use an existing library, there are both commercial and open source libraries available.

convert byte[] to string with charset Encoding in C#

I'm new to Windows phone 8 Dev and C#. I try to get String from remote server. This is my code:
var client = new HttpClient();
var response = await client.GetAsync(MyUrl);
string charset = GetCharset(response.Content.Headers.ContentType.ToString());
Debug.WriteLine("charset: " + charset); \\debug show: charset: ISO-8859-1
var bytesCharset = await response.Content.ReadAsByteArrayAsync();
Debug.WriteLine(Encoding.UTF8.GetString(bytesCharset,0,bytesCharset.Length));
//Debug show: `m\u1EF9 t�m`
m\u1EF9 t�m is what I got, but I expect it's Vietnamese: Mỹ Tâm. Can anyone give me an idea to get expected result? (I think the bytes is encoded in IOS-8859-1).
Encoding.UTF8 should be interpreting your data correctly, as ISO-8859-1 is a subset of UTF-8. However, so that other encodings are handled transparently, it is probably better to use HttpContent's ReadAsStringAsync() method instead of ReadAsByteArrayAsync().
I suspect you have the correct string there but your debug window simply cannot display those two unicode characters properly.
You can use the static GetEncoding method to request a specificy codepage.
e.g.:
var encoding = Encoding.GetEncoding("ISO-8859-1");
Finally I found the solution. After using Json.Net to parse json from remote server, my problem's gone, and I can get expected result:
JArray jArray = JArray.Parse(isoText);
String exptectedText= jArray[1].ToString();
Actually, I dont know why my code works :( Thank you anyway!

Resources