Solved

How to encrypt a password based on a string

Posted on 2014-02-12
2
539 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
2 Comments
 
LVL 19

Accepted Solution

by:
Daniel Van Der Werken earned 250 total points
Comment Utility
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
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

User art_snob (http://www.experts-exchange.com/M_6114203.html) encountered strange behavior of Android Web browser on his Mobile Web site. It took a while to find the true cause. It happens so, that the Android Web browser (at least up to OS ver. 2.…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

771 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now