How To Convert "Byted" String Back to Byte Without String [duplicate] - c#

I have a Base64 byte[] array which is transferred from a stream which i need to convert it to a normal byte[] how to do this ?

You have to use Convert.FromBase64String to turn a Base64 encoded string into a byte[].

This may be helpful
byte[] bytes = System.Convert.FromBase64String(stringInBase64);

Try
byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]
byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray));
// This work because all Base64-encoding is done with pure ASCII characters

You're looking for the FromBase64Transform class, used with the CryptoStream class.
If you have a string, you can also call Convert.FromBase64String.

I've written an extension method for this purpose:
public static byte[] FromBase64Bytes(this byte[] base64Bytes)
{
string base64String = Encoding.UTF8.GetString(base64Bytes, 0, base64Bytes.Length);
return Convert.FromBase64String(base64String);
}
Call it like this:
byte[] base64Bytes = .......
byte[] regularBytes = base64Bytes.FromBase64Bytes();
I hope it helps someone.

Related

Sending encrypted data via TCP (“Bad Data” exception)

How can i send illegal charecters from tpc client to tcp server.
This is an example of what the encrypted gibberish looks like:
https://i.stack.imgur.com/wfZdm.png
How can i send this pice of gibberish to either my client or server?
This is my encryption & decryption code
public static string Decrypt(string data)
{
byte[] dataToDecrypt = StringToByteArray(data);
byte[] decryptedData;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKey);
decryptedData = rsa.Decrypt(dataToDecrypt, false);
}
UnicodeEncoding byteConverter = new UnicodeEncoding();
return ByteArrayToString(decryptedData);
}
public static string Encrypt(string data, string publicKey)
{
UnicodeEncoding byteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = StringToByteArray(data);
byte[] encryptedData;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicKey);
encryptedData = rsa.Encrypt(dataToEncrypt, false);
}
return ByteArrayToString(encryptedData);
}
public static byte[] StringToByteArray(string data)
{
return Encoding.ASCII.GetBytes(data);
}
public static string ByteArrayToString(byte[] bytes)
{
return Encoding.ASCII.GetString(bytes);
}
I have made it so the client and the server share eachothers public keys but i am getting Exception "Bad data". One more thing if i send encrypted data from a client to the server which data is 128 bytes the server receives only 78 bytes for example
There's a few things wrong with your code:
You shouldn't be using String at all.
String is meant for text, not arbitrary binary data (I assume you got this impression from C or PHP where their string types are really just synonyms for - or thin-wrappers over - a byte-array).
Keep the Byte[] buffer you get from rs.Encrypt and pass that directly to your Socket, TcpClient or NetworkStream that you're using. You'll need to define a binary protocol with length-prefix though.
Encoding.ASCII.GetBytes will convert the UTF-16LE-encoded characters in the String data instance to 7-bit ASCII, it does this by replacing characters with values above 0x7F with '?' - this is not what you want! (and this is what's causing the garbage output on your screen: those "illegal characters" are byte-values above 0x7F that are outside ASCII's 7-bit range. From the documentation:
It uses replacement fallback to replace each string that it cannot encode and each byte that it cannot decode with a question mark ("?") character.
If you really do want to transmit data over the network using human-readable text then use Base64 encoding: Convert.ToBase64String( Byte[] buffer ) and convert it back using Convert.FromBase64String( String s ) at the receiving end - but you'll still need to length-prefix or delimit your data.

How do I write a byteArray to a specific path

I currently have a method which is taking a picture and saving it..
Once saved I call this method to encrypt the file from a string path
but im not sure how to save it.. I wanted to do
string path = #"C:/somePath"
File.WriteAllBytes(path);
but that doesnt work obv. So how do I properly save a bytearray?
string key = GetUniqueKey(32);
byte[] encKey = Encoding.UTF8.GetBytes(key);
byte[] imgBytes = File.ReadAllBytes(path);
byte[] ebytes = encrypt.AESEncrypt(imgBytes, encKey);
File.WriteAllBytes();
If you actually check the parameters it's asking for, you need to provide the bytes as well as the path.
So:
string path = #"C:/somePath/somefile.png"
string key = GetUniqueKey(32);
byte[] encKey = Encoding.UTF8.GetBytes(key);
byte[] imgBytes = File.ReadAllBytes(path);
byte[] ebytes = encrypt.AESEncrypt(imgBytes, encKey);
File.WriteAllBytes(path, ebytes);
Method's signature is:
File.WriteAllBytes(string path, byte[] bytes)

C# convert byte[] to string with a charset

In C# How can we convert byte[] to string with a charset.eg utf8,SHIFT_JIS,and more
.I know Encoding.UTF8
byte[] inputBytes =SupportClass.ToByteArray(readBytes);
StringBuilder result;
result.Append(System.Text.Encoding.UTF8.GetString(inputBytes,0,inputBytes.Length));//get unreadable code.
my question is how can I get the result from inputBytes with a special charset,like java
StringBuffer result.append(new String(buffer, "SJIS"));
System.Text.Encoding enc = System.Text.Encoding.GetEncoding("shift-jis");
result.Append(enc.GetString(inputBytes,0,inputBytes.Length));
See this article:
http://msdn.microsoft.com/en-us/library/aa332097(v=vs.71).aspx
Instead of Encoding.UTF8, use Encoding.GetEncoding.
E.g.
private static readonly Encoding SHIFT_JIS = Encoding.GetEncoding("Shift_JIS");
SHIFT_JIS.GetString(inputBytes,0,inputBytes.Length)

how to make sure that an array of bytes is encoded by Base64?

I have a method as below:
public void AddAttachment(byte[] attachment)
{
// how to make sure that the attachemnt is encoded by Base64?
}
how to make sure the AddAttachment method accepts an array of bytes that is encoded with Base64?
For example the below is a valid input before being sent to this method:
string attachmentInString = "Hello test";
byte[] attachmentInBytes = System.Convert.FromBase64String(attachmentInString);
but if the attachmentInBytes was encoded using ASCII or etc, the AddAttachement method should throw an exception.
How to achieve this?
Thanks,
Base64 is a way to represent a stream of bytes as a string. If you want the attachment to be a base64 string then change the signature to public void AddAttachment(string attachment)
Then decode the Base64 using byte[] data = Convert.FromBase64String(attachment)
If you want to encode the attachment into base64:
public void AddAttachment(byte[] attachment) {
string base64 = Convert.ToBase64String(attachment)
...
}
From your question I find you are misunderstanding something, hope this helps.
Convert.FromBase64String accepts a string(which is always like ALJWKA==) and outputs a byte[], while Convert.ToBase64String is opposite. So your code:
string attachmentInString = "Hello test";
byte[] attachmentInBytes = System.Convert.FromBase64String(attachmentInString);
will throw an exception, because "Hello test" is not a valid base64 string. See the other method
public void AddAttachment(byte[] attachment)
the argument is a byte[], so in this method you at most convert it to a base64 like string. You can't tell if a byte[] is a valid base64 string or not. You can only do this to a string:
public void AddAttachment(string attachment) //well I know it looks strange
{
byte[] bytes = null;
try
{
bytes = Convert.FromBase64String(attachment);
}
catch
{
//invalid string format
}
}

convert base64Binary to pdf

I have raw data of base64Binary.
string base64BinaryStr = "J9JbWFnZ......"
How can I make pdf file? I know it need some conversion. Please help me.
Step 1 is converting from your base64 string to a byte array:
byte[] bytes = Convert.FromBase64String(base64BinaryStr);
Step 2 is saving the byte array to disk:
System.IO.FileStream stream =
new FileStream(#"C:\file.pdf", FileMode.CreateNew);
System.IO.BinaryWriter writer =
new BinaryWriter(stream);
writer.Write(bytes, 0, bytes.Length);
writer.Close();
using (System.IO.FileStream stream = System.IO.File.Create("c:\\temp\\file.pdf"))
{
System.Byte[] byteArray = System.Convert.FromBase64String(base64BinaryStr);
stream.Write(byteArray, 0, byteArray.Length);
}
First convert the Bas64 string to byte[] and write it into a file.
byte[] bytes = Convert.FromBase64String(base64BinaryStr);
File.WriteAllBytes(#"FolderPath\pdfFileName.pdf", bytes );
This code does not write any file on the hard drive.
Response.AddHeader("Content-Type", "application/pdf");
Response.AddHeader("Content-Length", base64Result.Length.ToString());
Response.AddHeader("Content-Disposition", "inline;");
Response.AddHeader("Cache-Control", "private, max-age=0, must-revalidate");
Response.AddHeader("Pragma", "public");
Response.BinaryWrite(Convert.FromBase64String(base64Result));
Note: the variable base64Result contains the Base64-String: "JVBERi0xLjMgCiXi48/TIAoxI..."
All you need to do is run it through any Base64 decoder which will take your data as a string and pass back an array of bytes. Then, simply write that file out with pdf in the file name.
Or, if you are streaming this back to a browser, simple write the bytes to the output stream, marking the appropriate mime-type in the headers.
Most languages either have built in methods for converted to/from Base64. Or a simple Google with your specific language will return numerous implementations you can use. The process of going back and forth to Base64 is pretty straightforward and can be implemented by even novice developers.
base64BinaryStr - from webservice SOAP message
byte[] bytes = Convert.FromBase64String(base64BinaryStr);

Categories