Reputation: 11569
What would be the best way of converting a serial number from an X509certifiacte2 to a byte array (for storage) and back?
Upvotes: 1
Views: 3422
Reputation: 19033
You can use X509Certificate.GetSerialNumber. This method is accessible from X509Certificate2
as well.
Please, be wary about bytes order:
Returns the serial number of the X.509v3 certificate as an array of bytes in little-endian order.
Upvotes: 0
Reputation: 11569
public static String byteArrayToHex(byte[] data)
{
return BitConverter.ToString(data).Replace("-", string.Empty);
}
Upvotes: 0
Reputation: 217293
Here are two extension methods to convert a hexadecimal string to a byte array and back:
static byte[] ParseAsBytes(static string s)
{
return Enumerable.Range(0, s.Length / 2)
.Select(i => byte.Parse(s.Substring(i * 2, 2),
NumberStyles.AllowHexSpecifier))
.ToArray();
}
static string ToHexString(this byte[] buffer)
{
return string.Concat(buffer.Select(i => i.ToString("X2")));
}
Usage:
var input = "0001020304050607";
var bytes = input.ParseAsBytes();
// bytes == new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }
var result = bytes.ToHexString();
// result == "0001020304050607"
(For more efficient implementations, have a look the code of the internal System.Security.Util.Hex class using a tool like Reflector. These are used by the SerialNumber property to convert an internal byte[] field in the X509Certificate class to a hexadecimal string.)
Upvotes: 1
Reputation: 804
System.Text.Encoding handles converting strings to/from byte array. You should be able to do the following (assuming you're using ASCII for text encoding):
byte[] serial = System.Text.Encoding.ASCII.GetBytes(x509_cert.SerialNumber);
and to get the byte[] serial back into a string:
string x509_serial = System.Text.Encoding.ASCII.GetString(serial);
Upvotes: 0