Binary to String using Google.Protobuf - c#

I'm trying to take a .txt file which icontains some binary. E.g.
&
ns16A086C66661C9 D% C(0 ¢À
&
ns167C0BC683548A €\D% €‹C(0 ¢À
&
ns16BC3BAF56248CÍ=D%¤pìC(0 ¢À
&
ns16A89FBA902317q%¤D%"÷C(0 ¢À
&
ns16EC1F720BB5983ó1C%×C(0ž¢À
&
ns1690E7C450794F ÀD% €ŠC(0 ¢À
&
ns16A408EAB24E2Fš©ED%…‹éC(0 ¢À
&
ns16F832E429A2C4 #{D% €ÍC(0 ¢À
&
ns160CD74622F0D3
—yD%ÍløC(0 ¢À
&
ns16485A3F0BA1D7öˆyD%…+¹C(0ž¢À
&
ns16EC35866601D4 #HD% ÀD(0 ¢À
&
ns1660F189ED2318 «D% èB(0 ¢À
&
ns16
to change it into string. However I do not know how to approach this using Google.Protobuf's library.
This is what I have now, I can't seem to figure out how to parse the data read from the .txt, put it through Google.Protobuf's decoder??? and get the string out proper.
namespace ConsoleApplicationTest
{
class Program
{
static void Main(string[] args)
{
byte[] array = File.ReadAllBytes("C:/brokerdata.txt");
Google.Protobuf.IMessage<string> a = new IMessage<string>();
Google.Protobuf.MessageParser<a> bb = new MessageParser<a>(() => "");
bb.ParseFrom(array);
string s = System.Text.Encoding.UTF8.GetString(array, 0, array.Length);
Console.Out.WriteLine(s);
Console.WriteLine("First byte: {0}", array[0]);
Console.WriteLine("Last byte: {0}", array[array.Length - 1]);
Console.WriteLine(array.Length);
//Console.Out.WriteLine(array);
Console.ReadKey();
}
}
}

Related

Chrome Native messaging with C# Application

I am trying to communicate with a C# app through chrome native messaging. I am totally new to C#. So I'll create a sample app through following code. How do I add this DisplayMessage function to display the incoming message in the UI?. I have used forms for this UI.
nativeMessage.exe
using System;
using System.IO;
using System.Windows.Forms;
namespace NativeMsgApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string message = txt_inputBox.Text;
label1.Text = "Send Message "+ message;
OpenStandardStreamOut(message);
}
private static string OpenStandardStreamIn()
{
//// We need to read first 4 bytes for length information
Stream stdin = Console.OpenStandardInput();
int length = 0;
byte[] bytes = new byte[4];
stdin.Read(bytes, 0, 4);
length = System.BitConverter.ToInt32(bytes, 0);
string input = "";
for (int i = 0; i < length; i++)
{
input += (char)stdin.ReadByte();
}
return input;
}
private static void OpenStandardStreamOut(string stringData)
{
//// We need to send the 4 btyes of length information
string msgdata = "{\"text\":\"" + stringData + "\"}";
int DataLength = msgdata.Length;
Stream stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((DataLength >> 0) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 8) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 16) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 24) & 0xFF));
//Available total length : 4,294,967,295 ( FF FF FF FF )
Console.Write(msgdata);
}
private static void DisplayMessage()
{
while (OpenStandardStreamIn() != null || OpenStandardStreamIn() != "")
{
OpenStandardStreamOut("Received to Native App: " + OpenStandardStreamIn());
OpenStandardStreamOut("Recieved: " + OpenStandardStreamIn());
}
}
}
}
The UI of the App

How to parse binary data transmitted over GPIB with IVI library

I am working with a Fluke 8588 and communicating with it using Ivi.Visa.Interop I am trying to use the digitizer function to get a large number of samples of a 5V 1k Hz sinewave. To improve the transfer time of the data the manual mentions a setting for using a binary packed data format. It provides 2 and 4 byte packing.
This is the smallest example I could put together:
using System;
using System.Threading;
using Ivi.Visa.Interop;
namespace Example
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Initiallizing Equipment");
int timeOut = 3000;
string resourceName = "GPIB0::1::INSTR";
ResourceManager rm = new ResourceManager();
FormattedIO488 fluke8588 = new FormattedIO488
{
IO = (IMessage)rm.Open(resourceName, AccessMode.NO_LOCK, timeOut)
};
Console.WriteLine("Starting Setup");
fluke8588.WriteString("FORMAT:DATA PACKED,4");
fluke8588.WriteString("TRIGGER:COUNT 100000");
Console.WriteLine("Initiate Readings");
fluke8588.WriteString("INITIATE:IMMEDIATE");
Thread.Sleep(3000);
Console.WriteLine("Readings Complete");
Console.WriteLine("Fetching Reading");
fluke8588.WriteString("FETCH?");
string response = fluke8588.ReadString();
Byte[] bytes = System.Text.Encoding.ASCII.GetBytes(response);
fluke8588.WriteString("FORMAT:DATA:SCALE?");
double scale = Convert.ToDouble(fluke8588.ReadString());
int parityMask = 0x8;
for (int i = 0; i < 100000; i += 4)
{
int raw = (int)((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | (bytes[i + 3]));
int parity = (parityMask & bytes[i]) == parityMask ? -1 : 1;
int number = raw;
if (parity == -1)
{
number = ~raw * parity;
}
Console.WriteLine(number * scale);
}
Console.Read();
}
}
}
The resulting data looks like this:
I preformed the steps "manually" using a tool called NI Max. I get a header followed by the 10 4 byte integers and ending with a new line char. the negative integers are 2s complement, which was not specified in the manual but I was able to determine after I had enough samples.
TRIGGER:COUNT was only set to 10 at the time this image was taken.
How can I get this result in c#?
I found that I was using the wrong Encoding, changing from System.Text.Encoding.ASCII.GetBytes(response) to
System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(1252);
Byte[] bytes = encoding.GetBytes(response);
got the desired result.
That said, I also learned there is an alternative option to FormattedIO488.ReadString for binary data, using FormattedIO488.ReadIEEEBlock(IEEEBinaryType.BinaryType_I4) this will return an array of integers and requires no extra effort with twiddling bits, this is the solution I would suggest.
using System;
using System.Linq;
using Ivi.Visa.Interop;
using System.Threading;
using System.Collections.Generic;
namespace Example
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Initiallizing Equipment");
int timeOut = 3000;
string resourceName = "GPIB0::1::INSTR";
ResourceManager rm = new ResourceManager();
FormattedIO488 fluke8588 = new FormattedIO488
{
IO = (IMessage)rm.Open(resourceName, AccessMode.NO_LOCK, timeOut)
};
Console.WriteLine("Starting Setup");
fluke8588.WriteString("FORMAT:DATA PACKED,4");
fluke8588.WriteString("TRIGGER:COUNT 100000");
Console.WriteLine("Initiate Readings");
fluke8588.WriteString("INITIATE:IMMEDIATE");
Thread.Sleep(3000);
Console.WriteLine("Readings Complete");
Console.WriteLine("Fetching Reading");
fluke8588.WriteString("FETCH?");
List<int> response = new List<int>(fluke8588.ReadIEEEBlock(IEEEBinaryType.BinaryType_I4));
fluke8588.WriteString("FORMAT:DATA:SCALE?");
double scale = Convert.ToDouble(fluke8588.ReadString());
foreach (var value in response.Select(i => i * scale).ToList())
{
Console.WriteLine(value);
}
Console.Read();
}
}
}
Result data looks like:

