1

I have a helper function that will create a key or vector byte array for use in encryption methods. However I need a method that will take the byte[] and output the following representation of the values as a string from the byte array:

//I need the output to look like this:
    "{241, 253, 159, 1, 153, 77, 115, 174, 234, 157, 77, 23, 34, 14, 19, 182, 65, 94, 71, 166, 86, 84, 50, 15, 133, 175, 8, 162, 248, 251, 38, 161}"

I found this long hand method to use which technically works but it's a mess, especially with having to remove the last comma:

public static string ByteArrayToString(byte[] byteArray)
{
    var hex = new StringBuilder(byteArray.Length * 2);
    foreach (var b in byteArray)
        hex.AppendFormat("{0}, ", b);

    var output =  "{"+ hex.ToString() + "}";
    return output.Remove(output.Length - 3, 2); //yuck
}

This seems to be a highly asked question and I found several posts with solutions, but none of the suggestions output the string from the byte[] as I need above. I checked the following:

byte[] to hex string
How do you convert Byte Array to Hexadecimal String, and vice versa?

I used several of the parsing and LINQ examples but none of them output the byte array elements in the string as I needed above.

Is there a way to convert the actual values of the byte array returned from my helpwer method to the string format I need without using that hack of a method?

Community
  • 1
  • 1
atconway
  • 20,624
  • 30
  • 159
  • 229
  • Looks almost like JSON. If you can change format to real JSON ("[1,3,5]") than consider using either built in JSON serializer or JSON.Net one. – Alexei Levenkov Jul 12 '13 at 18:19
  • Actually this represents a `key` and `iv` values used in encryption and decryption method not JSON. It's already in the form of a `byte[]` so I need a method to deal with it in this form. – atconway Jul 12 '13 at 18:21
  • Check out http://msdn.microsoft.com/en-us/library/3a733s97.aspx – Timothy Shields Jul 12 '13 at 18:22
  • @TimothyShields - I already tried `var output = BitConverter.ToString(key);` and that did not produce the output I required. – atconway Jul 12 '13 at 18:24

1 Answers1

4

The very handy string.Join is the key to what you want.

public static string ByteArrayToString(byte[] byteArray)
{
    return "{" + string.Join(", ", byteArray) + "}";
}

If you're encoding for the computer, and not to pretty print to a human, base64 may be a better way to encode these bytes. It allows for much more compact encoding. E.g. this code:

public static string ByteArrayToString(byte[] byteArray)
{
    return Convert.ToBase64String(byteArray);
}

Produces the 44-character 8f2fAZlNc67qnU0XIg4TtkFeR6ZWVDIPha8Iovj7JqE= instead of the 142-character string you gave to encode these 32 bytes. And converting back to a byte[] is just Convert.FromBase64String(theString), instead of having to split and parse the long string yourself.

Update: Here's an option for compact code generation:

public static string ByteArrayEncoded(byte[] byteArray)
{
    return "Convert.FromBase64String(\""+Convert.ToBase64String(byteArray)+"\")";
}

Use like:

string generatedLine = "private static readonly byte[] defaultVector = "
                         + ByteArrayEncoded(myArray) + ";";
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • This is *exactly* what I was looking for with this question. Nice job! – atconway Jul 12 '13 at 18:25
  • So I could replace the following: `private byte[] defaultVector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };` with `private byte[] defaultVector = mJhaxtPOq+DqHvO9+QmR2oSlAKzna68L04BEeKL4u7Y=` I don't think the later would work as I've typed it though? – atconway Jul 12 '13 at 18:29
  • 2
    If the intent is to write C# code, the pretty print solution is probably the best. To use a base64-encoded string in that way, you'd do `private byte[] defaultVector = Convert.FromBase64String("mJhaxtPOq+DqHvO9+QmR2oSlAKzna68L04BEeKL4u7Y=");` But that makes it have to parse a string at runtime - not as nice as being declared for the compiler to know about. – Tim S. Jul 12 '13 at 18:33
  • +1. @atconway, you probably should have asked actual problem... `private byte[] defaultVector = Convert.FromBase64("mJhaxtPOq+DqHvO9+QmR2oSlAKzna68L04BEeKL4u7Y=")` would give much more compact generated code (and either version is not human readable anyway). – Alexei Levenkov Jul 12 '13 at 18:34
  • @TimS. - I like it explicitly declared as opposed to having to parse at runtime as well. Actually I use this in a test harness to produce these random keys for different apps. So the output is actually then copied and pasted into different apps. – atconway Jul 12 '13 at 18:44
  • If the base 64 encoding is the approach you want to take, I've added a method to my answer that'll help with that. – Tim S. Jul 12 '13 at 18:44