Help me, throwing exception error in decoding code. help needed - c#

To encode a string
Code:
public string base64Encode(string data)
{
try
{
byte[] encData_byte = new byte[data.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch(Exception e)
{
throw new Exception("Error in base64Encode" + e.Message);
}
}
and to decode
Code:
public string base64Decode(string data)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(data);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
catch(Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}

You haven't said what error you're getting, but surely your second code should simply be:
return Encoding.UTF8.GetString(Convert.FromBase64String(data));
You don't need to create a new UTF8Encoding
You don't need to worry about decoders explicitly
Additionally, your exception handling is nasty - the stack trace would already show where the error occurs, but by catching it and rethrowing just Exception you're hiding the original exception type. Just remove the try/catch blocks from both your methods. (And rename them to match .NET naming conventions.)
Basically, your code can look as simple as this:
public static string Base64AndUtf8Encode(string text)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(text));
}
public static string Base64AndUtf8Decode(string base64)
{
return Encoding.UTF8.GetString(Convert.FromBase64String(base64));
}
Obviously you can split it into separate statements if you want, but it can stil be pretty short:
public static string Base64AndUtf8Encode(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
return Convert.ToBase64String(bytes);
}
public static string Base64AndUtf8Decode(string base64)
{
bytes[] bytes = Convert.FromBase64String(base64);
return Encoding.UTF8.GetString(bytes);
}

Related

Convert Base64 string to image and save it

I want to save base64 image to a folder in application, but I have a problem in code. it gives an error as below,
Message = "Invalid length for a Base-64 char array or string."
In my code;
public static string UpdateUser(int refuser, string name, string surname,string base64)
{
string result = "FAILED";
var photo = "";
if (base64!=null && base64!="")
{
string mediaPath = Extend.GetXmlConfigParameter("media", "path")+"User\\";
string mediaName = Guid.NewGuid().ToString();
base64 = base64.Replace("data:image/png;base64,", "");
base64 = base64.Replace("data:image/jpg;base64,", "");
base64 = base64.Replace("data:image/gif;base64,", "");
base64 = base64.Replace("data:image/jpeg;base64,", "");
string filePath = mediaPath + mediaName + ".png";
try
{
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
//File.WriteAllBytes(filePath, Convert.FromBase64String(base64));
photo = mediaName + ".png";
}
catch(Exception ex)
{
Logger.LogError(ex.Message, ex.StackTrace);
return result;
}
}
try
{
DataSet ds = Database.GetDataSet(con, Database.CreateSpQuery("mobile_user_update ",
new List<object> {
refuser,
name,
surname,
photo
}));
if (!Database.IsDataSetValid(ds))
return null;
result = Database.GetString(ds.Tables[0].Rows[0]["Result"]);
}
catch (Exception ex)
{
Logger.LogError(ex.Message, ex.StackTrace);
}
return result;
}
when i try to convert to byte array with below step in code
byte[] bytes = Convert.FromBase64String(base64);
I take this error. my example base64 string is
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMEAAAEFCAMAAABtknO4AAABhlBMVEX////oTD3m5uZMS01PTU8AAADy8vIgICA4OzYPM0egoI7/zMnoSzza29o2Nzb6+vpGRUdBQEIwMDGFhYbIycmxsbLp6enoRzfi4uLv7+/nQzLnRTT0//+bmYnV1dXxTj6oqJjAwMAXFxfJQTTnPiyzs7P98vGzOi+9uq7/0s/mIwvW8/T73tw6OjovLS/ZRzndzMl4d3hZWFrmNCIvMy31sKqWlZb/UDsREREAL0dkZGQAITvX5+b84+HbRznNzcOko6TpXVDraF0AFjTle3H0r6k2Pkrwj4b2u7Z/f3/RursAACSsPTPunZftdmspNjbgpJ4jJyHwlIzEYlnRf3lvbG4AITCmt7fhnJbrYVXoGgDszszeeGu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8iK+LXJpLIoMQwvkGrgCkewFoLBJ59p8Q/cxO6JV8KemFIGC9+cbEZTwGNB375JNPP/3Emz795LNfJVPLH2rdkUPiOssI0vVffLaCfUyf/arRWJJB0PrWjUldYqXe/Ww9AADhF6200wGn63c3Oas2VkD22uh+shEAgPDZp4s6PCOB2U+eBt6XFQbJnRYPZqXPQepdbzU/3cw+AfGLLjrXnhJazdLHSQBWUkIt64h+CcZ2pQm7CDz32We//GWunL3597eFRhy8aSz/AjkAAAAcSURBVCAK3ejPABZIn7oIv4rcKgsvG7itpPH/APV4xrQzYxA1AAAAAElFTkSuQmCC
How can I solve this problem.
Thanks in advance.
It looks that you getting this base64 string through url. If so, you should encode it , before it send to the client.
HttpUtility.UrlEncode(base64string)

