ASN.1 DER length encoder. - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:ASN

Description

ASN.1 DER length encoder.

Demo Code


using Microsoft.Win32;
using System.Text;
using System.IO;/* ww w .ja  v  a2s .  c  om*/
using System;

public class Main{
        /// <summary>
        /// ASN.1 DER length encoder.
        /// </summary>
        /// <param name="xdata">result output stream.</param>
        /// <param name="length">source length.</param>
        /// <returns>result bytes.</returns>
        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;
        }
}

Related Tutorials