How to Write Secure Code in C#?

Secure Password Hashing in C#

Use secure password hashing algorithms to store passwords. Do not store passwords in plain text. Instead, use a secure password hashing algorithm to hash the password before storing it. This will make it more difficult for attackers to crack the password.

example

using System.Security.Cryptography;

public static string HashPassword(string password)
{
    // Create a new password hash algorithm.
    var hashAlgorithm = new SHA256Managed();

    // Generate a hash of the password.
    var hashedPassword = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(password));

    // Return the hash as a string.
    return Convert.ToBase64String(hashedPassword);
}

This code uses the SHA256 hashing algorithm to hash the password. The hash is then returned as a string.

User Input Validation in C#

Validate user input to prevent injection attacks. Always validate user input before using it. This will help prevent attackers from injecting malicious code into your application.

Example

public void ValidateUserInput(string input)
{
    // Check if the input contains any malicious characters.
    var regex = new Regex(@"[\"><';]");
    if (regex.IsMatch(input))
    {
        throw new Exception("Invalid input");
    }
}

This code uses a regular expression to check if the input contains any malicious characters. If it does, an exception is thrown.

Use parameterized SQL queries

Do not concatenate user input into SQL queries. Instead, use parameterized SQL queries. This will help prevent attackers from injecting malicious code into your database.

Example

public void ExecuteSqlQuery(string query, string param1, string param2)
{
    // Create a parameterized query.
    var sqlCommand = new SqlCommand(query);

    // Set the parameters.
    sqlCommand.Parameters.AddWithValue("param1", param1);
    sqlCommand.Parameters.AddWithValue("param2", param2);

    // Execute the query.
    sqlCommand.ExecuteNonQuery();
}

This code creates a parameterized SQL query and sets the parameters. The query is then executed.

Use cryptography to protect sensitive data

Encrypt sensitive data, such as passwords, credit card numbers, and social security numbers. This will help protect it from unauthorized access.

Example

public string EncryptData(string data, string key)
{
    // Create a new encryption algorithm.
    var encryptionAlgorithm = new AesManaged();

    // Generate a random IV.
    var iv = new byte[encryptionAlgorithm.IVLength];
    Random.NextBytes(iv);

    // Encrypt the data.
    var encryptedData = encryptionAlgorithm.Encrypt(data, iv);

    // Return the encrypted data.
    return Convert.ToBase64String(encryptedData);
}

This code uses the AesManaged encryption algorithm to encrypt the data. The key and IV are used to encrypt the data.

Use HTTPS to protect data in transit. When transmitting sensitive data over the network, use HTTPS. This will encrypt the data so that it cannot be intercepted by attackers.

Example

public void SendDataOverHttps(string data)
{
    // Create a new HTTPS request.
    var request = new HttpRequest("https://example.com");

    // Set the data to be sent.
    request.Content = new StringContent(data);

    // Send the request.
    request.GetResponse();
}

This code creates a new HTTPS request and sends the data over the secure connection.

Avoid hardcoding secrets in code

Do not hardcode secrets, such as passwords and database connection strings, in your code. Instead, store them in a secure location, such as an environment variable or a configuration file.

Example

// Do not do this.
public void ConnectToDatabase(string connectionString)
{
    // Connect to the database.
    var dbConnection = new SqlConnection(connectionString);
    dbConnection.Open();
}

// Do this instead.
public void ConnectToDatabase()
{
    // Get the connection string from an environment variable.
    var connectionString = Environment.GetEnvironmentVariable("DB_CONNECTION_STRING");

    // Connect to the database.
    var dbConnection = new SqlConnection(connectionString);
    dbConnection.Open();
}

The first code snippet hardcodes the database connection string in the code. This is not secure, as the connection string can be easily obtained by attackers. The second code snippet gets the connection string from an environment variable, which is a more secure way to store secrets.

Keep your code up to date

To keep your code up to date, you should regularly check for security updates and patches. You can do this by subscribing to the security notification lists of the software vendors that you use.


Similar Articles