3

I'm trying to initialize SecureString and I need Char* for that. I tried to do it with block of unsafe code:

unsafe {
    char[] c = { 'A', 'B', 'C', 'D' };
    char* pointer = &(c[0]);
    SecureString sec = new SecureString(pointer, 4);
}

When try this I got this error:

Error: You can only take the address of an unfixed expression inside of a fixed statement initializer

3 Answers 3

5

Why not just loop through each char and use AppendChar?

string s = "Hello";
SecureString ss = new SecureString();

foreach(char c in s) ss.AppendChar(c);
Sign up to request clarification or add additional context in comments.

Comments

1

They say you shouldn't use that constructor.

You should do this.

char[] chars = { 'A', 'B', 'C', 'D' };
SecureString sec = new SecureString();
foreach (var c in chars) {
    sec.AppendChar(c);
}

Comments

0

As the accepted answer says, the accepted way is to use a loop and AppendChar. For convenience I've created the following extension method:

public static SecureString FromClearString(this SecureString secureString, string clearString)
{
    secureString.Clear();
    clearString.ToList().ForEach(secureString.AppendChar);
    secureString.MakeReadOnly();
    return secureString;
}

I use it as follows, eg:

var pwd = new SecureString();
await _security.LoginAsync("some.random.user", pwd.FromClearString("the.password"), Cts.Token);

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.