|
using System;
using System.IO;
namespace LCLib.Asn1Processor
{
/// <summary>
/// Summary description for Util.
/// </summary>
public class Asn1Util
{
public static unsafe int BytePrecision(ulong value)
{
int i;
for (i=sizeof(ulong); i>0; --i)
if ((value >> (i-1)*8)!=0)
break;
return i;
}
public static int DERLengthEncode(Stream xdata, ulong length)
{
int i=0;
if (length <= 0x7f)
{
xdata.WriteByte((byte)length);
i++;
}
else
{
xdata.WriteByte((byte)(BytePrecision(length) | 0x80));
i++;
for (int j=BytePrecision((ulong)length); j>0; --j)
{
xdata.WriteByte((byte)(length >> (j-1)*8));
i++;
}
}
return i;
}
public static unsafe long DerLengthDecode(Stream bt)
{
long length = 0;
byte b;
b = (byte) bt.ReadByte();
if ((b & 0x80)==0)
{
length = b;
}
else
{
long lengthBytes = b & 0x7f;
if (lengthBytes == 0)
{
throw new Exception("Indefinite length.");
}
length = 0;
while (lengthBytes-- > 0)
{
if ((length >> (8*(sizeof(long)-1))) > 0)
throw new Exception("Length overflow.");
b = (byte) bt.ReadByte();
length = (length << 8) | b;
}
}
return length;
}
private Asn1Util()
{
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Liping Dai has worked in IT industry more than 17 years. He moved to Canada in 1996. After worked in Toronto for 4 years, he relocated to Silicon Valley. He has strong passion in the area of Multi-core/Multi thread programming, Parallel Computing, Image Reorganization, Secure Communication, and Mobile Device development.