Criptografia de Dados

Muitas vezes precisamos passar dados de uma pagina para outra geralmente usando-se QueryString (ex. login.aspx?id=1), existem situações em que não existe nenhum problema o usuário visualizar essas informações, mas há casos em que é necessário esconder essas informações para isso utilizamos a criptografia. O exemplo que vou mostrar agora é o algoritmo de Rijndael que é o novo DES, definido pelo governo americano, o Rijndael utiliza uma chave mais forte (256bits).

 

O exemplo acima criptografado ficaria assim (Ex. login.aspx?id=vLyHARA8A0m2SknVd0azxw==). Essa criptografia é tão segura que seria mais fácil acertarmos na Sena varias vezes do que acertar essa Senha de uma forma aleatória.

 

.NET Framework fornece as seguintes classes que podem ser usadas para implementar um algoritmo de cifragem usando chave privada:

01. RC2CryptoServiceProvider (algoritmo RC2)
02. DESCryptoServiceProvider (algoritmo DES)
03. TrippleDESCryptoServiceProvider (algoritmo TrippleDES)
04. RijndaelManaged (algoritmo Rijndael ) -->> Estamos usando este método

Vamos criar um pequeno exemplo que irá cifrar e decifrar dados. Por Exemplo:

Nome a ser cifrado: damon abdiel
Resultado cifrado: gSX8U2bgPCUjL5XvQZZ6zg==&Data2=NBeC47qEzqK0xSqtwmfYVw==

Resultado decifrado: damon abdiel

 

Inicie um novo projeto no VS.NET e escolha um projeto do tipo Asp.net Web Application usando VB.NET.

Teremos duas pagina a de login.aspx e a de resposta.aspx

Componentes da pagina INDEX.ASPX:

Textbox

tbID

Button

btEntrar

Na pagina inclua o código abaixo:

' ****************************************************************
' ***** Use os seguintes imports                                       
' ****************************************************************

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

Private ChaveSecreta As String = "uiw78r5zxHr4%#125*"

‘************************************
’***** Função executada pelo botão Entrar
’************************************

    Sub Botao_Entrar(ByVal Sender As Object, ByVal E As EventArgs)

‘*****************************************************************
’***** Aqui invocamos a função de cifrar e depois redirecionamos a QueryString já criptografada
’*****************************************************************

               Dim strCaminho As String = “./resposta.aspx?Data1=" & Me.Cifrar(Me.tb_ID.Text, ChaveSecreta)

                   Response.Redirect(strCaminho)

    End Sub

    ' ***************************************************************
    ' ***** Função responsável por Cifrar a sua String                               
    ' ***** Use da seguinte forma:                                                              
    ' ***** Call Cifrar("Palavra", "SuaChaveSecreta(Ex.2345)")                   
    ' ***************************************************************

    Private Function Cifrar(ByVal vstrTextToBeEncrypted As String, ByVal vstrEncryptionKey As String) As String

        Dim bytValue() As Byte
        Dim bytKey() As Byte
        Dim bytEncoded() As Byte
        Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62}
        Dim intLength As Integer
        Dim intRemaining As Integer
        Dim objMemoryStream As New MemoryStream
        Dim objCryptoStream As CryptoStream
        Dim objRijndaelManaged As RijndaelManaged

' ***************************************************************
' ****** Descarta todos os caracteres nulos da palavra a ser cifrada             
' ***************************************************************

        vstrTextToBeEncrypted = TiraCaracteresNulos(vstrTextToBeEncrypted)

' ***************************************************************
' ****** O valor deve estar dentro da tabela ASCII (i.e., no DBCS chars)    
' ***************************************************************

        bytValue = Encoding.ASCII.GetBytes(vstrTextToBeEncrypted.ToCharArray)

        intLength = Len(vstrEncryptionKey)

' ****************************************************************
' ****** A chave cifrada será de 256 bits long (32 bytes)                             
' ****** Se for maior que 32 bytes então será truncado.                               
' ****** Se for menor que 32 bytes será alocado.                                        
' ****** Usando upper-case Xs.                                                                  
' ****************************************************************

        If intLength >= 32 Then

            vstrEncryptionKey = Strings.Left(vstrEncryptionKey, 32)

        Else

            intLength = Len(vstrEncryptionKey)
            intRemaining = 32 – intLength
            vstrEncryptionKey = vstrEncryptionKey & Strings.StrDup(intRemaining, "X")

        End If

        bytKey = Encoding.ASCII.GetBytes(vstrEncryptionKey.ToCharArray)
        objRijndaelManaged = New RijndaelManaged

        Try

            objCryptoStream = New CryptoStream(objMemoryStream, objRijndaelManaged.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write)
            objCryptoStream.Write(bytValue, 0, bytValue.Length)
            objCryptoStream.FlushFinalBlock()
            bytEncoded = objMemoryStream.ToArray
            objMemoryStream.Close()
            objCryptoStream.Close()

        Catch

        End Try

        Return Convert.ToBase64String(bytEncoded)

    End Function

    ' ***************************************************************
    ' ***** Função responsável por tirar os espaços em branco da                     
    ' ***** variável a ser cifrada                                                                          
    ' ***** Esta função é chamada internamente                                                 
    ' ***************************************************************

    Private Function TiraCaracteresNulos(ByVal vstrStringWithNulls As String) As String

        Dim intPosition As Integer
        Dim strStringWithOutNulls As String
        intPosition = 1
        strStringWithOutNulls = vstrStringWithNulls
        Do While intPosition > 0

            intPosition = InStr(intPosition, vstrStringWithNulls, vbNullChar)
            If intPosition > 0 Then
                strStringWithOutNulls = Left$(strStringWithOutNulls, intPosition - 1) & _
                Right$(strStringWithOutNulls, Len(strStringWithOutNulls) - intPosition)

            End If

            If intPosition > strStringWithOutNulls.Length Then

                Exit Do

            End If

        Loop

        Return strStringWithOutNulls

    End Function

