public static void Encode(DEREncodingASN1Type type, byte[] value, Stream s) { s.WriteByte((byte)type); int valueLength = value.Length; if (valueLength < 128) { s.WriteByte((byte)valueLength); } else { byte[] bytesValueLength = BitConverter.GetBytes(valueLength); Array.Reverse(bytesValueLength); for (int i = 0; i < bytesValueLength.Length; i++) { if (bytesValueLength[i] != 0) { s.WriteByte((byte)(0x80 | (bytesValueLength.Length - i))); s.Write(bytesValueLength, i, bytesValueLength.Length - i); break; } } } s.Write(value, 0, valueLength); }
public static DEREncoding Decode(Stream s) { DEREncodingASN1Type type = (DEREncodingASN1Type)s.ReadByte(); int valueLength; int length1 = s.ReadByte(); if (length1 > 127) { int numberLenBytes = length1 & 0x7F; byte[] valueBytes = new byte[4]; s.Read(valueBytes, 0, numberLenBytes); switch (numberLenBytes) { case 1: valueLength = valueBytes[0]; break; case 2: Array.Reverse(valueBytes, 0, 2); valueLength = BitConverter.ToInt16(valueBytes, 0); break; case 3: Array.Reverse(valueBytes, 0, 3); valueLength = BitConverter.ToInt32(valueBytes, 0); break; case 4: Array.Reverse(valueBytes, 0, 4); valueLength = BitConverter.ToInt32(valueBytes, 0); break; default: throw new IOException("DER encoding length not supported."); } } else { valueLength = length1; } byte[] value = new byte[valueLength]; s.Read(value, 0, valueLength); return(new DEREncoding(type, value)); }
private DEREncoding(DEREncodingASN1Type type, byte[] value) { _type = type; _value = value; }