c# base64 encoding. Invalid length error on decrpytion

I'm trying to decrypt a string which is also base64 encoded, but I am receiving an when I try to decrypt the string.
The error I am receiving is:
{System.FormatException: Invalid length for a Base-64 char array or string.
at this line in the decrypt function below:
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
Encrpyt/Decrypt functions:
//ENCRYPT
public static bool stringEncrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;}
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,provider.CreateEncryptor(PWbytes,PWbytes),CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cs);
sw.Write(inString);
sw.Flush();
cs.FlushFinalBlock();
sw.Flush();
outstring = Convert.ToBase64String(ms.GetBuffer(),0,(int)ms.Length);
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Encrypt : " + ex.Message);
return false;
}
}
//DECRPYT
public static bool stringDecrypt(string inString,ref string outstring)
{
try
{
if(String.IsNullOrEmpty(inString)){return false;};
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(Convert.FromBase64String(inString));
CryptoStream cs = new CryptoStream(ms, provider.CreateDecryptor(PWbytes,PWbytes),CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cs);
outstring = sr.ReadToEnd();
return true;
}
catch(Exception ex)
{
clsCommonBase.AppendToExceptionFile("Decrypt : " + ex.Message);
return false;
}
}
Solved using the simple solution in the following link
How do I encode and decode a base64 string?
Also added some code in the encoding function to ensure the plain text string will be converted to a valid length base64 string.
Code:
public static string Base64Encode(string plainText)
{
//check plain text string and pad if needed
int mod4 = plainText.Length % 4;
if (mod4 > 0)
{
plainText += new string('=', 4 - mod4);
}
//convert to base64 and return
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
//decode base64 and return as string
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}

Validate string as Proper Base64String and Convert to byte[]

