Showing posts with label C# Tutorials. Show all posts
Showing posts with label C# Tutorials. Show all posts

Encrypt and decrypt a folder in C#

Encrypt and decrypt a folder in C#

 In this article, we are going to discuss Encrypt and decrypting a folder in C#

Encrypt a folder in C#

Encrypting a folder in C# can be accomplished using a combination of the System.Security.Cryptography namespace and the System.IO namespace.

Here's an example implementation of how to encrypt a folder using the AES algorithm:

using System;
using System.IO;
using System.Security.Cryptography;
namespace EncryptClassInCSharp
{
    public class EncryptClass
    {
        public static void EncryptFolder(string sourceFolder, string destinationFolder, string password)
        {
            // Generate a random salt value
            byte[] salt = new byte[8];
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(salt);
            }

            // Create an AES encryption algorithm with the specified password and salt
            using (var aes = new AesManaged())
            {
                aes.KeySize = 256;
                aes.BlockSize = 128;
                var key = new Rfc2898DeriveBytes(password, salt, 1000).GetBytes(32);
                aes.Key = key;
                aes.IV = new byte[16];
                aes.Padding = PaddingMode.PKCS7;
                aes.Mode = CipherMode.CBC;

                // Create the destination folder if it doesn't exist
                if (!Directory.Exists(destinationFolder))
                {
                    Directory.CreateDirectory(destinationFolder);
                }

                // Encrypt each file in the source folder and copy it to the destination folder
                foreach (string filePath in Directory.GetFiles(sourceFolder))
                {
                    using (var fsIn = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        using (var fsOut = new FileStream(Path.Combine(destinationFolder, Path.GetFileName(filePath)), FileMode.Create, FileAccess.Write))
                        {
                            // Write the salt value to the beginning of the output file
                            fsOut.Write(salt, 0, salt.Length);

                            // Encrypt the file using the AES algorithm
                            using (var cryptoStream = new CryptoStream(fsOut, aes.CreateEncryptor(), CryptoStreamMode.Write))
                            {
                                fsIn.CopyTo(cryptoStream);
                            }
                        }
                    }
                }

            }
        }
    }
}

This implementation takes in the path of the source folder, the destination folder, and a password to use for the encryption. It generates a random salt value, creates an AES encryption algorithm with the specified password and salt, and then loops through each file in the source folder. For each file, it writes the salt value to the beginning of the output file, encrypts the file using the AES algorithm, and then writes the encrypted data to the output file in the destination folder.

Note that this implementation does not encrypt any subfolders within the specified source folder. If you need to encrypt subfolders as well, you will need to modify the implementation to recurse through all subfolders in the source folder.

To decrypt a folder that has been encrypted using the AES algorithm in C#, you can use the following implementation:


using System;
using System.IO;
using System.Security.Cryptography;
namespace EncryptClassInCSharp
{
    public class DecryptFolder
    {
        public static void DecryptFolder(string sourceFolder, string destinationFolder, string password)
        {
            // Loop through each file in the source folder
            foreach (string filePath in Directory.GetFiles(sourceFolder))
            {
                // Read the salt value from the beginning of the input file
                byte[] salt = new byte[8];
                using (var fsIn = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    fsIn.Read(salt, 0, salt.Length);
                }

                // Create an AES decryption algorithm with the specified password and salt
                using (var aes = new AesManaged())
                {
                    aes.KeySize = 256;
                    aes.BlockSize = 128;
                    var key = new Rfc2898DeriveBytes(password, salt, 1000).GetBytes(32);
                    aes.Key = key;
                    aes.IV = new byte[16];
                    aes.Padding = PaddingMode.PKCS7;
                    aes.Mode = CipherMode.CBC;

                    // Decrypt the input file using the AES algorithm and copy it to the destination folder
                    using (var fsIn = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        using (var cryptoStream = new CryptoStream(fsIn, aes.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            using (var fsOut = new FileStream(Path.Combine(destinationFolder, Path.GetFileName(filePath)), FileMode.Create, FileAccess.Write))
                            {
                                cryptoStream.CopyTo(fsOut);
                            }
                        }
                    }
                }
            }
        }
    }
}

This implementation takes in the path of the source folder, the destination folder, and the same password used to encrypt the folder. It loops through each file in the source folder and reads the salt value from the beginning of the input file. It then creates an AES decryption algorithm with the specified password and salt and decrypts the input file using the AES algorithm. Finally, it writes the decrypted data to the output file in the destination folder.

Note that this implementation assumes that all files in the source folder have been encrypted using the same password and salt value. If this is not the case, you will need to modify the implementation to read the salt value from each input file and use it to create the appropriate decryption algorithm.

C#

Find the Longest Common Prefix in C#

In this article, we will see the longest common prefix in C#

Problem Description

Write a function to find the longest common prefix string amongst all the arrays of strings in C#.

If there is no any common prefix then return an empty string "".

The solution to finding the Longest Common Prefix

Input Example

Example 1

Let the set of strings be { "flower", "flight", "fly", "flow" };

The longest common prefix here is "fl"

Example 2

Let the set of strings be {"dot", "dog", "donkey", "door", "cat" } there is no common prefix here so the longest common prefix is "", which means, an empty string.

Since there is no common prefix at all. 

To find the longest common prefix of a given set of strings in C#, you can use the following algorithm:

