Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to encrypt a password based on a string

Posted on 2014-02-12
2
Medium Priority
?
572 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 1000 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 1000 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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

715 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