Convert a string to byte[] for socket - c#

I am writing a simple ftp client with c#.
I am not pro in c#. Is there any way to convert string to byte[] and write it to the socket?
for example for introducing username this is the socket content:
5553455220736f726f7573680d0a
and ASCII equivalent is:
USER soroush
I want a method to convert string. Something like this:
public byte[] getByte(string str)
{
byte[] ret;
//some code here
return ret;
}

Try
byte[] array = Encoding.ASCII.GetBytes(input);

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
Encoding encoding = Encoding.UTF8; //or below line
//System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding();
return encoding.GetBytes(str);
}
and
// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
Encoding enc = Encoding.UTF8; //or below line
//System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);

Related

Equivalent of CryptoJS.enc.Base64.parse on C#

I have a javascript backend that use CryptoJS to generate a hash, I need to generate the same hash on C# Client but can't reproduce the same result than javascript.
The backend code are this:
function generateHash (str, cypherkey) {
return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256(str, CryptoJS.enc.Base64.parse(cypherkey)))
}
console.log(generateHash("testString", "UTI5dVozSmhkSE1zSUhsdmRTZDJaU0JtYjNWdVpDQnBkQ0VnUVhKbElIbHZkU0J5WldGa2VTQjBieUJxYjJsdUlIVnpQeUJxYjJKelFIZGhiR3hoY0c5d0xtTnZiUT09"))
And print: "FwdJUHxt/xSeNxHQFiOhmPDRh73NFfuWK7LG6ssN9k4="
Then when I try to do the same on my C# client with this code:
public static string generateHash(string str, string cypherkey)
{
var keyenc = new System.Text.ASCIIEncoding();
byte[] keyBytes = keyenc.GetBytes(cypherkey);
var key = BitConverter.ToString(keyBytes);
var encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);
byte[] messageBytes = encoding.GetBytes(str);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
return Convert.ToBase64String(hashmessage);
}
}
Print other result: "SiEjJASvYWfO5y+EiSJAqamMcUyBSTDl5Sy1zXl1J/k="
The problem are on the process to convert to Base64 the cypherkey, probably it's wrong.
Anyone know how can solve this?
Greetings and a lot of thanks ^^
I haven't seen the source of CryptoJs so there are assumptions here (from method names, encoding, etc):
public static string generateHash(string str, string cypherkey)
{
// based on CryptoJS.enc.Base64.parse
byte[] keyBytes = System.Convert.FromBase64String(cypherkey);
using (var hmacsha256 = new HMACSHA256(keyBytes))
{
byte[] hashmessage = hmacsha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
return Convert.ToBase64String(hashmessage);
}
}
Result:
FwdJUHxt/xSeNxHQFiOhmPDRh73NFfuWK7LG6ssN9k4=
Hth

ASP.NET SOAP Webservice ,Encode Problem in Exception

Here is my problem, Im trying to Encode the response of my webservice with the following Code.
public static string ConvertToUTF8(string Cadena)
{
string mensajeex = Cadena;
Encoding utf8 = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
// Convert the string into a byte array.
byte[] unicodeBytes = unicode.GetBytes(mensajeex);
// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(unicode, utf8, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string.
char[] asciiChars = new char[utf8.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
utf8.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string Utf8string = new string(asciiChars);
// Display the strings created before and after the conversion.
Console.WriteLine("Original string: {0}", mensajeex);
Console.WriteLine("Ascii converted string: {0}", Utf8string);
return Utf8string;
}
And actually it works! But when I try to Encode a string and then pass through an exception as a Message property like this
throw new Exception(XMLHelper.ConvertToUTF8(Message));
It give me the response wrong like:
El valor 'R' no es vĂ¡lido seg&#250
Any ideas? Thanks

C#/powershell encoding digital signature to base 64 and decoding it back and authenticating it.

Hi I am trying to stuff a digital signature inside the Authorization header of a POST request.
I need to use powershell by requirement, but the actual digital signature is done in a c# class which I call from inside of my powershell.
$obj = new-object DigitalSignatureApplication.DigitalSignature
$signature = $obj.GetSignature($certificateName,$Message)
Same with the authentication part
$verification = $obj.verifySignature($signature64,$certificateName,$Message)
The idea is to Base 64 encode the signature in powershell and send it across in the POST request and then decode it back and authenticate the signature.
$signatureBytes = [System.Text.Encoding]::UTF8.GetBytes($signature)
$signature64 = [System.Convert]::ToBase64String($signatureBytes)
$headers = #{Authorization = "DSignature "+$signature64}
The problem is that between encoding it to base64 and decoding it back, something is messing up the signature and the authentication fails, I have tried encoding and decoding purely in c# too but even that dose not work.
The following is my signing logic in C#
byte[] buffer = Encoding.Default.GetBytes(UnsignedMessage);
byte[] signature = privateKey.SignData(buffer, new SHA1Managed());
return EncodeTo64(GetString(signature)); // converting to base 64 before returning
// return GetString(signature); // just converting the byte [] to a string
This is my verification/ authentication logic in C#
byte[] buffer = Encoding.Default.GetBytes(message);
string decodedSigneture = DecodeFrom64(encodedsignature);
byte[] signaturebytes = GetBytes(decodedSigneture);
bool verify = publicKey.VerifyData(buffer, new SHA1Managed(), signaturebytes);
The following is my logic for Get string and get bytes.
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
The following is the two different ways of encoding and decoding to base 64 processes I have tried ....
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static string Base64Decode(string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes
= System.Convert.FromBase64String(encodedData);
string returnValue =
System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
Thanks in advance,

Conversion between Base64String and Hexadecimal

I use in my C++/CLI project ToBase64String to give a string like /MnwRx7kRZEQBxLZEkXndA== I want to convert this string to Hexadecimal representation, How I can do that in C++/CLI or C#?
FromBase64String will take the string to bytes
byte[] bytes = Convert.FromBase64String(string s);
Then, BitConverter.ToString() will convert a byte array to a hex string ( byte[] to hex string )
string hex = BitConverter.ToString(bytes);
Convert the string to a byte array and then do a byte to hex conversion
string stringToConvert = "/MnwRx7kRZEQBxLZEkXndA==";
byte[] convertedByte = Encoding.Unicode.GetBytes(stringToConvert);
string hex = BitConverter.ToString(convertedByte);
Console.WriteLine(hex);
public string Base64ToHex(string strInput)
{
try
{
var bytes = Convert.FromBase64String(strInput);
var hex = BitConverter.ToString(bytes);
return hex.Replace("-", "").ToLower();
}
catch (Exception)
{
return "-1";
}
}
On the contrary: https://stackoverflow.com/a/61224761/3988122

how to convert from string to byte[] [duplicate]

I have the following code:
string s = "2563MNBJP89256666666685755854";
Byte[] bytes = encoding.GetBytes(s);
string hex = "";
foreach (byte b in bytes)
{
int c=b;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(c.ToString()));
}
It prints the hex values . How can I add it in a vector ob bytes like this?
new byte [0x32,0x35..]
In hex I have : 323536....and so on. The next step is to add then in a byte[] vector in the following format 0x32,0x35..and so on; How to do this?
THX
Isn't bytes already the list of bytes you want?
C#: System.Text.Encoding.ASCII.GetBytes("test")
For C# you could try
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(strVar);//strVar is the string variable
in C# you can use Encoding.GetBytes Method

Categories