I want to validate if an input string is valid Base64 or not. If it's valid then convert into byte[].
I tried the following solutions
RegEx
MemoryStream
Convert.FromBase64String
For example I want to validate if "932rnqia38y2" is a valid Base64 string or not and then convert it to byte[]. This string is not valid Base64 but I'm always getting true or valid in my code.
please let me know if you have any solutions.
Code
//Regex _rx = new Regex(#"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]==)?$", RegexOptions.Compiled);
Regex _rx = new Regex(#"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$", RegexOptions.Compiled);
if (image == null) return null;
if ((image.Length % 4 == 0) && _rx.IsMatch(image))
{
try
{
//MemoryStream stream = new MemoryStream(Convert.FromBase64String(image));
return Convert.FromBase64String(image);
}
catch (FormatException)
{
return null;
}
}
Just create some helper, which will catch FormatException on input string:
public static bool TryGetFromBase64String(string input, out byte[] output)
{
output = null;
try
{
output = Convert.FromBase64String(input);
return true;
}
catch (FormatException)
{
return false;
}
}

HttpListener how to serve images

I'm making a simple webserver to serve html, css, js & images (done in c#). I am using HttpListener and I can get the html, javascript and css files to work properly. I am just having trouble with the images. This is what I'm using currently:
if (request.RawUrl.ToLower().Contains(".png") || request.RawUrl.Contains(".ico") || request.RawUrl.ToLower().Contains(".jpg") || request.RawUrl.ToLower().Contains(".jpeg"))
{
string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string[] img = request.RawUrl.Split('/');
string path = dir + #"\public\imgs\" + img[img.Length - 1];
FileInfo fileInfo = new FileInfo(path);
long numBytes = fileInfo.Length;
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
byte[] output = binaryReader.ReadBytes((int)numBytes);
binaryReader.Close();
fileStream.Close();
var temp = System.Text.Encoding.UTF8.GetString(output);
return temp;
}
I am converting the image into a string to return them (it's the way my boss suggested). This is the method where I am handling these requests.
private static string SendResponse(HttpListenerRequest request)
This is my WebServer classes Run() method. The call to SetContentType just goes through the request.RawUrl and determines the content type.
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("StackLight Web Server is running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
// store html content in a byte array
string responderString = _responderMethod(ctx.Request);
// set the content type
ctx.Response.Headers[HttpResponseHeader.ContentType] = SetContentType(ctx.Request.RawUrl);
byte[] buffer = buffer = Encoding.UTF8.GetBytes(responderString);
// this writes the html out from the byte array
ctx.Response.ContentLength64 = buffer.Length;
using(Stream stream = ctx.Response.OutputStream)
{
stream.Write(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
});
}
My html page needs to display an image to the screen, it displays a broken image so far. I know the images directory is correct, I tested that.
This is where I got my code for the webserver: here
I was thinking that maybe I have to change the SendResponse method to not return a string
I figured it out. I created a class to hold the data, content type and the request.RawUrl. Then, where I was passing a string, I changed it to pass the object I created.
So, for my WebServer class, my Run method looks like this:
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("StackLight Web Server is running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
// set the content type
ctx.Response.Headers[HttpResponseHeader.ContentType] = SetContentType(ctx.Request.RawUrl);
WebServerRequestData data = new WebServerRequestData();
// store html content in a byte array
data = _responderMethod(ctx.Request);
string res = "";
if(data.ContentType.Contains("text"))
{
char[] chars = new char[data.Content.Length/sizeof(char)];
System.Buffer.BlockCopy(data.Content, 0, chars, 0, data.Content.Length);
res = new string(chars);
data.Content = Encoding.UTF8.GetBytes(res);
}
// this writes the html out from the byte array
ctx.Response.ContentLength64 = data.Content.Length;
ctx.Response.OutputStream.Write(data.Content, 0, data.Content.Length);
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
finally
{
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch (Exception ex)
{
ConfigLogger.Instance.LogCritical(LogCategory, ex);
}
});
}
And my SendResponse method looks like this:
private static WebServerRequestData SendResponse(HttpListenerRequest request)
{
string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string[] fileUrl = request.RawUrl.Split('/');
// routes
if (request.RawUrl.Contains("/"))
{
// this is the main page ('/'), all other routes can be accessed from here (including css, js, & images)
if (request.RawUrl.ToLower().Contains(".png") || request.RawUrl.ToLower().Contains(".ico") || request.RawUrl.ToLower().Contains(".jpg") || request.RawUrl.ToLower().Contains(".jpeg"))
{
try
{
string path = dir + Properties.Settings.Default.ImagesPath + fileUrl[fileUrl.Length - 1];
FileInfo fileInfo = new FileInfo(path);
path = dir + #"\public\imgs\" + fileInfo.Name;
byte[] output = File.ReadAllBytes(path);
_data = new WebServerRequestData() {Content = output, ContentType = "image/png", RawUrl = request.RawUrl};
//var temp = System.Text.Encoding.UTF8.GetString(output);
//return Convert.ToBase64String(output);
return _data;
}
catch(Exception ex)
{
ConfigLogger.Instance.LogError(LogCategory, "File could not be read.");
ConfigLogger.Instance.LogCritical(LogCategory, ex);
_errorString = string.Format("<html><head><title>Test</title></head><body>There was an error processing your request:<br />{0}</body></html>", ex.Message);
_byteData = new byte[_errorString.Length * sizeof(char)];
System.Buffer.BlockCopy(_errorString.ToCharArray(), 0, _byteData, 0, _byteData.Length);
_data = new WebServerRequestData() { Content = _byteData, ContentType = "text/html", RawUrl = request.RawUrl };
return _data;
}
}
I'm still cleaning up the code a bit but it now serves the images!
Oh... And here is the object I'm using:
public class WebServerRequestData
{
public string RawUrl { get; set; }
public string ContentType { get; set; }
public byte[] Content { get; set; }
public string RawData { get; set; }
}
Some really bad stuff here:
Empty catch. You'll never find out about many bugs.
Stuffing binary data into a string. Why? There's no encoding that is able to roundtrip binary data.
You're not disposing of ctx. I don't see why you need a manual finally block. Use using.
Untrusted callers can inject arbitrary paths into path. I could request your web.config file by navigating to /img/..\..\web.config (something like that).
Consider factoring out some common expressions into variables. You've got a Copy&Paste error with ToLower. Don't do dirty stuff and you'll have less bugs.

Converting file into Base64String and back again

The title says it all:
I read in a tar.gz archive like so
break the file into an array of bytes
Convert those bytes into a Base64 string
Convert that Base64 string back into an array of bytes
Write those bytes back into a new tar.gz file
I can confirm that both files are the same size (the below method returns true) but I can no longer extract the copy version.
Am I missing something?
Boolean MyMethod(){
using (StreamReader sr = new StreamReader("C:\...\file.tar.gz")) {
String AsString = sr.ReadToEnd();
byte[] AsBytes = new byte[AsString.Length];
Buffer.BlockCopy(AsString.ToCharArray(), 0, AsBytes, 0, AsBytes.Length);
String AsBase64String = Convert.ToBase64String(AsBytes);
byte[] tempBytes = Convert.FromBase64String(AsBase64String);
File.WriteAllBytes(#"C:\...\file_copy.tar.gz", tempBytes);
}
FileInfo orig = new FileInfo("C:\...\file.tar.gz");
FileInfo copy = new FileInfo("C:\...\file_copy.tar.gz");
// Confirm that both original and copy file have the same number of bytes
return (orig.Length) == (copy.Length);
}
EDIT: The working example is much simpler (Thanks to #T.S.):
Boolean MyMethod(){
byte[] AsBytes = File.ReadAllBytes(#"C:\...\file.tar.gz");
String AsBase64String = Convert.ToBase64String(AsBytes);
byte[] tempBytes = Convert.FromBase64String(AsBase64String);
File.WriteAllBytes(#"C:\...\file_copy.tar.gz", tempBytes);
FileInfo orig = new FileInfo(#"C:\...\file.tar.gz");
FileInfo copy = new FileInfo(#"C:\...\file_copy.tar.gz");
// Confirm that both original and copy file have the same number of bytes
return (orig.Length) == (copy.Length);
}
Thanks!
If you want for some reason to convert your file to base-64 string. Like if you want to pass it via internet, etc... you can do this
Byte[] bytes = File.ReadAllBytes("path");
String file = Convert.ToBase64String(bytes);
And correspondingly, read back to file:
Byte[] bytes = Convert.FromBase64String(b64Str);
File.WriteAllBytes(path, bytes);
Another working example in VB.NET:
Public Function base64Encode(ByVal myDataToEncode As String) As String
Try
Dim myEncodeData_byte As Byte() = New Byte(myDataToEncode.Length - 1) {}
myEncodeData_byte = System.Text.Encoding.UTF8.GetBytes(myDataToEncode)
Dim myEncodedData As String = Convert.ToBase64String(myEncodeData_byte)
Return myEncodedData
Catch ex As Exception
Throw (New Exception("Error in base64Encode" & ex.Message))
End Try
'
End Function
private String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}
For Java, consider using Apache Commons FileUtils:
/**
* Convert a file to base64 string representation
*/
public String fileToBase64(File file) throws IOException {
final byte[] bytes = FileUtils.readFileToByteArray(file);
return Base64.getEncoder().encodeToString(bytes);
}
/**
* Convert base64 string representation to a file
*/
public void base64ToFile(String base64String, String filePath) throws IOException {
byte[] bytes = Base64.getDecoder().decode(base64String);
FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}

Categories

Resources