I Want Convert Hex to Ascii

I want convert hex to ascii.
I was try different two methods. But I could not be successful.
Method1:
public void ConvertHex(String hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
}
String ascii = sb.ToString();
StreamWriter wrt = new StreamWriter("D:\\denemeASCII.txt");
wrt.Write(ascii);
}
Method 2:
public string HEX2ASCII(string hex)
{
string res = String.Empty;
for (int a = 0; a < hex.Length; a = a + 2)
{
string Char2Convert = hex.Substring(a, 2);
int n = Convert.ToInt32(Char2Convert, 16);
char c = (char)n;
res += c.ToString();
}
return res;
}
Incoming error message :(
What should I do?
Your "Method1" has a few chances of being rewritten to work. (Your "Method2" is hopeless.)
So, in "Method1", you do String hs = hexString.Substring( i, i + 2 ) and then you forget that hs ever existed. (Shouldn't the compiler be giving you a warning about that?) Then you proceed to do System.Convert.ToChar( System.Convert.ToUInt32( hexString.Substring( 0, 2 ), 16 ) ) but hexString.Substring( 0, 2 ) will always pick the first two characters of the hexString, not the two characters pointed by i. What you probably meant to do is this instead: System.Convert.ToChar( System.Convert.ToUInt32( hs , 16) )
Also, you are declaring a StringBuilder sb; but you are never adding anything to it. At the same time, System.Convert.ToChar() does not work by side effect; it returns a value; if you don't do anything with the returned value, the returned value is lost forever. What you probably meant to do is add the result of System.Convert.ToChar() to your StringBuilder.
You don't have valid character in your input. A character in c# is two bytes class with a private property which indicates if the character is one or two bytes. The encoding library methods (unicode, UTF6, UTF7, UTF8) normally does the conversion and sets the private property. It is hard to tell with your input if you are converting to one or two bytes, and if the input is big endian or little endian. The code below converts to byte[] and int16[].
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "0178 0000 0082 f000 0063 6500 00da 6400 00be 0000 00ff ffff ffff ffff ffd6 6600";
ConvertHex(input);
}
static void ConvertHex(String hexString)
{
Int16[] hexArray = hexString.Split(new char[] {' '},StringSplitOptions.RemoveEmptyEntries)
.Select(x => Int16.Parse(x, NumberStyles.HexNumber)).ToArray();
byte[] byteArray = hexArray.Select(x => new byte[] { (byte)((x >> 8) & 0xff), (byte)(x & 0xff) }).SelectMany(x => x).ToArray();
}
}
}

