Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to encrypt a password based on a string

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

783 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