OID Conversion






2.09/5 (6 votes)
Convert OID numbers from a byte array to a string and vice versa.
Introduction
What is an object identifier? Object identifiers are, basically, strings of numbers. They are allocated in a hierarchical manner, so that, for instance, the authority for "1.2.3" is the only one that can say what "1.2.3.4" means. They are used in a variety of protocols.
The formal definition of OIDs comes from the ITU-T recommendation X.208 (ASN.1), which is available from the ITU (if you have your checkbook handy). The definition of OID is in chapter 28; the assignment of the "top of the tree" is given in appendixes B, C, and D.
The encodings - how you can transfer an OID as bits on the wire - is defined in X.209.
What object identifiers exist? Millions and millions.... remember, once you have a valid OID that is yours to handle, you will automatically have the right to assign any OID that starts off with the digits in your OID. For example, the Internet OID is 1.3.6.1.
In the code attached, you can find functions for converting OID numbers from a byte
array to a string
and vice versa.
The Code
public byte[] OidStringToByteArray(string oid)
{
string[] split = oid.Trim(' ','.').Split('.');
List retVal = new List();
for (int a = 0, b = 0, i = 0; i < split.Length; i++)
{
if (i == 0)
a = int.Parse(split[0]);
else if (i == 1)
retVal.Add(40 * a + int.Parse(split[1]));
else
{
b = int.Parse(split[i]);
if (b < 128)
retVal.Add(b);
else
{
retVal.Add(128+(b/128));
retVal.Add(b%128);
}
}
}
byte[] temp = new byte[retVal.Count];
for (int i = 0; i < retVal.Count; i++)
temp[i] = (byte)retVal[i];
return temp;
}
public string OidByteArrayToString(byte[] oid)
{
StringBuilder retVal = new StringBuilder();
for (int i = 0; i < oid.Length; i++)
{
if (i == 0)
{
int b = oid[0] % 40;
int a = (oid[0] - b) / 40;
retVal.AppendFormat("{0}.{1}", a, b);
}
else
{
if (oid[i] < 128)
retVal.AppendFormat(".{0}", oid[i]);
else
{
retVal.AppendFormat(".{0}",
((oid[i] - 128) * 128) + oid[i + 1]);
i++;
}
}
}
return retVal.ToString();
}