Reputation: 4811
I'm working with a vendor who is supplying us with a sample AES encrypted message, we have a shared key, and I am just testing encryption/decription.
The decrypted message they are providing looks like this. Usually I would be expecting a string, but this is what they have provided:
d4 ee 84 87 f4 e2 0d c2 ef 07 e4 2c 9f b2 48 9e
I'm a little confused, what kind of notation is that?
My encryption/decrption method is using string as the input, and string as the output, but internally I am using a byte array:
byte[] plainBytes = Encoding.Unicode.GetBytes(plainText);
How can I convert that above input into a byte array?
Upvotes: 0
Views: 275
Reputation: 11514
After this code runs, theBytes
will contain your byte array:
byte[] theBytes = new byte[15];
string hexstring = "d4ee8487f4e20dc2ef07e42c9fb2489e";
for (int i = 0; i < 15; i++)
{
string thisByte = hexstring.Substring(i * 2, 2);
int intValue = Convert.ToInt16(thisByte, 16);
theBytes[i] = BitConverter.GetBytes(intValue)[0];
}
Upvotes: 1
Reputation: 12546
It is hexadecimal represantation of bytes
string bytes = "d4 ee 84 87 f4 e2 0d c2 ef 07 e4 2c 9f b2 48 9e";
var buf = bytes.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
if your hex string doesn't contain any spaces
string bytes = "d4ee8487f4e20dc2ef07e42c9fb2489e";
var buf = Regex.Matches(bytes, ".{2}").Cast<Match>()
.Select(x => Convert.ToByte(x.Value, 16)).ToArray();
You can even use System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary
class that can parse hex strings with or without spaces.
string bytes = "d4ee8487f4e20dc2ef07e42c9fb2489e";
var buf = SoapHexBinary.Parse(bytes).Value;
BTW:
You should note that every byte array can not be safely converted to string by Encoding.Unicode.GetString
in case you are using it.
var buf = new byte[] { 0xff, 0xff, 0xff };
string str = Encoding.Unicode.GetString(buf);
var buf2 = Encoding.Unicode.GetBytes(str);
buf2
will not be equal to buf
. To convert byte arrays to string, either use Convert.ToBase64String
or BitConverter.ToString
Upvotes: 3