diff options
Diffstat (limited to 'crypto/src/asn1/Asn1Object.cs')
-rw-r--r-- | crypto/src/asn1/Asn1Object.cs | 47 |
1 files changed, 31 insertions, 16 deletions
diff --git a/crypto/src/asn1/Asn1Object.cs b/crypto/src/asn1/Asn1Object.cs index 0cf89052b..523476f3d 100644 --- a/crypto/src/asn1/Asn1Object.cs +++ b/crypto/src/asn1/Asn1Object.cs @@ -1,4 +1,5 @@ using System; +using System.Diagnostics; using System.IO; namespace Org.BouncyCastle.Asn1 @@ -8,16 +9,31 @@ namespace Org.BouncyCastle.Asn1 { public override void EncodeTo(Stream output) { - Asn1OutputStream asn1Out = Asn1OutputStream.Create(output); - GetEncoding(asn1Out.Encoding).Encode(asn1Out); - asn1Out.FlushInternal(); + using (var asn1Out = Asn1OutputStream.Create(output, Ber, leaveOpen: true)) + { + GetEncoding(asn1Out.Encoding).Encode(asn1Out); + } } public override void EncodeTo(Stream output, string encoding) { - Asn1OutputStream asn1Out = Asn1OutputStream.Create(output, encoding); - GetEncoding(asn1Out.Encoding).Encode(asn1Out); - asn1Out.FlushInternal(); + using (var asn1Out = Asn1OutputStream.Create(output, encoding, leaveOpen: true)) + { + GetEncoding(asn1Out.Encoding).Encode(asn1Out); + } + } + + internal virtual byte[] InternalGetEncoded(string encoding) + { + var encodingType = Asn1OutputStream.GetEncodingType(encoding); + var asn1Encoding = GetEncoding(encodingType); + byte[] result = new byte[asn1Encoding.GetLength()]; + using (var asn1Out = Asn1OutputStream.Create(new MemoryStream(result, true), encoding)) + { + asn1Encoding.Encode(asn1Out); + Debug.Assert(result.Length == Convert.ToInt32(asn1Out.Position)); + } + return result; } public bool Equals(Asn1Object other) @@ -31,17 +47,17 @@ namespace Org.BouncyCastle.Asn1 /// <exception cref="IOException"> /// If there is a problem parsing the data, or parsing an object did not exhaust the available data. /// </exception> - public static Asn1Object FromByteArray( - byte[] data) + public static Asn1Object FromByteArray(byte[] data) { try { - MemoryStream input = new MemoryStream(data, false); - Asn1InputStream asn1 = new Asn1InputStream(input, data.Length); - Asn1Object result = asn1.ReadObject(); - if (input.Position != input.Length) - throw new IOException("extra data found after object"); - return result; + using (var asn1In = new Asn1InputStream(new MemoryStream(data, false), data.Length)) + { + Asn1Object result = asn1In.ReadObject(); + if (data.Length != asn1In.Position) + throw new IOException("extra data found after object"); + return result; + } } catch (InvalidCastException) { @@ -53,8 +69,7 @@ namespace Org.BouncyCastle.Asn1 /// <param name="inStr">The stream to parse.</param> /// <returns>The base ASN.1 object represented by the byte array.</returns> /// <exception cref="IOException">If there is a problem parsing the data.</exception> - public static Asn1Object FromStream( - Stream inStr) + public static Asn1Object FromStream(Stream inStr) { try { |