Skip to content

API proposal: Add ReadOnlySpan<byte> to IDataProtector (un)Protect  #44758

Open
@KLuuKer

Description

@KLuuKer

Background and Motivation

Add ReadOnlySpan<byte> overrides so consumer apps are able to avoid a extra array allocation+blockbuffer.copy every time they try to protect\unprotect data.

Proposed API

namespace Microsoft.AspNetCore.DataProtection;

public interface IDataProtector : IDataProtectionProvider
{
+    byte[] Protect(ReadOnlySpan<byte> plaintext);

+    byte[] Unprotect(ReadOnlySpan<byte> protectedData);
}

Usage Examples

var buffer = new ArrayBufferWriter<byte>();

// write some data to buffer
var blob = new Data { Some = "Payload" };
MessagePackSerializer.Serialize(buffer, blob);

IDataProtector protector = provider.CreateProtector("demo");
return protector.Protect(buffer.WrittenSpan);

Alternative Designs

namespace Microsoft.AspNetCore.DataProtection;

public interface IDataProtector : IDataProtectionProvider
{
+    byte[] Protect(ReadOnlySpan<byte> plaintext) => this.Protect(plaintext.ToArray())

+    byte[] Unprotect(ReadOnlySpan<byte> protectedData) => this.Unprotect(protectedData.ToArray())
}

Risks

All of the existing protector implementations have to be changed to implement this change.
We could also have a default interface implementation to prevent it breaking to aggressively.

Performance impact should be minimal, and actually open the possibility for apps to avoid a unnecessary array copy, if people use the api correctly

Metadata

Metadata

Assignees

No one assigned

    Labels

    Perfapi-ready-for-reviewAPI is ready for formal API review - https://github.com/dotnet/apireviewsarea-dataprotectionIncludes: DataProtection

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions