How to convert a byteArray to Binary Value in c#? - c#

I initilaly have a string which is converted to byteArray.
Then I convert this byteArray to HEX as shown below in my code.
Then I further need to convert this to a binary value.
string ID = "A0101185K";
byte[] ba = Encoding.Default.GetBytes(IC);
var hexString= BitConverter.ToString(ba).Replace("-", "");

You can convert byte to string in that way
static string ToBinary(byte b) => Convert.ToString(b, 2).PadLeft(8, '0');
and use it in your program like this
string MESSAGE = "A0101185K";
byte[] bytes = Encoding.Default.GetBytes(MESSAGE);
var binaries = string.Concat(bytes.Select(ToBinary));
I hope that helps you. But of course you didn't tell how you want to store your result, so maybe this is not the right answer.

Related

how to deocde some coded text in c# [duplicate]

I have following string as utf-8. i want convert it to persian unicode:
ابراز داشت: امام رضا برخال� دیگر ائمه با جنگ نرم
this site correctly do convert and result is: ابراز داشت: امام رضا برخالف دیگر ائمه با جنگ نرم
I test many method and ways but can't resolve this problem, for example these two lines did not produce the desired result:
string result = Encoding.GetEncoding("all type").GetString(input);
and
byte[] preambleBytes= Encoding.UTF8.GetPreamble();
byte[] inputBytes= Encoding.UTF8.GetBytes(input);
byte[] resultBytes= preambleBytes.Concat(inputBytes).ToArray();
string result=Encoding.UTF8.GetString(resultBytes.ToArray());
string resultAscii=Encoding.Ascii.GetString(inputBytes);
string resultUnicode=Encoding.Unicode.GetString(inputBytes);
You can use Encoding.Convert.
string source = // Your source
byte[] utfb = Encoding.UTF8.GetBytes(source);
byte[] resb = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("ISO-8859-6"), utfb);
string result = Encoding.GetEncoding("ISO-8859-6").GetString(resb);
NOTE: I wasn't sure which standard you wanted so for the example I used ISO-8859-6 (Arabic).
I understand what is problem by reading What is problem and Solution .
when i converted string to byte[], i forced that to convert as utf-8 format but really i should use default format for converting.
False converting:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
resultString = Encoding.UTF8.GetString(bytes);
But
True converting:
byte[] bytes = Encoding.Default.GetBytes(inputString);
resultString = Encoding.UTF8.GetString(bytes);
Tanks for your comments and answers.
I get bytes by UTF8 and Get String by Default as follow. This worked for me.
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
resultString = Encoding.Default.GetString(bytes);

C# equivalent for PHP file_put_contents

I am converting a PHP file to C#,completed 75%,stuck with these lines
if(file_put_contents($uploaddir.$randomName, $decodedData)) {
//echo $randomName.":uploaded successfully"; //NO NEED TO CONVERT ECHO PART
}
PHP Brothers please help
MORE INFO
I converted this
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
to this
// Encode it correctly
string encodedData = data[1].Replace(' ', '+');
string decodedData = base64Decode(encodedData);
where base64Decode is
public static string base64Decode(string data)
{
byte[] binary = Convert.FromBase64String(data);
return Encoding.Default.GetString(binary);
}
Try this:
System.IO.File.WriteAllText (uploaddir + randomname, decodedData);
See the MSDN for details on the WriteAllText method.
However, your approach of converting your data to a byte array, and then converting it to a string in the base64Decode method, followed by writing it to the file is a bit too complicated IMO. You can just write your byte array to a file, decode the data like this:
public static byte[] base64Decode(string data)
{
return Convert.FromBase64String(data);
}
and then call
byte[] decodedData = base64Decode(encodedData);
System.IO.File.WriteAllBytes(uploaddir + randomname, decodedData);
WriteAllBytes documentation here.
Closest analogon is probably System.IO.File.WriteAllText
string uploaddir;
string randomName;
string decodedData;
// ....
System.IO.File.WriteAllText(
System.IO.Path.Combine(uploaddir, randomName),
decodedData
);

Error in converting from Encrypted value

