.NET has native class in System.Security namespace, called: SecureString
Using of this class could be useful if we don’t want to send strings over our private/public network in plain text format. Of course, this is not a 100% secure solution. It can be decoded, but at least we’re not sending plain text passwords in our network.
If I need hash of a string (that cannot be decoded), I can use this simple snippet as can be seen as 3rd method.
I create a static class with static methods, so I can use it anywhere in my code easily.
static class _SecureString { public static SecureString ENCODING(string _string) { SecureString secure = new SecureString(); foreach (char c in _string) { secure.AppendChar(c); } return secure; } public static string DECODING(SecureString _secureString) { IntPtr valuePtr = IntPtr.Zero; try { valuePtr = Marshal.SecureStringToGlobalAllocUnicode(_secureString); return Marshal.PtrToStringUni(valuePtr); } finally { Marshal.ZeroFreeGlobalAllocUnicode(valuePtr); } } public static string HASH_GENERATE(string _inputString) { byte[] data = Encoding.UTF8.GetBytes(_inputString); using (SHA512 shaM = new SHA512Managed()) { return Convert.ToBase64String(shaM.ComputeHash(data)); } } }
Using the HASH could be useful, when we store passwords in database and make all authentications from there. We generate the password hash from a simple string and store the hashed result string in the database. SHA512 is strong enough. Next time when a user wants to authenticate, we again generate a hash from his/her typed-in password and compare it to the stored one. In this case we are not sending and receiving any readable password text in the network. Fast and simple solution.