Recently I came across a situation when I had to encrypt certain piece of data into ASP.NET and then read the same encrypted data for decryption into Classic ASP. Spent several hours and could not understand why the same encryption/decryption method used in both are producing entirely two different characters. After doing some tests, finally concluded that it is an issue of character Encoding.  By default ASP.NET produces data in UTF8 Charset and UTF8Encoding Content Encoding . Whereas Classic ASP defaults to null Charset. After all research and headache following one line of code fixed this issue and both started talking to each other.

In ASP.NET Page, on page Load event add following line

Response.ContentEncoding = Encoding.Default

This default value shows as SBCSCodePageEncoding, not sure if that is showing because of my environment or configuration settings but it fixed my issue.

Signature

As you know, Web.Config and App.Config files are like plain readable XML files. However, it contains sensitive information such as Connection Strings, Impersonation, App Setting Keys and their values. At some point you may need to secure these sections. .NET Framework allows to make your life simple, by just executing few commands on Command Prompt or few clicks using a Enterprise Library Configuration tool, you can achieve the desired result. There is only one basic requirement you should be able to at least remotely login to the Server where you would like to make these thing. Following are few simple steps to secure web.config or app.config.

File: Web.Config using Command Prompt

1. Go to Command Prompt

2. Change Directory to C:\Windows\Microsoft.NET\Framework\v2.0.50727

3. To Encrypt a Section in Web.Cofig -  type following - 

         aspnet_regiis -pef "<CONFIG_SECTION" "<PHYSICAL_PATH>"

        i.e. aspnet_regiis -pef "connectionStrings" “C:\Inetpub\wwwroot\TestWebSite"

        i.e. aspnet_regiis -pef "system.web/identity" “C:\Inetpub\wwwroot\TestWebSite"

4. Go to your website root directory, and create a File AppUser.Aspx and type the following line save it.                

        a. <%@ Page Language="VB" %>

            <% Response.Write( System.Security.Principal.WindowsIdentity.GetCurrent().Name ) %>

        b. Now, open your browser and call this page, this will show you a DOMAIN/UserName under which you website is running. Take a note of it. Now go back to command prompt.

5. Run the following command on command prompt to allow Permission to Users e.g. "NT Authority\Network Service", and the User Your Web Site is using it. run following command

              aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT Authority\Network Service"       

              aspnet_regiis -pa "NetFrameworkConfigurationKey" "DOMAIN/USERNAME"

6. After successful completion of command, remove the AppUser.Aspx file.

7. If you ever want to decrypt the section you encrypted, use following command

              aspnet_regiis -pdf  "<CONFIG_SECTION" "<PHYSICAL_PATH>"

You do not need to make any code change in your application for encryption or decryption, .NET automatically does it for you. 

For more details you can visit http://msdn.microsoft.com/en-us/library/ms998283.aspx

File: App.Config using Command Prompt

So what would you do to encrypt the same in case of App.Config, above command only work for Web.Config. Here is a trick – Copy the contents of App.Config into Web.Config file, or you can rename as web.config. Follow the same instructions as above, and after encryption, copy the file contents or rename it back to App.Config.

Easy Way To Encrypt/Decrypt - Web.Config/App.Config

If you have downloaded and Installed Microsoft Enterprise Library Configuration Tool, just open Web.Config or App.Config and select the section you want to encrypt, Go into Protection à Protection Provider and choose a provider you want (default is none) and save the file, you are done.  BUT,  you may have to follow #4 - #6, if .NET is not able to read encrypted section.

Signature

It is important to secure information on the web specially when transferring data from one page to another. Some information you may not want to make it readable by end user. Microsoft .NET provides Cryptography namespace which can be easily utilized for this purpose. The following example contains a simple class containing Encryption and Decryption method. It supports 2 types – DESC and Rijndael. Symmetric type and encryption key can be configured easily through .config file.


Imports System
Imports System.IO
Imports System.Text
Imports System.Security.Cryptography
Imports System.Configuration
 
