Click here to Skip to main content
15,884,298 members
Articles / Desktop Programming / Windows Forms
Article

Simple Password Manager Using System.Security

Rate me:
Please Sign up or sign in to vote.
4.81/5 (14 votes)
29 Sep 2006CPOL3 min read 107.5K   6.1K   84   11
Password Manager is a System.Security usage example using SecureString and SymmetricAlgorithms.

Password Manager Main Window

Introduction

The main goal of this application is to show how easy is to work with System.Security (SecureString, SymmetricAlgorithms) in a Windows Forms project. The application uses the SecurePasswordTextBox control made by Paul Glavich. SecurePasswordTextBox is a Windows Forms TextBox control that uses the .NET V2 SecureString class to store its contents. More details about this control can be found at Paul Glavich's blog.

Why do we need SecureStrings? Well, the MSDN documentation is very explicit on this, I will just quote it: "An instance of the System.String class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created, and it is not possible to predict when the instance will be deleted from computer memory. Consequently, if a String object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used, because your application cannot delete the data from computer memory." So, as a programmer, you must make sure that the sensitive data that you are dealing with in your applications like passwords are as much as possible protected. In my manager, I am receiving the password string as a SecureString with help from the Paul Glavich's control, and then I encrypt it with a symmetric algorithm (Rijndael) for storage and internal use. There is a moment when you can't protect the string, and that moment comes when the user wants to see his password in clear, or wants to paste it into a web page.

Using the code

There are two main classes that I use in my application; one is the CryptoCore class, with which I encrypt the serialized data to disk and the passwords while residing in memory. The class looks like this:

SymmetricAlgorithm helper class

For encryption and decryption, I am using a hard-coded Key and Initial Vector but you can change them by calling the SetBinaryKeys method. The second class is named Storage, and is used for the management of the encrypted files. You can create new files, and edit and save them to disk in a safe manner. The Storage class has a collection of entries, each entry holds a row from the listview. The Entry class looks like this:

Storage.Entry class

Let's take a look at the constructor of the Entry class:

C#
public Entry(string name, string user, SecureString password, 
             string site, string comment)
{
    this.name = name;
    this.user = user;
    this.comment = comment;
    this.site = site;
    using (CryptoCore cryptor = new CryptoCore())
    {
        IntPtr ptr = Marshal.SecureStringToBSTR(password);
        this.password = cryptor.EncryptString(Marshal.PtrToStringAuto(ptr));
        Marshal.ZeroFreeBSTR(ptr);
    }
}

So I am receiving a password of type SecureString from the form, and I encrypt it with Rijndael for storage in memory. After creating a new entry, we can add it to the Storage.Entries, and when you want to change the password, you can call the entry.UpdatePassword method.

C#
//ads a new entry in the Storage entry colection
Program.CurrentStorage.Entries.Add(
        new Storage.Entry(txtName.Text, txtUser.Text,
        txtPass.SecureText, txtSite.Text, txtComment.Text));

//updates a password with an Storage entry  
entry.UpdatePassword(txtPass.SecureText);

Next, I want to show you how the application can save or load a .sps file. An SPS file is a serialized Storage object, to load a file we have to deserialize (special constructor) and for saving a file we have to serialize:

C#
//decrypt and deserialize an object from disk
public Storage(string filePath)
{
    Entries = new List<Entry>();
    using (CryptoCore cryptor = new CryptoCore())
    {
        byte[] storage = cryptor.DecryptBuffer(File.ReadAllBytes(filePath));
        using (MemoryStream ms = new MemoryStream(storage))
        {
            BinaryFormatter bf = new BinaryFormatter();
            Entries = ((Storage)bf.Deserialize(ms)).Entries;
        }
    }
}

//save to disk an ecrypted serialized object
public void Serialize(string filePath)
{
    byte[] storage;
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, this);
        storage = ms.ToArray();
    }
    using (CryptoCore cryptor = new CryptoCore())
    {
        File.WriteAllBytes(filePath, cryptor.EncryptBuffer(storage));
    }
}

When we load an SPS file, the binding between the class and the listview control is very easy. Notice that the password is not shown here, there is another form that will help you change the password or view the credentials. Every time we open a new SPS file, it will load into a global Storage class, Program.CurrentStorage. Program.CurrentStorage is a static public member of the Program class.

C#
private void FillListView()
{
    listView.Items.Clear();
    for (int i = 0; i < Program.CurrentStorage.Entries.Count; i++)
    {
        ListViewItem itemName = new ListViewItem(
           Program.CurrentStorage.Entries[i].Name);
        itemName.Tag = i;
        itemName.SubItems.Add(Program.CurrentStorage.Entries[i].User);
        itemName.SubItems.Add(Program.CurrentStorage.Entries[i].Site);
        itemName.SubItems.Add(Program.CurrentStorage.Entries[i].Comment);
        listView.Items.Add(itemName);
    }
}

Points of interest

You have to download the code in order to understand the whole project; you can find examples of the new C# 2.0 features like generics and anonym delegates. This project does not implement a true password manager, because it lacks features like a main password for opening SPS files. It encrypts all SPS files with the same Rijndael key and so on. I will update the application with new features in time, if anyone finds it interesting.

History

  • 27.09.2006 - Version 1.0 Alpha.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO VeriTech.io
Romania Romania
Co-Founder at VeriTech.io. Passionate about software architecture, SOA, domain driven design, continuous integration, .NET and Javascript programming. I write on www.stefanprodan.com.

Comments and Discussions

 
Question123 Pin
Member 1000551923-Jun-13 1:54
Member 1000551923-Jun-13 1:54 
BugBuild Warnings Pin
Vasudevan Deepak Kumar15-Apr-13 7:51
Vasudevan Deepak Kumar15-Apr-13 7:51 
QuestionHow to insert security code on a web page Pin
kelejiwa20-Oct-09 1:35
kelejiwa20-Oct-09 1:35 
General2 small bugs Pin
itaymaya11-Nov-07 3:04
itaymaya11-Nov-07 3:04 
GeneralBug: select and del chars from password field Pin
Jerome Hordies3-Feb-07 3:15
Jerome Hordies3-Feb-07 3:15 
QuestionQuestion about the security of the string Pin
FrEaK_CH30-Sep-06 22:02
FrEaK_CH30-Sep-06 22:02 
AnswerRe: Question about the security of the string Pin
Stefan Prodan3-Oct-06 9:31
Stefan Prodan3-Oct-06 9:31 
You are rite but the Marshal.PtrToStringAuto is called inside the using, so the exposure time is under 1 millisecond. Sure it’s a vulnerability but is better then to keep the string all the run time in clear in memory. An improvement will be to serialize the SecureString without calling Marshal.PtrToStringAuto but I cant see how this can be done. Any suggestions?

http://stefanprodan.wordpress.com

QuestionRe: Question about the security of the string Pin
FrEaK_CH26-Oct-06 10:39
FrEaK_CH26-Oct-06 10:39 
AnswerRe: Question about the security of the string Pin
wout de zeeuw9-Jul-07 8:00
wout de zeeuw9-Jul-07 8:00 
AnswerRe: Question about the security of the string Pin
Member 1127378629-Nov-14 10:23
Member 1127378629-Nov-14 10:23 
GeneralRe: Question about the security of the string Pin
Member 1127378629-Nov-14 10:20
Member 1127378629-Nov-14 10:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.