Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

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#

Angular v16 is available | Angular 16 new feature | What's New in #Angular16

Angular v16 has released in May 2023; in this article, we will discuss new features introduced in angular v16

Last year Angular 15 was released in November 2022 with some new features, including performance improvement and standalone components and API. So now (May 2023), Angular V16 has been released with some new features and enhancements.



👉Angular v17 new features | What's New in #Angular17

Please follow the below link for more,

  1. Angular 14 Features
  2. Angular 15 Features

Angular 16 new features

  1. Rethinking Reactivity
  2. Angular Signals
  3. RxJS interoperability
  4. Server-side rendering 
  5. hydration enhanced
  6. Improved tooling experience for standalone components, pipes, and directives
  7. Advancing developer tooling
  8. Better unit testing using Jest and Web Test Runner
  9.  Autocomplete imports within the HTML templates.      

Rethinking Reactivity

  1. It helps us to improve the performance and the developer experience.
  2. It completely depends on backward compatibility and the inoperable with the current system and then enabling it.
  3. It improves performance by reducing the number of the computation during the change detection.
  4. It enables fine-grained reactivity

Angular Signals

Now just like the signals we used in React, it is available in Angular V16 as well.

This signal library allows us to define all the reactive values and then expose their dependencies.

@Component({
  selector: 'my-app',
  standalone: true,
  template: `
    {{ fullName() }} <button (click)="DisplayName('DotNet')">Click</button>
  `,
})
export class App {
  fName = signal('DotNet_new');
  lName = signal('Office');
  fullName = computed(() => `${this.fName()} ${this.lName()}`);

  constructor() {
    effect(() => console.log('Name :', this.fullName()));
  }

  DisplayName(name: string) {
    this.firstName.set(name);
  }
}
ASP.NET (C#)

In the above code, we are computing the value of fullName, which depends on the signals fName and the LName. Here we declare an effect, which executes every time we make changes in the value of any of the signals.

When we give the value off the Name ”dotnet”, it will log into the console.

"Name : dotnet office"
ASP.NET (C#)






RxJS interoperability

Now we will able to use signals in observables using functions by using below CLI command which is still in preview @angular/core/rxjs-interop

Convert observable to signal 

import { signal,toObservable } from '@angular/core/rxjs-interop';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class App {
  count = signal(0);
  count1 = toObservable(this.count);

  ngOnInit() {
    this.count1.subscribe(() => ..);
  }
}
ASP.NET (C#)

Convert Signal to observable

import { signal,toObservable,toSignal } from '@angular/core/rxjs-interop';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: `
  <li *ngFor="let row of data()"> {{ row }} </li>
`,
  styleUrls: ['./app.component.css']
})
export class App {
  dataService = inject(DataService);
  data = toSignal(this.dataService.data$, []);
}
ASP.NET (C#)




Server-side rendering and hydration enhanced

  1.    So the Angular team has enhanced in performance with the help of the Chrome Aurora team.
  2.   They have improved the server-side rendering.





Reference: https://blog.angular.io/angular-v16-is-here-4d7a28ec680d

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

Top Microsoft NuGet Packages in 2023

Here are some of the popular NuGet packages that have been frequently used by developers.

1.    Newtonsoft.Json: This is a popular package for working with JSON data in .NET applications. It provides a simple and efficient API for parsing and serializing JSON data.

2.    Entity Framework Core: This is a lightweight and extensible ORM (object-relational mapper) that simplifies database access in .NET applications.

3.    AutoMapper: This package helps to simplify object-to-object mapping in .NET applications, reducing the amount of boilerplate code needed for mapping between different objects.

4.    Microsoft.Extensions.DependencyInjection: This package provides a lightweight dependency injection framework for .NET applications. It simplifies the process of registering and resolving dependencies in your application.

5.    Serilog: This is a popular logging framework for .NET applications that supports structured logging, making it easy to search and analyze log data.

6.    Microsoft.AspNetCore.Mvc: This is a package that provides a lightweight and flexible framework for building web applications using ASP.NET Core.

7.    Microsoft.EntityFrameworkCore.SqlServer: This package provides support for using SQL Server with Entity Framework Core, making it easy to work with SQL Server databases in your .NET application.

8.    Dapper: This is a popular micro-ORM (object-relational mapper) for .NET that provides a fast and efficient way to access data from a database.

9.    Microsoft.AspNet.WebApi.Core: This package provides a framework for building RESTful APIs using ASP.NET, making it easy to build scalable and maintainable web services.

10. Microsoft.Extensions.Logging: This package provides a logging abstraction for .NET applications, making it easy to switch between different logging providers and configure logging behavior.

11. Microsoft.Extensions.Caching.Memory: it is a NuGet package that provides an in-memory caching implementation for .NET applications. It is part of the Microsoft.Extensions.Caching namespace, which also includes other caching implementations like Redis and SQL Server.

12. FluentValidation.AspNetCore:- FluentValidation validation helps us validate our model when working with DotNet Core 7.0 application. To utilize the functionality of FluentValidation, we need to install the FluentValidation library from the NuGet package manager. FluentValidation uses the fluent API and the lambda expression to create the data validation rules for a model. Below is the command to install the FluentValidation package


There are many other Microsoft NuGet Packages as well, which are used in real programming also.

Above are a couple of packages that mostly we use in programming, let us know your thought on it if any important package is missing here.



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

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now