Solved

How to encrypt a password based on a string

Posted on 2014-02-12
2
565 Views
Last Modified: 2014-02-13
Hi

I'm using .NET 4 ASP.NET, the membership is the default settings, I have not made any changes to any settings

How to I encrypt the text value so that the password looks something like this

h2Ipfv8rXHQMtrn1X7dVydPAmP0=

I think thats sha1, hashed

can someone please send me the code to encrypt text to a password (like the password used in the aspnet_Membership table)

I know .net code takes care of that, but I want to check the password has not been used before, I have another table that I look at for that.

So the user enters a new password, I want to convert the string to a password ("encrypted")  and before it gets saved to the aspnet_Membership table, I want to check that in another table, if it exist save it in the aspnet_Membership, else dont save it

thanks
0
Comment
Question by:mousemat24
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 20

Accepted Solution

by:
Daniel Van Der Werken earned 250 total points
ID: 39853970
Okay, this is a pretty important topic, and a simple answer here isn't really going to suffice for true security. You should do research on this. Ideally, you want to salt the hash and use something like PBKDF2 or SCrypt or BCrypt. SHA-hashes really aren't sufficient for true security any longer.

Here is a simple SHA mechanism because you asked:

This is a simple, unsalted example using the password of password as below:
using System.Security.Cryptography;
HashAlgoritym sha1 = new SHA1CryptoServiceProvider();
byte[] bytePWD = sha1.ComputeHash(Encoding.Unicode.GetBytes(password));
string hashedPWD = Convert.ToBase64String(bytePWD);

Open in new window

This will get you started, but I do NOT RECOMMEND you use this in a production environment. Again, so the research and use a salted PBKDF2 hash or use SCrypt or BCrypt.
0
 
LVL 7

Assisted Solution

by:XGIS
XGIS earned 250 total points
ID: 39853986
Hello mousemat24.

Poeple using passwords the same as each other should not be an issue.
If you want to disguise the duplicate passwords that encrypt the same, then you need to add some salt. eg a random prefix of 3-4 characters that totally changes the encrypted hashed result.

eg password1 = h2Ipfv8rXHQMtrn1X7dVydPAmP0=

salt + password1  = hjgkibt9ods8n8w7ynshkjhkjhd

word of advice.. dont "play" with encryption and security... A bunch of jumbled characters looks safe but it is not always the case..  Note also that "ENCODING" is not encryption, which is stated in some examples you will find.

Here are some codes I have used.. but there is no guarantee it will work.  Your best bet is to get an existing "ASP.NET Membership" resource that is "ready to go".. Avoid reinventing the wheel,  it takes enough time to get a handle on membership.

A great starter is MYWSAT.

here is the code sample (which does NOT do salt)

       var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^*()_+|';[]}{=-:?`";
        var random = new Random();
        var result = new string(
            Enumerable.Repeat(chars, 12)
                      .Select(s => s[random.Next(s.Length)])
                      .ToArray());
        tbKey.Text = result.ToString();



      

    }

    protected void Decrypt(object sender, EventArgs e)
    {

        TripleDES threedes = new TripleDESCryptoServiceProvider();

        threedes.Key = StringToByte(tbKey.Text, 24); // convert to 24 characters - 192 bits
        threedes.IV = StringToByte("12345678");
        byte[] key = threedes.Key;
        byte[] IV = threedes.IV;

        //ICryptoTransform encryptor = threedes.CreateEncryptor(key, IV);

        MemoryStream msEncrypt = new MemoryStream();
        //CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

        //// Write all data to the crypto stream and flush it.
        //csEncrypt.Write(StringToByte(this.tbMessage.Text), 0, StringToByte(this.tbMessage.Text).Length);
        //csEncrypt.FlushFinalBlock();

        //// Get the encrypted array of bytes.
        byte[] encrypted = msEncrypt.ToArray();

        //this.tbEncrypt.Text = ByteToString(encrypted);

        ICryptoTransform decryptor = threedes.CreateDecryptor(key, IV);

        // Now decrypt the previously encrypted message using the decryptor
        MemoryStream msDecrypt = new MemoryStream(encrypted);
        CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

        this.Label5.Text = ByteToString(csDecrypt);
    }

    protected void Encrypt_Click(object sender, EventArgs e)
    {
        
        try
        {
            TripleDES threedes = new TripleDESCryptoServiceProvider();

            threedes.Key = StringToByte(tbKey.Text, 24); // convert to 24 characters - 192 bits
            threedes.IV = StringToByte("12345678");
            byte[] key = threedes.Key;
            byte[] IV = threedes.IV;

            ICryptoTransform encryptor = threedes.CreateEncryptor(key, IV);

            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

            // Write all data to the crypto stream and flush it.
            csEncrypt.Write(StringToByte(this.tbMessage.Text), 0, StringToByte(this.tbMessage.Text).Length);
            csEncrypt.FlushFinalBlock();

            // Get the encrypted array of bytes.
            byte[] encrypted = msEncrypt.ToArray();

            this.tbEncrypt.Text = ByteToString(encrypted);

            ICryptoTransform decryptor = threedes.CreateDecryptor(key, IV);

            // Now decrypt the previously encrypted message using the decryptor
            MemoryStream msDecrypt = new MemoryStream(encrypted);
            CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

            this.tbDecrypt.Text = ByteToString(csDecrypt);
            ExcecuteInsert(); 
        }
        catch (Exception ex)
        {
            this.tbEncrypt.Text = ex.Message.ToString();
            
        }
    }
    public static byte[] StringToByte(string StringToConvert)
    {

        char[] CharArray = StringToConvert.ToCharArray();
        byte[] ByteArray = new byte[CharArray.Length];
        for (int i = 0; i < CharArray.Length; i++)
        {
            ByteArray[i] = Convert.ToByte(CharArray[i]);
        }
        return ByteArray;
    }
    public static byte[] StringToByte(string StringToConvert, int length)
    {

        char[] CharArray = StringToConvert.ToCharArray();
        byte[] ByteArray = new byte[length];
        for (int i = 0; i < CharArray.Length; i++)
        {
            ByteArray[i] = Convert.ToByte(CharArray[i]);
        }
        return ByteArray;
    }
    public static string ByteToString(CryptoStream buff)
    {
        string sbinary = "";
        int b = 0;
        do
        {
            b = buff.ReadByte();
            if (b != -1) sbinary += ((char)b);

        } while (b != -1);
        return (sbinary);
    }
    public static string ByteToString(byte[] buff)
    {
        string sbinary = "";
        for (int i = 0; i < buff.Length; i++)
        {
            sbinary += buff[i].ToString("X2"); // hex format
        }
        return (sbinary);
    }

Open in new window

0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C# LINQ 5 43
Unprotect Visio drawing page in C# 4 22
.NET universe documentation poster 2 24
Ajax calendar distorted 4 19
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question