encrypt string with salt c# in csharp

Here's an example code snippet for creating a salted hash of a string in C#:

main.cs
using System;
using System.Security.Cryptography;
using System.Text;

namespace SaltedHashExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string originalString = "password123";
            byte[] salt = GenerateSalt();

            // Compute hash of the password with the generated salt
            byte[] hash = ComputeHash(Encoding.UTF8.GetBytes(originalString), salt);

            Console.WriteLine("Original String: " + originalString);
            Console.WriteLine("Salt: " + Convert.ToBase64String(salt));
            Console.WriteLine("Hash: " + Convert.ToBase64String(hash));

            Console.ReadLine();
        }

        static byte[] GenerateSalt()
        {
            byte[] salt = new byte[16];

            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(salt);
            }

            return salt;
        }

        static byte[] ComputeHash(byte[] inputBytes, byte[] salt)
        {
            byte[] hashedBytes;

            using (var pbkdf2 = new Rfc2898DeriveBytes(inputBytes, salt, 10000))
            {
                hashedBytes = pbkdf2.GetBytes(32);
            }

            return hashedBytes;
        }
    }
}
1249 chars
49 lines

This code generates a random salt, then uses the Rfc2898DeriveBytes class with 10000 iterations to compute a hash of the input string and the salt. The resulting hash can be stored in a database or other storage medium, while the salt can be kept alongside it. Later, when a user tries to log in with their password, the same salt can be retrieved and the hash can be computed again to check if it matches the stored hash. This adds an extra layer of security, as even if an attacker gains access to the hash, they would still need the salt and the iteration count in order to crack the password.

gistlibby LogSnag