I have a encryption method GetDecryptedSSN(). I tested it’s correctness by the following test. It works fine
//////////TEST 2//////////
byte[] encryptedByteWithIBMEncoding2 = DecryptionServiceHelper.GetEncryptedSSN("123456789");
string clearTextSSN2 = DecryptionServiceHelper.GetDecryptedSSN(encryptedByteWithIBMEncoding2);
But when I do a conversion to ASCII String and then back, it is not working correctly. What is the problem in the conversion logic?
//////////TEST 1//////////
//String -- > ASCII Byte --> IBM Byte -- > encryptedByteWithIBMEncoding
byte[] encryptedByteWithIBMEncoding = DecryptionServiceHelper.GetEncryptedSSN("123456789");
//encryptedByteWithIBMEncoding --> Encrypted Byte ASCII
string EncodingFormat = "IBM037";
byte[] encryptedByteWithASCIIEncoding = Encoding.Convert(Encoding.GetEncoding(EncodingFormat), Encoding.ASCII,
encryptedByteWithIBMEncoding);
//Encrypted Byte ASCII - ASCII Encoded string
string encodedEncryptedStringInASCII = System.Text.ASCIIEncoding.ASCII.GetString(encryptedByteWithASCIIEncoding);
//UpdateSSN(encodedEncryptedStringInASCII);
byte[] dataInBytesASCII = System.Text.ASCIIEncoding.ASCII.GetBytes(encodedEncryptedStringInASCII);
byte[] bytesInIBM = Encoding.Convert(Encoding.ASCII, Encoding.GetEncoding(EncodingFormat),
dataInBytesASCII);
string clearTextSSN = DecryptionServiceHelper.GetDecryptedSSN(bytesInIBM);
Helper Class
public static class DecryptionServiceHelper
{
public const string EncodingFormat = "IBM037";
public const string SSNPrefix = "0000000";
public const string Encryption = "E";
public const string Decryption = "D";
public static byte[] GetEncryptedSSN(string clearTextSSN)
{
return GetEncryptedID(SSNPrefix + clearTextSSN);
}
public static string GetDecryptedSSN(byte[] encryptedSSN)
{
return GetDecryptedID(encryptedSSN);
}
private static byte[] GetEncryptedID(string id)
{
ServiceProgram input = new ServiceProgram();
input.RequestText = Encodeto64(id);
input.RequestType = Encryption;
ProgramInterface inputRequest = new ProgramInterface();
inputRequest.Test__Request = input;
using (MY_Service operation = new MY_Service())
{
return ((operation.MY_Operation(inputRequest)).Test__Response.ResponseText);
}
}
private static string GetDecryptedID(byte[] id)
{
ServiceProgram input = new ServiceProgram();
input.RequestText = id;
input.RequestType = Decryption;
ProgramInterface request = new ProgramInterface();
request.Test__Request = input;
using (MY_Service operationD = new MY_Service())
{
ProgramInterface1 response = operationD.MY_Operation(request);
byte[] encodedBytes = Encoding.Convert(Encoding.GetEncoding(EncodingFormat), Encoding.ASCII,
response.Test__Response.ResponseText);
return System.Text.ASCIIEncoding.ASCII.GetString(encodedBytes);
}
}
private static byte[] Encodeto64(string toEncode)
{
byte[] dataInBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
Encoding encoding = Encoding.GetEncoding(EncodingFormat);
return Encoding.Convert(Encoding.ASCII, encoding, dataInBytes);
}
}
REFERENCE:
Getting incorrect decryption value using AesCryptoServiceProvider
This is the problem, I suspect:
string encodedEncryptedStringInASCII =
System.Text.ASCIIEncoding.ASCII.GetString(encryptedByteWithASCIIEncoding);
(It's not entirely clear because of all the messing around with encodings beforehand, which seems pointless to me, but...)
The result of encryption is not "text encoded in ASCII" - so you shouldn't try to treat it that way. (You haven't said what kind of encryption you're using, but it would be very odd for it to produce ASCII text.)
It's just an arbitrary byte array. In order to represent that in text only using the ASCII character set, the most common approach is to use base64. So the above code would become:
string encryptedText = Convert.ToBase64(encryptedByteWithIBMEncoding);
Then later, you'd convert it back to a byte array ready for decryption as:
encryptedByteWithIBMEncoding = Convert.FromBase64String(encryptedText);
I would strongly advise you to avoid messing around with the encodings like this if you can help it though. It's not clear why ASCII needs to get involved at all. If you really want to encode your original text as IBM037 before encryption, you should just use:
Encoding encoding = Encoding.GetEncoding("IBM037");
string unencryptedBinary = encoding.GetBytes(textInput);
Personally I'd usually use UTF-8, as an encoding which can handle any character data rather than just a limited subset, but that's up to you. I think you're making the whole thing much more complicated than it needs to be though.
A typical "encrypt a string, getting a string result" workflow is:
Convert input text to bytes using UTF-8. The result is a byte array.
Encrypt result of step 1. The result is a byte array.
Convert result of step 2 into base64. The result is a string.
To decrypt:
Convert the string from base64. The result is a byte array.
Decrypt the result of step 1. The result is a byte array.
Convert the result of step 2 back to a string using the same encoding as step 1 of the encryption process.
In DecryptionServiceHelper.GetEncryptedSSN you are encoding the text in IBM037 format BEFORE encrypting.
So the following piece of code is not correct as you are converting the encrypted bytes to ASCII assuming that its in the IBM037 format. That's wrong as the encrypted bytes is not in IBM037 format (the text was encoded before encryption)
//encryptedByteWithIBMEncoding --> Encrypted Byte ASCII
string EncodingFormat = "IBM037";
byte[] encryptedByteWithASCIIEncoding = Encoding.Convert(Encoding.GetEncoding(EncodingFormat), Encoding.ASCII,
encryptedByteWithIBMEncoding);
One possible solution is to encode the encrypted text using IBM037 format, that should fix the issue I guess.

get dsa signature value in octect string

I am trying to read the octect string value of attribute dsa-signature. I got the field from default naming context properties. But its in byte array, when I try to convert it into a string it give wrong output.
Does anyone knows how to do correct octect converion?
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=cobra,DC=net");
PropertyValueCollection propCol = entry.Properties["dSASignature"];
Console.WriteLine(propCol.PropertyName + " : " + propCol.Value);
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string str = enc.GetString((System.Byte[])propCol.Value);
Console.WriteLine("value : " + str);
Thanks in advance
But its in byte array, when I try to convert it into a string it give wrong output.
It's a byte array. Just an arbitrary sequence of bytes. It's not UTF-8-encoded text, which is what you're treating it as.
If you want to display the bytes formatted as hex, you can use:
byte[] data = (byte[]) propCol.Value;
string hex = BitConverter.ToString(data);
If you need to transfer it more efficiently but as text, you could use base64... but ideally you should treat it as a byte array for as long as possible, given that fundamentally it's just binary data.

How do I convert a Hexidecimal string to byte in C#?

How can I convert this string into a byte?
string a = "0x2B";
I tried this code, (byte)(a); but it said:
Cannot convert type string to byte...
And when I tried this code, Convert.ToByte(a); and this byte.Parse(a);, it said:
Input string was not in a correct format...
What is the proper code for this?
But when I am declaring it for example in an array, it is acceptable...
For example:
byte[] d = new byte[1] = {0x2a};
You have to specify the base to use in Convert.ToByte since your input string contains a hex number:
byte b = Convert.ToByte(a, 16);
byte b = Convert.ToByte(a, 16);
You can use the ToByte function of the Convert helper class:
byte b = Convert.ToByte(a, 16);
Update:
As others have mentioned, my original suggestion to use byte.Parse() with NumberStyles.HexNumber actually won't work with hex strings with "0x" prefix. The best solution is to use Convert.ToByte(a, 16) as suggested in other answers.
Original answer:
Try using the following:
byte b = byte.Parse(a, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
You can use UTF8Encoding:
public static byte[] StrToByteArray(string str)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}

Categories