Agora a pagina RESPOSTA.ASPX

 

' ****************************************************************
' ***** Use os seguintes imports                                       
' ****************************************************************

Imports System.Security.Cryptography
Imports System.IO
Imports System.Text

Private ChaveSecreta As String = "uiw78r5zxHr4%#125*"

 

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

 

            If Convert.ToString(Request.QueryString("Data1")) <> "" Then

 

                Dim strID, strSenha As String

 

                strID = Me.Decifrar(Request.QueryString("Data1").ToString(), ChaveSecreta)

 

Response.write(“ID - ” & strID)

 

           End If

 End Sub

 

' **************************************************************
' ***** Função Responsável por Decifrar a sua String Cifrada                     
' ***** Use da seguinte forma:                                                                    
' ***** Call Decifrar ("Palavra", "SuaChaveSecreta(Ex.2345)")                   
' **************************************************************

 

Private Function Decifrar(ByVal vstrStringToBeDecrypted As String, ByVal vstrDecryptionKey As String) As String

 

            Dim bytDataToBeDecrypted() As Byte

            Dim bytTemp() As Byte

            Dim bytIV() As Byte = {121, 241, 10, 1, 132, 74, 11, 39, 255, 91, 45, 78, 14, 211, 22, 62}

            Dim objRijndaelManaged As New RijndaelManaged

            Dim objMemoryStream As MemoryStream

            Dim objCryptoStream As CryptoStream

            Dim bytDecryptionKey() As Byte

 

            Dim intLength As Integer

            Dim intRemaining As Integer

            Dim intCtr As Integer

            Dim strReturnString As String = String.Empty

            Dim achrCharacterArray() As Char

            Dim intIndex As Integer

' ***************************************************************
' ****** Convert base64 cifrada para byte array                                
' ****** Convert base64 cifrada para byte array                                
' ***************************************************************

 

            bytDataToBeDecrypted = Convert.FromBase64String(vstrStringToBeDecrypted)

 

' ***************************************************************
' ****** A chave cifrada sera de 256 bits long (32 bytes)                           
' ****** Se for maior que 32 bytes então será truncado.                              
' ****** Se for menor que 32 bytes será alocado.                                       
' ****** Usando upper-case Xs.                                                              
' ***************************************************************

 

            intLength = Len(vstrDecryptionKey)

 

            If intLength >= 32 Then

                vstrDecryptionKey = Strings.Left(vstrDecryptionKey, 32)

            Else

                intLength = Len(vstrDecryptionKey)

                intRemaining = 32 - intLength

                vstrDecryptionKey = vstrDecryptionKey & Strings.StrDup(intRemaining, "X")

            End If

 

            bytDecryptionKey = Encoding.ASCII.GetBytes(vstrDecryptionKey.ToCharArray)

 

            ReDim bytTemp(bytDataToBeDecrypted.Length)

 

            objMemoryStream = New MemoryStream(bytDataToBeDecrypted)

 

' ***************************************************************
' ****** Escrever o valor decifrado depois que é convertido                      
' ***************************************************************

 

            Try

 

                objCryptoStream = New CryptoStream(objMemoryStream, _

                objRijndaelManaged.CreateDecryptor(bytDecryptionKey, bytIV), _

                CryptoStreamMode.Read)

 

                objCryptoStream.Read(bytTemp, 0, bytTemp.Length)

 

                objCryptoStream.FlushFinalBlock()

                objMemoryStream.Close()

                objCryptoStream.Close()

 

            Catch

 

            End Try

' ***************************************************************
' ****** Retorna o valor decifrado                                    
' ***************************************************************

            Return TiraCaracteresNulos(Encoding.ASCII.GetString(bytTemp))

 

        End Function

 

        ' ***************************************************************

        ' ***** Função responsável por tirar os espaços em branco da                     

        ' ***** variável a ser cifrada                                                                         

        ' ***** Esta função é chamada internamente                                                  

        ' ***************************************************************

 

        Private Function TiraCaracteresNulos(ByVal vstrStringWithNulls As String) As String

 

            Dim intPosition As Integer

            Dim strStringWithOutNulls As String

 

            intPosition = 1

            strStringWithOutNulls = vstrStringWithNulls

 

            Do While intPosition > 0

                intPosition = InStr(intPosition, vstrStringWithNulls, vbNullChar)

 

                If intPosition > 0 Then

                    strStringWithOutNulls = Left$(strStringWithOutNulls, intPosition - 1) & _

                    Right$(strStringWithOutNulls, Len(strStringWithOutNulls) - intPosition)

                End If

 

                If intPosition > strStringWithOutNulls.Length Then

                    Exit Do

                End If

            Loop

 

            Return strStringWithOutNulls

 

        End Function