Question

I know it's a very silly problem as I'm still newbie.

Case :
String A : An output string from an encryption algorithm ( contains special characters )
String B : An output string from a hash function of String A ( contains special characters )

String C = A + "|" + B;

Problem :
I want to send them together from sender as String C so that I can Separate them in receiver
But String A & B may contains my separator "|"

So what do you suggest for me ? [ C# ]

Was it helpful?

Solution

One option would be to convert the output from the encryption tool (which hopefully returns raw bytes) into something like Base64 using the Convert.ToBase64String function, which should be safe to use "|" with. You lose out on space efficiency though, since Base64 wastes a good amount of space, but if you're dealing with small data you'd be ok.

If your encryption code does/can not return bytes, you'd have to convert it to bytes first using the appropriate encoder, i.e. Encoding.ASCII.GetBytes() if your string is in ASCII encoding.

//On the sender side
byte[] bytesA = Encoding.Default.GetBytes(A);
byte[] bytesB = Encoding.Default.GetBytes(B);
string encA = Convert.ToBase64String(bytesA);
string encB = Convert.ToBase64String(bytesB);

string C = encA + "|" + encB;

//On the receiver side
string[] parts = C.Split('|');
string A = Encoding.Default.GetString(Convert.FromBase64String(parts[0]));
string B = Encoding.Default.GetString(Convert.FromBase64String(parts[1]));

OTHER TIPS

You could enode the length of the first string in the first 3 characters. Then you use the length at the receiver to split the strings.

Not pretty, but works.

You could escape all pipes in string C

e.g.

  • define "=" as an escape character (you could use "\", which would be typical, but that will really mess with you since it's also an escape character for strings in c#)
  • replace all "=" in strings A and B with "=E" (E for Equals)
  • replace all "|" in strings A and B with "=P" (P for pipe)
  • join them together with the pipe

that will guarantee that you have no pipes in your string except the one joining A and B, but it will also let you split them on the other side and restore all existing pipes to their original places. Just reverse the order of operations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top