Skip to content

New ReadOnlySpan constructor for SecureString #44873

@xtqqczze

Description

@xtqqczze

Background and Motivation

In PowerShell project we sometimes create a SecureString from a string, e.g. in SecureStringCommands, by using the following pattern:

SecureString ss = new SecureString();
foreach (char t in password)
    ss.AppendChar(t);

Unfortunately, it appears that every call to AppendChar results in an allocation, which I suppose we could avoid with the following unsafe code:

SecureString ss;
fixed (char* pChars = &password.GetPinnableReference())
    ss = new SecureString(pChars, password.Length);

However the constructor SecureString(char* value, int length) creates a ReadOnlySpan to initialize from, so why not expose a constructor that takes a ReadOnlySpan?

Proposed API

namespace System.Security
{
+    public SecureString(ReadOnlySpan<char> value) {
+        Initialize(value);
+    }

Usage Examples

Alternative Designs

Risks

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationuntriagedNew issue has not been triaged by the area owner

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions