Home > Software Development > Encrypt and Decrypt Password in C#?

Encrypt and Decrypt Password in C#?

November 12th, 2012 Leave a comment Go to comments

I just spent a little time playing with C# on password encryption. Here is a sample code I wrote to get myself familiar with related APIs. Overall it’s pretty straight forward – it first encrypts a clear text to an encrypted Base64 encoded string, then reverses it.

using System;
using System.Security.Cryptography;
using System.Text;

namespace DoubleCloud
    class ProtectPassword
        static void Main(string[] args)
            // encryption
            string clearText = "doublecloud.org";
            byte[] clearTextBytes = Encoding.Unicode.GetBytes(clearText);

            byte[] encryptedTextBytes = ProtectedData.Protect(clearTextBytes, null, DataProtectionScope.CurrentUser);
            string encryptedTextBase64 = Convert.ToBase64String(encryptedTextBytes);
            System.Console.WriteLine("Encrypted:" + encryptedTextBase64);

            // decrypt what's been encrypted
            string encText = encryptedTextBase64;
            byte[] encTextBytes = Convert.FromBase64String(encText);

            byte[] decryptedBytes = ProtectedData.Unprotect(encTextBytes, null, DataProtectionScope.CurrentUser);
            string decryptedText = Encoding.Unicode.GetString(decryptedBytes);
            System.Console.WriteLine("Decrypted:" + decryptedText);


As I ran the program for several times, I noticed that the encrypted string of each run was different. This differs from the one way hash in which a password is always hashed to a same binary string. If you hash a random password and get the same known hashed string, the random password is for sure the password, meaning you break it. I guess the .Net encryption APIs may factor in the time it runs. It seems a better solution than hashing in protecting passwords.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

BTW, one trick I learned with Visual Studio is that if you want a Console Application to pause in the Dos Window, you can simply use CTRL + F5 to run it. After the normal print out, it adds one line says “Press any key to continue …” and pause there. If you use the F5, the Dos Windows disappears before you can see much. The other way is to set a breakpoint on the last line of execution code and run in debug mode. Either way works.

  1. November 12th, 2012 at 01:18 | #1

    Encrypt and Decrypt Password in C#? http://t.co/zLhEt1bZ via @sjin2008

  2. November 12th, 2012 at 01:57 | #2

    Encrypt and Decrypt Password in C#? (DoubleCloud) http://t.co/LspzvJfp

  1. No trackbacks yet.