  1. Initialize a variable prefix to an empty string.
  2. If the input array is empty, return the empty string.
  3. Sort the input array in lexicographic order.
  4. Iterate over the characters in the first string in the sorted array.
  5. For each character, compare it to the corresponding character in the other strings in the array. If any of the characters don't match, return the current prefix.
  6. If all the characters match, append the current character to the prefix.
  7. Return the prefix.

Here is the C# code that implements this algorithm:

public class LongestCommonPrefix {
    public static string LongestCommonPrefixFun(string[] input) {
        if (input.Length == 0) {
            return "";
        }
        Array.Sort(input);
        string prefix = "";
        for (int i = 0; i < input[0].Length; i++) {
            char c = input[0][i];
            for (int j = 1; j < input.Length; j++) {
                if (i >= input[j].Length || input[j][i] != c) {
                    return prefix;
                }
            }
            prefix += c;
        }
        return prefix;
    }
}
C#

You can call this method with an array of strings as an argument, like this:

string[] input = { "flower", "flight", "fly", "flow" };
string result = LongestCommonPrefix.LongestCommonPrefixFun(input);
Console.WriteLine("Longest Common Prefix is- " + result); // Output: "fl"
C#

This code will output "fl", which is the longest common prefix of the input strings "flower""flight", "flow", and "flight".


Output





-----------------------------------------------------

Job Sequencing Problem in C#

  In this article we will discuss the Job sequencing problem in C#, we will achieve it using a greedy approach algorithm.

Problem statement

The job sequencing problem is a common problem that contains assigning a set of jobs to a set of machines, where each job has a deadline and a profit, and we have to get the maximum profit before the job deadline.

Given an array of jobs where each job has its deadline and profit. And Profit can get only if the job is finished before the job deadline also every job takes a single unit of time, so the minimum possible deadline for any job is 1 so we have to get the maximum profit before the job deadline.

For example,

JobIDDeadlineProfit
1390
2120
3230
4125
5215

Output

JobID:-> 4,3,1

C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JobsSequencingProblemInCSharp {
    public class Jobs {
        public int JobsID {
            get;
            set;
        }
        public int Deadline {
            get;
            set;
        }
        public int Profit {
            get;
            set;
        }
    }
    public class JobsSequencingProblem {
        public static void JobsSequencing() {
            List < Jobs > Jobs = new List < Jobs > () {
                new Jobs {
                    JobsID = 1, Deadline = 3, Profit = 90
                },
                new Jobs {
                    JobsID = 2, Deadline = 1, Profit = 20
                },
                new Jobs {
                    JobsID = 3, Deadline = 2, Profit = 30
                },
                new Jobs {
                    JobsID = 4, Deadline = 1, Profit = 25
                },
                new Jobs {
                    JobsID = 5, Deadline = 2, Profit = 15
                }
            };
            // Sort Jobs in the decreasing order of profit
            Jobs = Jobs.OrderByDescending(j => j.Profit).ToList();
            // Determine the maximum deadline of job
            int maxDeadline = Jobs.Max(j => j.Deadline);
            // Initialize the slots array
            int[] slots = new int[maxDeadline];
            foreach(Jobs Job in Jobs) {
                int slot = -1;
                for (int i = Job.Deadline - 1; i >= 0; i--) {
                    if (slots[i] == 0) {
                        slot = i;
                        break;
                    }
                }
                // If the slot is available, assign the Jobs to that slot
                if (slot != -1) {
                    slots[slot] = Job.JobsID;
                }
            }
            Console.WriteLine("Selected Jobs:");
            for (int i = 0; i < maxDeadline; i++) {
                if (slots[i] != 0) {
                    Console.WriteLine("Jobs " + slots[i]);
                }
            }
        }
    }
}
Public static void Main(string[] args) {
    JobsSequencingProblem.JobsSequencing();
    Console.ReadLine();
}
C#

Problem Explanation

This implementation is done by the greedy approach; we start by sorting the jobs in the decreasing order of the profit and then we determine the maximum deadline of the job then we initialize an array of slots with a length equal to the maximum deadline.

And then we iterate through each job and find the latest available slot for that job by starting from its deadline and going backward until we find an empty slot. If we find an available slot, we assign the job to that slot. If we don't find an available slot, we skip the job.

Finally, we print the selected jobs by iterating through the slots array and printing the job ID for each non-zero slot.

 



------------------------------------------