Wednesday 9 October 2019

Encrypt Files using System.Security.Cryptography in SSIS package


Information security is very important for the company. When we are sending the files over the network better way to encrypt these files and then send it.
In this demo we will see who we can encrypt the CSV file
Below is my file which I want to encrypt.
 
 

Here I will encrypt this file using System.Security.Cryptography (Rijndael Algorithm).
I am taking script task. We need to write the below code
We need to include below namespaces
  • using System.Security.Cryptography;
  • using System.IO;

string filepath = @"J:\SSIS1\Source\sales_10062019_1.csv";//File pth     
            string newFilepath = filepath.Substring(0, filepath.LastIndexOf(".") - 1) + "_ENCRYPTED" + filepath.Substring(filepath.LastIndexOf("."));
            string encryptionKey = "Bagesh"; //Encryption key
            FileStream fsIn = new FileStream(filepath, FileMode.Open, FileAccess.Read);
            // Open filestream for encrypted file
            FileStream fsOut = new FileStream(newFilepath, FileMode.OpenOrCreate, FileAccess.Write);
            // Create Key and IV from the password with salt technique
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(encryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            // Create a symmetric algorithm with Rijndael
            Rijndael alg = Rijndael.Create();
            // Set Key and IV
            alg.Key = pdb.GetBytes(32);
            alg.IV = pdb.GetBytes(16);
            CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write);
            int bufferLen = 4096;
            byte[] buffer = new byte[bufferLen];
            int bytesRead;
            do
            {
               bytesRead = fsIn.Read(buffer, 0, bufferLen);
               cs.Write(buffer, 0, bytesRead);
            } while (bytesRead != 0);
            cs.Close();
            fsIn.Close();

Compile the code and save it and close. Now I am running this package.
  
Let’s see the encrypted file.
   


It is not human readable.

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts