cifrar txt y lectura solo con proyecto unicamente

Iniciado por cael1011, 11 Enero 2017, 06:00 AM

0 Miembros y 1 Visitante están viendo este tema.

cael1011

Alguien tiene una idea de cifrar un txt, que sea ilegible para cualquier editor de texto, pero legible para la lectura, en un texbox ? me gustaria saber como hago qeu el archivo no se pueda leer con editores externo solo desde la lectura de vb.net

Eleкtro

#1
Hola. Primero que nada, las preguntas sobre VisualBasic.NET van en el subforo de .NET, este lenguaje no tiene nada que ver con VisualBasic.

Para llevar a cabo lo que solicitas, hay múltiples formas, si son archivos de texto, poco tamaño, yo considero que te valdría con implementar cualquier metodología sincrónica o "método bloqueador" con un algoritmo de cifrado, y listo. Es decir, tu programa se encargaría de cifrar el archivo de texto para que sea ilegible al ojo humano (al menos para el usuario común que no sepa ni encender un PC), y cuando quieras leerlo simplemente desencriptas el contenido en memoria y lees el string resultante.

Para este ejemplo he utilizado la implementación de Microsoft del algoritmo criptográfico DES, si lo prefieres puedes utilizar cualquier otro de los disponibles en la librería de clases de .NET Framework.

Bien, primero desarrollamos el algoritmo de cifrado y desencriptación, los dividiremos en tres métodos distintos a los que he llamado "EncryptFile", "DecryptFile", "DecryptFileAsString":

Código (vbnet) [Seleccionar]
Public Shared Sub EncryptFile(ByVal srcFilepath As String, ByVal dstFilepath As String, key As String)
   If String.IsNullOrEmpty(key) Then
       Throw New ArgumentNullException("key")
       Exit Sub

   ElseIf (key.Length < 8) Then
       ' DESCryptoServiceProvider needs a 64 bit key, so I fill the key string with dots until it has character length of 8.
       key = key.Insert(key.Length, String.Join("", Enumerable.Repeat("."c, (8 - key.Length))))

   End If

   Using fsInput As New FileStream(srcFilepath, FileMode.Open, FileAccess.Read),
         fsOutput As New FileStream(dstFilepath, FileMode.CreateNew, FileAccess.Write),
         des As New DESCryptoServiceProvider() With {.Key = ASCIIEncoding.ASCII.GetBytes(key), .IV = .Key},
         cryptoStream As New CryptoStream(fsOutput, des.CreateEncryptor(), CryptoStreamMode.Write)

       Dim rawData As Byte() = New Byte(CInt(fsInput.Length - 1)) {}
       fsInput.Read(rawData, 0, rawData.Length)
       cryptoStream.Write(rawData, 0, rawData.Length)
   End Using
End Sub

Public Shared Sub DecryptFile(srcFilepath As String, dstFilepath As String, key As String)
Using fsWrite As New StreamWriter(dstFilepath)
       fsWrite.Write(DecryptFileAsString(srcFilepath, key))
       fsWrite.Flush()
   End Using
End Sub

Public Shared Function DecryptFileAsString(srcFilepath As String, key As String) As String
   If String.IsNullOrEmpty(key) Then
       Throw New ArgumentNullException("key")
       Return Nothing

   ElseIf (key.Length < 8) Then
       ' DESCryptoServiceProvider needs a 64 bit key, so I fill the key string with dots until it has character length of 8.
       key = key.Insert(key.Length, String.Join("", Enumerable.Repeat("."c, (8 - key.Length))))

   End If

   Using des As New DESCryptoServiceProvider() With {.Key = ASCIIEncoding.ASCII.GetBytes(key), .IV = .Key}
       Using fsRead As New FileStream(srcFilepath, FileMode.Open, FileAccess.Read),
             cryptoStream As New CryptoStream(fsRead, des.CreateDecryptor(), CryptoStreamMode.Read),
             srRead As New StreamReader(cryptoStream)

           Return srRead.ReadToEnd()
       End Using
   End Using
End Function


La diferencia entre los métodos "DecryptFile" y "DecryptFileAsString" es que el primero descifra y escribe los datos en un archivo de destino, mientras que el otro simplemente descifra y devuelve los datos en un valor de retorno de tipo String.




Así pues, el algoritmo en tu programa lo puedes usar de la siguiente manera:

Código (vbnet) [Seleccionar]

' La clave única que este progama usará para cifrar y descifrar archivos.
Private ReadOnly key As String = "MyKey"

' Archivo de texto a cifrar:
Dim srcFile As New FileInfo("C:\File.txt")

' Archivo de texto a descifrar:
Dim dstFile As New FileInfo(String.Format("{0}.dat", srcFile.FullName))

Try ' Comenzar la cifrado.
   EncryptFile(srcFile.FullName, dstFile.FullName, key)
   ' srcFile.Delete()

Catch ex As Exception
   Throw

End Try

' descifrar archivo de texto.
Dim result As String = DecryptFileAsString(dstFile.FullName, key)

' Mostrar el string descifrado en un TextBox.
Me.TextBox1.Text = result





Si tenemos un archivo de texto en codificación UTF-8 (con BOM) con el siguiente contenido:
Hello World!

Y usando la clave "MyKey", entonces el algoritmo de cifrado generará esto:
M3bëëa(MÆ7]7¸wc

Y el algoritmo de desencriptación devolverá el texto original.