0

How can I convert an input if 16 characters to a byte array with the following format. E.g. From textBox.Text = 4a4de6878247d37b to

byte[] esk_bytearr = { 0x4a, 0x4d, 0xe6, 0x87, 0x82, 0x47, 0xd3, 0x7b };

The method I'm using is not working and is the below.

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;
}

The byte array is an input to an decryption method using DES. The method is working but the decrypted message is different from when I use directly the esk_bytearr directly as parameter to decryption method. Thanks

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
user2307236
  • 665
  • 4
  • 19
  • 44

2 Answers2

1

What you're looking for is a method that converts from a hex string to a byte array. This has been answered a few times on stack overflow. For example:

How do you convert Byte Array to Hexadecimal String, and vice versa?

Community
  • 1
  • 1
Matt Varblow
  • 7,651
  • 3
  • 34
  • 44
1

Use a loop to go through each hex pair, converting it to a byte using Convert.ToByte specifying base16.

var hex = @"4a4de6878247d37b";
int hexLength = hex.Length;
byte[] bytes = new byte[hexLength / 2];
for (int i = 0; i < hexLength; i += 2)
{
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
}
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
  • This worked fine however I didn't really understand why the divisor in bytes[i / 2] and is there a way to automatically show the - sign after every 4 char the user enter like when you enter a product key or it would complicate things the populate the byte array as of the - sign. – user2307236 Dec 27 '13 at 18:04
  • You need to use the divisor in `bytes[i / 2]` because we're incrementing `i` by 2 each time - the hex string is of length 16, the byte array is length 8. If I understand you second question you want the user to enter a `-` after every 4. How to do that depends on what you're developing in, but when the user is done you can do a `hex = hex.Replace("-", "");` to get rid of them. – Dave Zych Dec 27 '13 at 18:08
  • Thanks for the explanation. Regarding the second question I mean that when the user type in the text the program automatically add a - sign after every four character. Eg. XXXX-XXXX-XXXX-XXXX, but the sign shall not be typed by the user it should be displayed automatically. – user2307236 Dec 27 '13 at 18:51
  • That's something that should be asked in a different question. – Dave Zych Dec 27 '13 at 18:54