Chrome native message

I am working on sample application of "Chrome Native Messaging". I did all the set as per steps mention on website. I am able to run application as well however i am not getting response message from native application. When i start extension very firts time i get the response message.
Downloaded sample from here
When i sent message from browser native app not responding it check below image
C# code as below
static void Main(string[] args)
{
string message = "test message from native app.";
OpenStandardStreamOut(message);
while (OpenStandardStreamIn() != null || OpenStandardStreamIn() != "")
{
OpenStandardStreamOut("Received to Native App: " + OpenStandardStreamIn());
OpenStandardStreamOut("Recieved: " + OpenStandardStreamIn());
}
}
private static string OpenStandardStreamIn()
{
//// We need to read first 4 bytes for length information
Stream stdin = Console.OpenStandardInput();
int length = 0;
byte[] bytes = new byte[4];
stdin.Read(bytes, 0, 4);
length = System.BitConverter.ToInt32(bytes, 0);
string input = "";
for (int i = 0; i < length; i++)
{
input += (char)stdin.ReadByte();
}
return input;
}
private static void OpenStandardStreamOut(string stringData)
{
//// We need to send the 4 btyes of length information
string msgdata = "{\"text\":\"" + stringData + "\"}";
int DataLength = msgdata.Length;
Stream stdout = Console.OpenStandardOutput();
stdout.WriteByte((byte)((DataLength >> 0) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 8) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 16) & 0xFF));
stdout.WriteByte((byte)((DataLength >> 24) & 0xFF));
//Available total length : 4,294,967,295 ( FF FF FF FF )
Console.Write(msgdata);
}
manifest.json as below
{"name": "com.example.native",
"description": "Native support for Chrome Extension",
"path": "NativeApp.exe",
"type": "stdio",
"allowed_origins": [
"chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"
],
"permissions": [
"nativeMessaging"
]
}
Some where i feel we are not receiving response from native host becoz i have added debug point to following code in browser which is not getting hit
function onNativeMessage(message) {
appendMessage("Received message: " + JSON.stringify(message) + "");
}
Am i missing something ?
I had the same problem. Make sure the message you are sending is valid JSON. In my case, the value being received by the host was "some value" with the double quotation marks. When that was getting concatenated to make the msgdata variable, it was creating invalid JSON.

