Link to home
Start Free TrialLog in
Avatar of brgdotnet
brgdotnetFlag for United States of America

asked on

How to check is a SecureString object is empty

I need to use the SecureString in my C# web application. However in looking at this class I don't see of a way to determine if a SecureString object is empty. If I know that the the String class has an IsNullOrEmpty(String) method however, SecureString does not. Does someone know of a way to determine in a SecureString object is an empty string?

 https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@MlandaT, I think that is what I stated in my post.
Avatar of Brady Kelly
Brady Kelly

But what about whitespace? i don't know, but surely SecureString can contain non-visible characters, such as a NewLine or something.
Hi Brady;

From Microsoft documentation
The SecureString class has no members that inspect, compare, or convert the value of a SecureString. The absence of such members helps protect the value of the instance from accidental or malicious exposure. Use appropriate members of the System.Runtime.InteropServices.Marshal class, such as the SecureStringToBSTR method, to manipulate the value of a SecureString object.
If you have any questions on this post please post a new question.

Thanks
I accept that the only way to check if a SecureString is truly empty is by its Length property, but my first comment was more a rhetorical question, to warn the OP that Length == 0 is not a safe replacement  for IsNullOrEmpty, although he should be using IsNullOrWhiteSpace. The following code shows the length of a practically useless SecureString to be correct: 10, but ten 0 chars is as good as empty, or at least would not pass IsNullOrWhiteSpace if it were a normal string:

    SecureString badPwd = new SecureString();
    for (var i = 0; i < 10; i++)
    {
        badPwd.AppendChar((char)0);
    }
    var badlen = badPwd.Length;
    var check = string.IsNullOrWhiteSpace(new string((char)0, 10));

Open in new window


badlen == 10, and check = false.