Solved

How to encrypt a password based on a string

Posted on 2014-02-12
2
555 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 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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.…
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.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

861 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