We had a string with byte array (hexadecimal) sequence, like: "0x65,0x31,0xb6,0x9e,0xaf,0xd2,0x39,0xc9,0xad,0x07,0x78,0x99,0x73,0x52,0x91,0xf5,0x93,0x1a,0x49,0xc6" and we need to recovery this sequence to byte array again.
We are using the following approach:
string byteSequence = "0x65,0x31,0xb6,0x9e,0xaf,0xd2,0x39,0xc9,0xad,0x07,0x78,0x99,0x73,0x52,0x91,0xf5,0x93,0x1a,0x49,0xc6";
byte[] myBytes = stringByteSequence.Split(',').Select(s => Convert.ToByte(s, 16)).ToArray();
This hash sequence it been generated by this sample:
string password = "<your password here>";
using (var cryptoProvider = System.Security.Cryptography.SHA1.Create())
{
byte[] passwordHash = cryptoProvider.ComputeHash(Encoding.UTF8.GetBytes(password));
string result = "new byte[] { " +
String.Join(",", passwordHash.Select(x => "0x" + x.ToString("x2")).ToArray())
+ " } ";
//...
// result = "new byte[] { 0x65,0x31,0xb6,0x9e,0xaf,0xd2,0x39,0xc9,0xad,0x07,0x78,0x99,0x73,0x52,0x91,0xf5,0x93,0x1a,0x49,0xc6 }"
//...
}
Is there a "cleaner" way to do this conversion?
Illustrative code, like:
byte[] myBytes = byteSequence.Which.Method.I.Can.Use.To.Convert.It.To.Byte.Array.Again?();
Original sample (referenced link above):
new BasicAuthAuthorizationUser
{
Login = "Administrator-2",
// Password as SHA1 hash
Password = new byte[]{0xa9,
0x4a, 0x8f, 0xe5, 0xcc, 0xb1, 0x9b,
0xa6, 0x1c, 0x4c, 0x08, 0x73, 0xd3,
0x91, 0xe9, 0x87, 0x98, 0x2f, 0xbb,
0xd3}
}
Our main idea:
new BasicAuthAuthorizationUser
{
Login = "Administrator-2",
// Password as SHA1 hash
Password = configuration["MY_ENV_VAR_NAME"].Split(',').Select(s => Convert.ToByte(s, 16)).ToArray();
}