''' <summary>
''' Custom Encryption Class
''' Author: Vishwa
''' Date :05/28/08
''' Purpose: To Encrypt and Decrypt the Data
''' Design Pattern : Singleton
''' </summary>
''' <remarks>
''' This class implements a Base 64 encryption and decryption Using Symetric
''' IMPT: Config File will contain 2 keys and its value - SymmetricType and SymmetricKey
''' </remarks>
 
Public NotInheritable Class RegCryptographer
    Private Shared _instance As New RegCryptographer
 
#Region "Constructor"
    Private Sub New()
 
    End Sub
#End Region
 
#Region "Public Methods"
 
    Public Shared Function DecryptQueryString(ByVal stringToDecrypt As String) As String
        Return DecryptSymmetric(stringToDecrypt.Replace(" ", "+"))
    End Function
 
    Public Shared Function EncryptQueryString(ByVal stringToEncrypt As String) As String
        Return EncryptSymmetric(stringToEncrypt)
    End Function
 
#End Region
 
#Region "Custom Cryptography"
    Private Shared _key() As Byte = {}
    Private Shared _IV() As Byte = {}
    Private Shared _symmetricKey As String = String.Empty
 
#Region "Rijndael Encryption/Decryption"
    Public Shared Function DecryptSymmetric(ByVal stringToDecrypt As String) As String
        If SymmetricType = "Rijndael" Then
            Return DecryptSymmetricRijndael(stringToDecrypt)
        Else
            Return DecryptSymmetricDESC(stringToDecrypt)
        End If
    End Function
 
    Public Shared Function EncryptSymmetric(ByVal stringToEncrypt As String) As String
        If SymmetricType = "Rijndael" Then
            Return EncryptSymmetricRijndael(stringToEncrypt)
        Else
            Return EncryptSymmetricDESC(stringToEncrypt)
        End If
    End Function
 
    Private Shared Function DecryptSymmetricRijndael(ByVal stringToDecrypt As String) As String
        Try
            Dim inputByteArray(stringToDecrypt.Length) As Byte
            Dim rijndael As New RijndaelManaged()
            rijndael.GenerateIV()
            'rijndael.GenerateKey()
            '_key = rijndael.Key
            _IV = rijndael.IV
 
            rijndael.KeySize = 128
            rijndael.BlockSize = 128
            rijndael.Mode = CipherMode.ECB
            rijndael.Padding = PaddingMode.PKCS7
            _key = System.Text.Encoding.UTF32.GetBytes(SymmetricKey)
            inputByteArray = Convert.FromBase64String(stringToDecrypt)
 
            Dim decryptor As ICryptoTransform = rijndael.CreateDecryptor(_key, _IV)
            Dim msDecrypt As New MemoryStream()
            Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write)
            csDecrypt.Write(inputByteArray, 0, inputByteArray.Length)
            csDecrypt.FlushFinalBlock()
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
            Return encoding.GetString(msDecrypt.ToArray())
        Catch e As Exception
            Return e.Message
        End Try
    End Function
 
    Private Shared Function EncryptSymmetricRijndael(ByVal stringToEncrypt As String) As String
        Try
            Dim rijndael As New RijndaelManaged()
            rijndael.GenerateIV()
            'rijndael.GenerateKey()
            '_key = rijndael.Key
            _IV = rijndael.IV
            _key = System.Text.Encoding.UTF32.GetBytes(SymmetricKey)
 
            rijndael.KeySize = 128
            rijndael.BlockSize = 128
            rijndael.Mode = CipherMode.ECB
            rijndael.Padding = PaddingMode.PKCS7
            Dim encryptor As ICryptoTransform = rijndael.CreateEncryptor(_key, _IV)
            Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
            Dim msEncrypt As New MemoryStream()
            Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
            csEncrypt.Write(inputByteArray, 0, inputByteArray.Length)
            csEncrypt.FlushFinalBlock()
            Return Convert.ToBase64String(msEncrypt.ToArray())
        Catch e As Exception
            Return e.Message
        End Try
    End Function
 
#End Region
 
#Region "DESC Encryption/DeCryption"
    Private Shared _symmetricType As String = String.Empty
    Private Shared Function DecryptSymmetricDESC(ByVal stringToDecrypt As String) As String
        Dim inputByteArray(stringToDecrypt.Length) As Byte
        Try
            inputByteArray = Convert.FromBase64String(stringToDecrypt)
            Dim des As New DESCryptoServiceProvider()
            des.GenerateIV()
            _IV = des.IV
            _key = System.Text.Encoding.UTF8.GetBytes(SymmetricKey)
 
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateDecryptor(_key, _IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
            Return encoding.GetString(ms.ToArray())
        Catch e As Exception
            Return e.Message
        End Try
    End Function
 
    Private Shared Function EncryptSymmetricDESC(ByVal stringToEncrypt As String) As String
        Try
            Dim des As New DESCryptoServiceProvider()
            des.GenerateIV()
            _IV = des.IV
            _key = System.Text.Encoding.UTF8.GetBytes(SymmetricKey)
 
            Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
            Dim ms As New MemoryStream()
            Dim cs As New CryptoStream(ms, des.CreateEncryptor(_key, _IV), CryptoStreamMode.Write)
            cs.Write(inputByteArray, 0, inputByteArray.Length)
            cs.FlushFinalBlock()
            Return Convert.ToBase64String(ms.ToArray())
        Catch e As Exception
            Return e.Message
        End Try
    End Function
 
 
#End Region
 
#Region "Properties"
   
    Private Shared ReadOnly Property SymmetricType() As String
        Get
            If String.IsNullOrEmpty(_symmetricType) Then
                Try
                   _symmetricType = ConfigurationManager.AppSettings.Item("SymmetricType")
                Catch ex As Exception
                    _symmetricType = "Rijndael"
                End Try
                If String.IsNullOrEmpty(_symmetricType) Then _symmetricType = "Rijndael"
            End If
            Return _symmetricType
        End Get
    End Property
 
 
    Private Shared ReadOnly Property SymmetricKey() As String
        Get
            If String.IsNullOrEmpty(_symmetricKey) Then
                Try
                    _symmetricKey = ConfigurationManager.AppSettings.Item("SymmetricKey")
                Catch ex As Exception
                    _symmetricKey = "DIffTkey"
                End Try
                If String.IsNullOrEmpty(_symmetricKey) Then _symmetricKey = "DIffTkey"
            End If
            Return Left(_symmetricKey, 8)
        End Get
    End Property
 
#End Region
 
#End Region
 
End Class
Signature

I came across a situation where I had to find all the stored procedures or user defined functions that do not have “execute” permission under a particular user. Here is a simple SQL Statement one which can be used under SQL Server 2005 to find those objects.

 Note: Make sure that you have logged in as a most privileged user through a Query Analyzer window and then replace the  ‘user_name’ for which you want to check permission. For example, following code will show all the procedures which do not have Execute permission for 'user_name'.

Declare @ObjName Varchar(100)

Create table #TempTable1 (Entity_Name varchar(100), Permission_Name varchar(25))

Create table #TempTable2 (Entity_Name varchar(100), Permission_Name varchar(25))

 

INSERT #TempTable1(Entity_Name)

SELECT Name FROM sys.objects

WHERE type='P'

ORDER by Name

 

EXECUTE AS USER = 'user_name';

 

Declare TableList cursor LOCAL FAST_FORWARD FOR     

SELECT Entity_Name FROM #TempTable1

ORDER by Entity_Name

OPEN TableList     

     

FETCH NEXT FROM TableList INTO @ObjName         

WHILE @@fetch_status = 0        

 BEGIN   

        INSERT INTO #TempTable2  

  SELECT Entity_Name,Permission_Name 

  FROM fn_my_permissions(@ObjName, 'OBJECT')

        FETCH NEXT FROM TableList INTO @ObjName   

 End

 

CLOSE TableList

DEALLOCATE TableList

 

SELECT Entity_Name FROM #TempTable1

WHERE Entity_Name NOT IN (SELECT Entity_Name FROM #TempTable2);

 

Drop table #TempTable1;

Drop table #TempTable2;

Signature

About Me

Me Hello,my name is Vishwa Mohan Kumar.
I am a Software Architect. This blog is result of my experiments.

Flickr Photos

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent Comments

Comment RSS

Live Traffic Feed