Search code examples
.netencryptionsmtpnetworkcredentials

Storing passwords for external use


I'm currently employing the following hashing algorithm for storing encrypted text in my database:

public static string HashString(string inputString, string hashName)
{
    HashAlgorithm algorithm = HashAlgorithm.Create(hashName);
    byte[] hash = algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
    return Convert.ToBase64String(hash);
}

Basically, whenever the user inputs anything that needs to be encrypted, I call this function first, and then store the result in the database.

This has worked fine for me so far, because I've only been storing passwords, and I never need to actually output the content. Whenever a user wants to log in, I take the password they enter, encrypt it using the above function, and then compare the encrypted password with the value stored in the database.

The problem I'm now encountering is that, in certain cases, I do need to get the unhashed content. Basically, I want the clients to be able to store the username and password for their SMTP sending account, and I need to be able to then create the credential, using the following:

System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(login, pass)

Since the content stored in my database is encrypted using the HashString method, how can I send the password to the NetworkCredential, for use in my SmtpClient? Ideally I want to maintain the part about me not being able to obtain those passwords myself.


Solution

  • After reading a bit more in to this, I've realised that my question is not really well formulated. I'm going to mark this as answered, and upvote @GolezTrol's comment

    Note that hashing is not the same as encrypting. You can unencrypt something, but you can't unhash something. Hashing is irreversible. In addition, if you need the actual login and password to pass to that function, you will have to have it. You can't use it if you don't have the actual unencrypted password.

    since it helped steer me in the correct direction. I found Fundamental difference between Hashing and Encryption algorithms to be a useful reference for helping to guide me closer towards what I should be doing.