bool ValidateDEREncoding(Stream stream)
        {
            try
            {
                var asn1Stream  = new Org.BouncyCastle.Asn1.Asn1InputStream(stream);
                var certificate = asn1Stream.ReadObject();

                var derEncodedStream = new MemoryStream();
                var encoder          = new Org.BouncyCastle.Asn1.DerOutputStream(derEncodedStream);
                encoder.WriteObject(certificate);
                encoder.Flush();

                if (stream.Length != derEncodedStream.Length)
                {
                    return(false);
                }

                stream.Seek(0, SeekOrigin.Begin);
                derEncodedStream.Seek(0, SeekOrigin.Begin);

                for (int i = 0; i < stream.Length; i++)
                {
                    if (stream.ReadByte() != derEncodedStream.ReadByte())
                    {
                        return(false);
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }