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

CSharp examples for System.Security.Cryptography:ASN

Description

ASN.1 DER length decoder.

Demo Code


using Microsoft.Win32;
using System.Text;
using System.IO;/*from   w  w w.  ja va 2s. co  m*/
using System;

public class Main{
        /// <summary>
        /// ASN.1 DER length decoder.
        /// </summary>
        /// <param name="bt">Source stream.</param>
        /// <param name="isIndefiniteLength">Output parameter.</param>
        /// <returns>Output length.</returns>
        public static long DerLengthDecode(Stream bt, ref bool isIndefiniteLength)
        {
              isIndefiniteLength = false;
            long length = 0;
            byte b;
            b = (byte) bt.ReadByte();
            if ((b & 0x80)==0)
            {
                length = b;
            }
            else
            {
                long lengthBytes = b & 0x7f;
                if (lengthBytes == 0)
                {
                              isIndefiniteLength = true;
                              long sPos = bt.Position;
                    return -2; // Indefinite length.
                }
                length = 0;
                while (lengthBytes-- > 0)
                {
                    if ((length >> (8 * (4 - 1))) > 0) // 4: sizeof(long)
                    {
                        return -1; // Length overflow.
                    }
                    b = (byte) bt.ReadByte();
                    length = (length << 8) | b;
                }
            }
            return length;
        }
}

Related Tutorials