From 2e6b7d2714818494e094209d11e9184dd370ad18 Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Wed, 13 Oct 2021 17:54:05 +0700 Subject: DER sequence/set encoding opts. --- crypto/src/asn1/DerSequence.cs | 42 ++++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) (limited to 'crypto/src/asn1/DerSequence.cs') diff --git a/crypto/src/asn1/DerSequence.cs b/crypto/src/asn1/DerSequence.cs index 823fa869b..7940f6b5a 100644 --- a/crypto/src/asn1/DerSequence.cs +++ b/crypto/src/asn1/DerSequence.cs @@ -45,7 +45,7 @@ namespace Org.BouncyCastle.Asn1 { } - /* + /* * A note on the implementation: *

* As Der requires the constructed, definite-length model to @@ -53,22 +53,36 @@ namespace Org.BouncyCastle.Asn1 * ASN.1 descriptions given. Rather than just outputing Sequence, * we also have to specify Constructed, and the objects length. */ - internal override void Encode(DerOutputStream derOut) - { - // TODO Intermediate buffer could be avoided if we could calculate expected length - MemoryStream bOut = new MemoryStream(); - DerOutputStream dOut = new DerOutputStream(bOut); + internal override void Encode(DerOutputStream derOut) + { + if (Count < 1) + { + derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, Asn1OctetString.EmptyOctets); + return; + } - foreach (Asn1Encodable obj in this) - { - dOut.WriteObject(obj); - } + // TODO Intermediate buffer could be avoided if we could calculate expected length + MemoryStream bOut = new MemoryStream(); + DerOutputStream dOut = new DerOutputStream(bOut); - Platform.Dispose(dOut); + foreach (Asn1Encodable obj in this) + { + dOut.WriteObject(obj); + } + + dOut.Flush(); +#if PORTABLE byte[] bytes = bOut.ToArray(); + int length = bytes.Length; +#else + byte[] bytes = bOut.GetBuffer(); + int length = (int)bOut.Position; +#endif - derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, bytes); - } - } + derOut.WriteEncoded(Asn1Tags.Sequence | Asn1Tags.Constructed, bytes, 0, length); + + Platform.Dispose(dOut); + } + } } -- cgit 1.4.1