How to encrypt xmL file using VB.NET

Hello,

I'm using the following code to encrypt an xml file from VB.NET, however the code is not working, can you please help me figure out the correct code.

Imports System
Imports System.IO
Imports System.Security.AccessControl

Code:

Dim FileName As String = "C:\Links.xml"
File.Encrypt(FileName)

Thanks,

Victor
vcharlesAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Meir RivkinFull stack Software EngineerCommented:
chcek this code snippet:
class FileExample
    {
        public static void Main()
        {
            try
            {
                string FileName = "test.xml";

                Console.WriteLine("Encrypt " + FileName);

                // Encrypt the file.
                AddEncryption(FileName);

                Console.WriteLine("Decrypt " + FileName);

                // Decrypt the file.
                RemoveEncryption(FileName);

                Console.WriteLine("Done");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.ReadLine();
        }


        // Encrypt a file.
        public static void AddEncryption(string FileName)
        {

            File.Encrypt(FileName);

        }

        // Decrypt a file.
        public static void RemoveEncryption(string FileName)
        {
            File.Decrypt(FileName);
        }
    }

Open in new window

Meir RivkinFull stack Software EngineerCommented:
another method is to use a key to encrypt and to decrypt the data, check the following code from msdn:
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;

namespace CSEncryptDecrypt
{
   class Class1
   {
      //  Call this function to remove the key from memory after use for security
      [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")]
      public static extern bool ZeroMemory(IntPtr Destination, int Length);
		
      // Function to Generate a 64 bits Key.
      static string GenerateKey() 
      {
         // Create an instance of Symetric Algorithm. Key and IV is generated automatically.
         DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

         // Use the Automatically generated key for Encryption. 
         return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
      }

      static void EncryptFile(string sInputFilename,
         string sOutputFilename, 
         string sKey) 
      {
         FileStream fsInput = new FileStream(sInputFilename, 
            FileMode.Open, 
            FileAccess.Read);

         FileStream fsEncrypted = new FileStream(sOutputFilename, 
            FileMode.Create, 
            FileAccess.Write);
         DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
         DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
         DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
         ICryptoTransform desencrypt = DES.CreateEncryptor();
         CryptoStream cryptostream = new CryptoStream(fsEncrypted, 
            desencrypt, 
            CryptoStreamMode.Write); 

         byte[] bytearrayinput = new byte[fsInput.Length];
         fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
         cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
         cryptostream.Close();
         fsInput.Close();
         fsEncrypted.Close();
      }

      static void DecryptFile(string sInputFilename, 
         string sOutputFilename,
         string sKey)
      {
         DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
         //A 64 bit key and IV is required for this provider.
         //Set secret key For DES algorithm.
         DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
         //Set initialization vector.
         DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

         //Create a file stream to read the encrypted file back.
         FileStream fsread = new FileStream(sInputFilename, 
            FileMode.Open, 
            FileAccess.Read);
         //Create a DES decryptor from the DES instance.
         ICryptoTransform desdecrypt = DES.CreateDecryptor();
         //Create crypto stream set to read and do a 
         //DES decryption transform on incoming bytes.
         CryptoStream cryptostreamDecr = new CryptoStream(fsread, 
            desdecrypt,
            CryptoStreamMode.Read);
         //Print the contents of the decrypted file.
         StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
         fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
         fsDecrypted.Flush();
         fsDecrypted.Close();
      } 

      static void Main()
      {
         // Must be 64 bits, 8 bytes.
         // Distribute this key to the user who will decrypt this file.
         string sSecretKey;
         
         // Get the Key for the file to Encrypt.
         sSecretKey = GenerateKey();

         // For additional security Pin the key.
         GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
         
         // Encrypt the file.        
         EncryptFile(@"C:\MyData.txt", 
            @"C:\Encrypted.txt", 
            sSecretKey);

         // Decrypt the file.
         DecryptFile(@"C:\Encrypted.txt", 
            @"C:\Decrypted.txt", 
            sSecretKey);

         // Remove the Key from memory. 
         ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
         gch.Free();
      }
   }
}

Open in new window

Meir RivkinFull stack Software EngineerCommented:
sorry, i didn't see u use vb.net, so here's both code snippets in vb.net.

Imports System
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Runtime.InteropServices
Imports System.Text

Namespace CSEncryptDecrypt
    Class Class1
        '  Call this function to remove the key from memory after use for security
        <System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint:="RtlZeroMemory")> _
        Public Shared Function ZeroMemory(ByVal Destination As IntPtr, ByVal Length As Integer) As Boolean
        End Function

        ' Function to Generate a 64 bits Key.
        Private Shared Function GenerateKey() As String
            ' Create an instance of Symetric Algorithm. Key and IV is generated automatically.
            Dim desCrypto As DESCryptoServiceProvider = DirectCast(DESCryptoServiceProvider.Create(), DESCryptoServiceProvider)

            ' Use the Automatically generated key for Encryption. 
            Return ASCIIEncoding.ASCII.GetString(desCrypto.Key)
        End Function

        Private Shared Sub EncryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
            Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)

            Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
            Dim DES As New DESCryptoServiceProvider()
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
            Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
            Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)

            Dim bytearrayinput As Byte() = New Byte(fsInput.Length - 1) {}
            fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
            cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
            cryptostream.Close()
            fsInput.Close()
            fsEncrypted.Close()
        End Sub

        Private Shared Sub DecryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
            Dim DES As New DESCryptoServiceProvider()
            'A 64 bit key and IV is required for this provider.
            'Set secret key For DES algorithm.
            DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
            'Set initialization vector.
            DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)

            'Create a file stream to read the encrypted file back.
            Dim fsread As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
            'Create a DES decryptor from the DES instance.
            Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor()
            'Create crypto stream set to read and do a 
            'DES decryption transform on incoming bytes.
            Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
            'Print the contents of the decrypted file.
            Dim fsDecrypted As New StreamWriter(sOutputFilename)
            fsDecrypted.Write(New StreamReader(cryptostreamDecr).ReadToEnd())
            fsDecrypted.Flush()
            fsDecrypted.Close()
        End Sub

        Private Shared Sub Main()
            ' Must be 64 bits, 8 bytes.
            ' Distribute this key to the user who will decrypt this file.
            Dim sSecretKey As String

            ' Get the Key for the file to Encrypt.
            sSecretKey = GenerateKey()

            ' For additional security Pin the key.
            Dim gch As GCHandle = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned)

            ' Encrypt the file.        
            EncryptFile("C:\MyData.txt", "C:\Encrypted.txt", sSecretKey)

            ' Decrypt the file.
            DecryptFile("C:\Encrypted.txt", "C:\Decrypted.txt", sSecretKey)

            ' Remove the Key from memory. 
            ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2)
            gch.Free()
        End Sub
    End Class
