CODEDIGEST
Home » Articles
Search
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
SecureString in .Net 2.0

By Satheesh Babu
Posted On Feb 20,2008
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: .Netframework
Print this article.

SecureString .Net 2.0

There are some disadvantages in using string if we want to store some important information’s like password, credit card numbers, bank pins, etc for some manipulations. The following list will help you understand it better.

1)      Storing in string makes GC to move around the memory leaving the information in many places.

2)      Storing in string is not encrypted and it is plain text.

3)      Storing in string we would never know when it will be deleted from memory.

4)      Storing in string in immutable which leads to have older versions and new versions of the string in the memory.

.Netframework 2.0 introduced a new class called SecureString which prevents the above problems. It is packed with the namespace System.Security. Let us see some of the advantages of using it.



1)      Storing in SecureString is pinned so GC cannot move to different place which confirms one copy of a string in the memory.

2)      Storing in SecureString is encrypted automatically.

3)      Storing in SecureString we can delete or GC can delete it.

4)      Can make it read-only and can prevent further modification.

Still using SecureString has some disadvantages like it hits the performance since it is encrypted. And also we can’t assign a text to a SecureString means text can be assigned only by character by character. See the code for better understanding.

 

System.Security.SecureString strpwd = new System.Security.SecureString();

strpwd.AppendChar('b');

strpwd.AppendChar('a');

strpwd.AppendChar('b');

strpwd.AppendChar('u');

strpwd.MakeReadOnly();

 

Appending a character after calling MakeReadOnly() function will throw InvalidOperatioException.

Retrieving the text stored in SecureString can be done by Interop marshalling.

 

IntPtr ptr = Marshal.SecureStringToBSTR(strpwd);

string plainPass = Marshal.PtrToStringUni(ptr);

MessageBox.Show(plainPass);

 

Include System.Runtime.InteropServices namespace for the above code to work.

Similar Articles

You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments