3

I have a byte[] which I need to encode in Base64 and return as SecureString. My current code is as follows:

        string privateString = Convert.ToBase64String(byteArray);
        SecureString result = new SecureString();
        foreach (char c in privateString)
        {
            result.AppendChar(c);
        }
        // wipe the byte array...

The problem is that calling Convert.ToBase64String is not secure as it creates a managed string which I can't destroy. Is there a secure way of doing this?

4
  • 1
    Microsoft does not recommend using SecureString github.com/dotnet/platform-compat/blob/master/docs/DE0001.md it's mentioned in their docs learn.microsoft.com/en-us/dotnet/api/… Commented Mar 17, 2020 at 11:47
  • 1
    No. The fact that you have a managed byteArray in memory somewhere containing the unencrypted contents, subject to being moved around in memory by GC and/or leaked through snapshots, already means there is little to no point involving SecureString. It is extremely difficult to make any effective use of and you typically shouldn't bother, as the offered security is illusory. Commented Mar 17, 2020 at 11:48
  • @JeroenMostert having a byte[] can be more useful than having a string, though; at least you can overwrite it when you're done (without needing to resort to unsafe hacks). But yeah; totally agree on SecureString etc Commented Mar 17, 2020 at 11:52
  • 1
    @MarcGravell: true, but then the question just becomes "where did you get that byte[]"? Unless it was created ex nihilo or from a crypto RNG call that made sure to track all of its buffers it's very likely to involve another path somewhere where memory was copied. Narrow is the gate to SecureString and wide is the path to insecure copies of data... (And that's before we consider the path out of SecureString of course, which is the main reason this thing doesn't really work.) Commented Mar 17, 2020 at 11:55

1 Answer 1

1

In terms of ways to encode base-64 data without an intermediate string: System.Buffers.Text.Base64. However! SecureString is not secure and should basically not be used now. Ever. It doesn't achieve any useful protection against any meaningful attack.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.