Skip to content

AsnWriter should provide an API to write non-normalized integers #27079

Closed
@filipnavara

Description

@filipnavara

Currently AsnWriter offers couple of methods for writing integers represented using ReadOnlySpan<byte>:

public void WriteInteger(ReadOnlySpan<byte> value);
public void WriteIntegerUnsigned(ReadOnlySpan<byte> value);
public void WriteInteger(Asn1Tag tag, ReadOnlySpan<byte> value);
public void WriteIntegerUnsigned(Asn1Tag tag, ReadOnlySpan<byte> value);

These methods throw CryptographicException when the value is not properly padded, ie. the integer starts with a zero, followed by a byte < 0x80.

Nearly all of the usages of these methods use extra code to strip this padding. Examples include:

https://github.com/dotnet/corefx/blob/1e2dfe2c2ef9ca04a46e38f6645021e5da39ffe3/src/System.Security.Cryptography.Algorithms/src/Internal/Cryptography/Helpers.cs#L109-L144

https://github.com/dotnet/corefx/blob/85c4b4bdae8095c3681d4cd91e00894f26c3baf6/src/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/CertificateRequest.cs#L610-L630

https://github.com/dotnet/corefx/blob/5812dcbef2cde02a8213139085deefe666376f2c/src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Rfc3161TimestampRequest.cs#L259-L283

I found no usages of WriteInteger[Unsigned] that rely on the padding check except for the unit tests that check that specific behavior.

I propose that these WriteInteger[Unsigned] overloads should strip the padding instead of throwing an exception on it. Alternatively, if there's a compelling reason to keep the current API with the checks, offer a different API that does the normalization.

Furthermore, the WriteIntegerUnsigned overloads above are not exposed from AsnSerializer. If the normalization is enabled in some way it should be available for the serializer as well.

Of the three normalization code snippets above two of them had bugs, which were spotted only after careful review (one of them landed in master, the other was spotted during pull request review). This suggests that it's a bit of code that's prone to be written incorrectly and a good API should ideally prevent the users from writing incorrect code.

/cc @bartonjs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions