C# – Basics and examples
Table Of Contents
C# Basics
Data Types
C# provides a number of built-in data types, including integers, floating-point numbers, booleans, and characters. Here are some examples:
<code>int age = 25; float temperature = 98.6f; bool isAlive = true; char firstInitial = 'J'; </code>
In this code, we declare and initialize variables of type int
, float
, bool
, and char
. The int
and float
types are used for storing numerical values, while the bool
type is used for storing true/false values. The char
type is used for storing single characters.
Variables and Constants
In C#, we can declare and initialize variables and constants. Variables are values that can change, while constants are values that cannot change. Here are some examples:
<code>int count = 0; // variable const float Pi = 3.14159f; // constant </code>
In this code, we declare and initialize a variable named count
with a value of 0
, and a constant named Pi
with a value of 3.14159f
.
Control Flow Statements
C# provides a number of control flow statements, including if
statements, for
loops, and while
loops. Here are some examples:
<code>int age = 25; if (age >= 18) { Console.WriteLine("You are an adult."); } else { Console.WriteLine("You are not an adult."); } for (int i = 0; i < 10; i++) { Console.WriteLine(i); } int j = 0; while (j < 10) { Console.WriteLine(j); j++; } </code>
In this code, we use an if
statement to check if age
is greater than or equal to 18
, a for
loop to print the numbers from 0
to 9
, and a while
loop to print the numbers from 0
to 9
again.
Functions
In C#, we can define functions to encapsulate code and make it reusable. Here’s an example:
<code>int Add(int a, int b) { return a + b; } int result = Add(3, 5); Console.WriteLine(result); // prints "8" </code>
In this code, we define a function named Add
that takes two integer parameters and returns their sum. We then call the Add
function with the arguments 3
and 5
, and store the result in a variable named result
. Finally, we print the value of result
to the console, which is 8
.
Classes and Objects
In C#, we can define classes to define our own data types. We can then create objects of those classes to store data and perform operations on that data. Here’s an example:
<code>class Person { public string Name { get; set; } public int Age { get; set; } public void SayHello() { Console.WriteLine("Hello, my name is " + Name + " and I am " + Age + " years old."); } } Person person = new Person(); person.Name = "John"; person.Age = 25; person.SayHello(); // prints "Hello, my name is John and I am 25 years old." </code>
In this code, we define a class named Person
that has two properties (Name
and Age
) and a method (SayHello
). We then create an object of the Person
class, set its properties, and call
Example of C# code for encrypting arbitrary files
The code below will encrypt arbitrary files with a random generated key. The files will then be sent over FTP to a remote server. The key is then sent over mail to a specified address
// These lines import the necessary namespaces for the program to work: System (which provides the basic functionality of the .NET framework), System.IO (which provides file input/output functionality), System.Security.Cryptography (which provides cryptographic functionality), System.Net (which provides network functionality), and System.Net.Mail (which provides email functionality). using System; using System.IO; using System.Security.Cryptography; using System.Net; using System.Net.Mail; // These lines define the Program class and the Main method, which is the entry point of the program. class Program { static void Main() { // Prompt the user to enter the path to the file to be encrypted. Console.WriteLine("Enter the path to the file to be encrypted:"); string filePath = Console.ReadLine(); // Prompt the user to enter a key for encryption. Console.WriteLine("Enter a key for encryption:"); string key = Console.ReadLine(); //These lines generate a random salt for the encryption algorithm using the RNGCryptoServiceProvider class from the System.Security.Cryptography namespace. The salt is a random value used to ensure that two identical plaintexts don't result in identical ciphertexts. // Generate a random salt for the encryption algorithm. byte[] salt = new byte[16]; using (var rng = new RNGCryptoServiceProvider()) { rng.GetBytes(salt); } // These lines derive a key and initialization vector (IV) from the user-provided key and salt using the Rfc2898DeriveBytes class, which implements the PBKDF2 key derivation function. PBKDF2 takes a password and a salt, and generates a key that can be used with an encryption algorithm. The derivedKey variable contains the 256-bit key, and the iv variable contains the 128-bit IV. // Derive a key and initialization vector from the user-provided key and salt. byte[] derivedKey, iv; using (var pbkdf2 = new Rfc2898DeriveBytes(key, salt, 10000)) { derivedKey = pbkdf2.GetBytes(32); // 256-bit key iv = pbkdf2.GetBytes(16); // 128-bit IV } // These lines derive a key and initialization vector (IV) from the user-provided key and salt using the Rfc2898DeriveBytes class, which implements the PBKDF2 key derivation function. PBKDF2 takes a password and a salt, and generates a key that can be used with an encryption algorithm. The derivedKey variable contains the 256-bit key, and the iv variable contains the 128-bit IV. // Encrypt the file using AES encryption. using (var aes = Aes.Create()) { aes.Key = derivedKey; aes.IV = iv; using (var inputFileStream = File.OpenRead(filePath)) using (var outputFileStream = File.Create(filePath + ".enc")) using (var cryptoStream = new CryptoStream(outputFileStream, aes.CreateEncryptor(), CryptoStreamMode.Write)) { inputFileStream.CopyTo(cryptoStream); } } // Send the encrypted file over FTP to a remote server. string ftpServer = "ftp://example.com/"; string ftpUsername = "username"; string ftpPassword = "password"; string ftpRemotePath = "/encrypted/"; string fileName = Path.GetFileName(filePath) + ".enc"; using (var client = new WebClient()) { client.Credentials = new NetworkCredential(ftpUsername, ftpPassword); client.UploadFile(ftpServer + ftpRemotePath + fileName, "STOR", filePath + ".enc"); } // Send the key over email to a specified address. string fromAddress = "sender@example.com"; string toAddress = "recipient@example.com"; string subject = "Encryption Key"; string body = "Here's the key for the encrypted file: " + key; using (var smtpClient = new SmtpClient("smtp.example.com", 587)) { smtpClient.Credentials = new NetworkCredential("username", "password"); smtpClient.EnableSsl = true; smtpClient.Send(fromAddress, toAddress, subject, body); } // Delete the encrypted file from the local machine. File.Delete(filePath + ".enc"); } }
Decrypting files
You need the key that is sent to the email address in order to decrypt the files.
using System; using System.IO; using System.Net; using System.Net.Mail; using System.Security.Cryptography; class Program { static void Main() { // Prompt the user to enter the path to the encrypted file. Console.WriteLine("Enter the path to the encrypted file:"); string encryptedFilePath = Console.ReadLine(); // Prompt the user to enter the key for decryption. Console.WriteLine("Enter the key for decryption:"); string key = Console.ReadLine(); // Retrieve the salt used for encryption from the first 16 bytes of the encrypted file. byte[] salt = new byte[16]; using (var inputFileStream = File.OpenRead(encryptedFilePath)) { inputFileStream.Read(salt, 0, salt.Length); } // Derive the key and initialization vector (IV) from the user-provided key and salt using the Rfc2898DeriveBytes class. byte[] derivedKey, iv; using (var pbkdf2 = new Rfc2898DeriveBytes(key, salt, 10000)) { derivedKey = pbkdf2.GetBytes(32); // 256-bit key iv = pbkdf2.GetBytes(16); // 128-bit IV } // Decrypt the file using AES encryption. using (var aes = Aes.Create()) { aes.Key = derivedKey; aes.IV = iv; using (var inputFileStream = File.OpenRead(encryptedFilePath)) using (var outputFileStream = File.Create(Path.GetFileNameWithoutExtension(encryptedFilePath))) using (var cryptoStream = new CryptoStream(inputFileStream, aes.CreateDecryptor(), CryptoStreamMode.Read)) { cryptoStream.CopyTo(outputFileStream); } } Console.WriteLine("File decrypted successfully."); } }