C# Base64 encoding / decoding fails when using custom encrypted password

Im currently writing a program that is encrypting a password (using a custom method), and then encoding the password to Base64 using the To/FromBase64Transform classes. The problem is, when i encode my encrypted password, I am unable to decode it back to its proper encrypted state. The Base64Helper class is just a wrapper for the To/FromBase64Transform classes.
My Test Code:
static void Main(string[] args)
{
bool Worked = false;
string Password = "testing";
Console.WriteLine("Password: " + Password);
// == Encode then decode 64 test. DecPass64 should equal password == //
// Encodes to Base64 using ToBase64Transform
string EncPass64 = Base64Helper.EncodeString(Password);
// Decodes a Base64 string using FromBase64Transform
string DecPass64 = Base64Helper.DecodeString(EncPass64);
// Test if base 64 ecoding / decoding works
Worked = (Password == DecPass64);
Console.WriteLine();
Console.WriteLine("Base64 Pass Encoded: " + EncPass64);
Console.WriteLine("Base64 Pass Decoded: " + DecPass64);
Console.WriteLine("Base64 Encode to Base64 Decode Worked? : " + Worked); // True
// gspassenc uses XOR to switch passwords back and forth between encrypted and decrypted
string GsEncodedPass = gspassenc(Password);
string GsDecodedPass = gspassenc(GsEncodedPass);
Worked = (Password == GsDecodedPass);
// GsDecodedPass should equal the original Password
Console.WriteLine();
Console.WriteLine("GsPass Encoded: " + GsEncodedPass);
Console.WriteLine("GsPass Decoded: " + GsDecodedPass);
Console.WriteLine("GsEncode to GsDecode Worked? : " + Worked); // True
// Bas64 encode the encrypted password. Then decode the base64. B64_GsDecodedPass should equal
// the GsEncoded Password... But it doesn't for some reason!
string B64_GsEncodedPass = Base64Helper.EncodeString(GsEncodedPass);
string B64_GsDecodedPass = Base64Helper.DecodeString(B64_GsEncodedPass);
Worked = (B64_GsDecodedPass == GsEncodedPass);
// Print results
Console.WriteLine();
Console.WriteLine("Base64 Encoded GsPass: " + B64_GsEncodedPass);
Console.WriteLine("Base64 Decoded GsPass: " + B64_GsDecodedPass);
Console.WriteLine("Decoded == GS Encoded Pass? : " + Worked); // False
// Stop console from closing till we say so
Console.Read();
}
private static int gslame(int num)
{
int c = (num >> 16) & 0xffff;
int a = num & 0xffff;
c *= 0x41a7;
a *= 0x41a7;
a += ((c & 0x7fff) << 16);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
a += (c >> 15);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
return a;
}
private static string gspassenc(string pass)
{
int a = 0;
int num = 0x79707367; // gspy
int len = pass.Length;
char[] newPass = new char[len];
for (int i = 0; i < len; ++i)
{
num = gslame(num);
a = num % 0xFF;
newPass[i] = (char)(pass[i] ^ a);
}
return new String(newPass);
}
And the result is:
Any help will be much appreciated!
UPDATE: Here is my Base64Helper Class:
class Base64Helper
{
public static string DecodeString(string encoded)
{
return Encoding.ASCII.GetString(Convert.FromBase64String(encoded));
}
public static string EncodeString(string decoded)
{
return Convert.ToBase64String(Encoding.ASCII.GetBytes(decoded));
}
}
It's because of the way you are interfering with the Unicode "Chars" of the string with the encoding algorithm and then constructing a String using those "Chars" which then might not form a valid Unicode stream.
When converting from your String to a Byte array and back again, you need to decide which encoding to use....and you can't arbitrarily change the byte stream (via your encryption routine) and expect it to produce a valid string when being converted back.
I've modified your code to show some string to byte[] conversion steps...you can adjust these depending on your need.
static void Main(string[] args)
{
bool Worked = false;
string Password = "testing";
Console.WriteLine("Password: " + Password);
// == Encode then decode 64 test. DecPass64 should equal password == //
// Encodes to Base64 using ToBase64Transform
string EncPass64 = Base64Helper.EncodeString(Password);
// Decodes a Base64 string using FromBase64Transform
string DecPass64 = Base64Helper.DecodeString(EncPass64);
// Test if base 64 ecoding / decoding works
Worked = (Password == DecPass64);
Console.WriteLine();
Console.WriteLine("Base64 Pass Encoded: " + EncPass64);
Console.WriteLine("Base64 Pass Decoded: " + DecPass64);
Console.WriteLine("Base64 Encode to Base64 Decode Worked? : " + Worked); // True
// gspassenc uses XOR to switch passwords back and forth between encrypted and decrypted
byte [] passwordbytes = Encoding.UTF8.GetBytes(Password);
byte [] bytes_GsEncodedPass = gspassenc(passwordbytes);
string GsEncodedPass = Encoding.UTF8.GetString(bytes_GsEncodedPass);
byte[] bytes_GsDecodedPass = gspassenc(bytes_GsEncodedPass);
string GsDecodedPass = Encoding.UTF8.GetString(bytes_GsDecodedPass);
Worked = (Password == GsDecodedPass);
// GsDecodedPass should equal the original Password
Console.WriteLine();
Console.WriteLine("GsPass Encoded: " + GsEncodedPass);
Console.WriteLine("GsPass Decoded: " + GsDecodedPass);
Console.WriteLine("GsEncode to GsDecode Worked? : " + Worked); // True
// Bas64 encode the encrypted password. Then decode the base64. B64_GsDecodedPass should equal
// the GsEncoded Password... But it doesn't for some reason!
string B64_GsEncodedPass = Convert.ToBase64String(bytes_GsEncodedPass);
byte []bytes_B64_GsDecodedPass = Convert.FromBase64String(B64_GsEncodedPass);
string B64_GsDecodedPass = Encoding.UTF8.GetString(bytes_B64_GsDecodedPass);
Worked = (B64_GsDecodedPass == GsEncodedPass);
// Print results
Console.WriteLine();
Console.WriteLine("Base64 Encoded GsPass: " + B64_GsEncodedPass);
Console.WriteLine("Base64 Decoded GsPass: " + B64_GsDecodedPass);
Console.WriteLine("Decoded == GS Encoded Pass? : " + Worked); // False
// Stop console from closing till we say so
Console.Read();
}
private static int gslame(int num)
{
int c = (num >> 16) & 0xffff;
int a = num & 0xffff;
c *= 0x41a7;
a *= 0x41a7;
a += ((c & 0x7fff) << 16);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
a += (c >> 15);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
return a;
}
private static byte[] gspassenc(byte [] pass)
{
int a = 0;
int num = 0x79707367; // gspy
int len = pass.Length;
byte[] newPass = new byte[len];
for (int i = 0; i < len; ++i)
{
num = gslame(num);
a = num % 0xFF;
newPass[i] = (byte)(pass[i] ^ a);
}
return newPass;
}
}

Categories