End Namespace

Open in new window

CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Meir RivkinFull stack Software EngineerCommented:
and the first one here:
Imports System.IO

Class FileExample
    Public Shared Sub Main()
        Try
            Dim FileName As String = "test.xml"

            Console.WriteLine("Encrypt " & FileName)

            ' Encrypt the file.
            AddEncryption(FileName)

            Console.WriteLine("Decrypt " & FileName)

            ' Decrypt the file.
            RemoveEncryption(FileName)

            Console.WriteLine("Done")
        Catch e As Exception
            Console.WriteLine(e)
        End Try

        Console.ReadLine()
    End Sub


    ' Encrypt a file.
    Public Shared Sub AddEncryption(ByVal FileName As String)


        File.Encrypt(FileName)
    End Sub

    ' Decrypt a file.
    Public Shared Sub RemoveEncryption(ByVal FileName As String)
        File.Decrypt(FileName)
    End Sub
End Class

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vcharlesAuthor Commented:
Hello,

I tried to following code to test encrypting and decrypting an xml file from VB.NET, but it still doesn't work. Below is the code that I'm using. What am
I doing wrong?

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Encrypt.Click
Dim FileName As String = "c:\test.xml"
 ' Encrypt the file.
 AddEncryption(FileName)
End Sub
   
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Decrypt.Click
Dim FileName As String = "c:\test.xml"
 ' Decrypt the file.
RemoveEncryption(FileName)
End Sub
     

       
Meir RivkinFull stack Software EngineerCommented:
i tested the code again and it worked fine.
why do u say it's not working?

check http://msdn.microsoft.com/en-us/library/system.io.file.encrypt.aspx
vcharlesAuthor Commented:
Hi All,

I will stay involve, thank you for the reminder.

When I encrypt the file with the code below, the color of the test.xml turns greem, however I'm still avle to view its contents. What am I missing in the code below?

Thanks,

Victor

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Encrypt.Click
Dim FileName As String = "c:\test.xml"
 ' Encrypt the file.
 AddEncryption(FileName)
End Sub
   
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Decrypt.Click
Dim FileName As String = "c:\test.xml"
 ' Decrypt the file.
RemoveEncryption(FileName)
End Sub
vcharlesAuthor Commented:
I don't understand the last post. What do youmean by Forced accept?
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
XML

From novice to tech pro — start learning today.