Forums Últimos mensajes - Powered by IBM
 

Encriptar / desencriptar una cadena de texto

17/05/2005 - 13:48 por Baldor | Informe spam
Me suena que hay alguna clase en el Framework para poder
encriptar/desencriptar un string.
¿Alguien la conoce?

Gracias
 

Leer las respuestas

#1 Eduardo A. Morcillo [MS MVP VB]
17/05/2005 - 16:32 | Informe spam
No hay ninguna clase que encripte o desencripte strings en el framework. Lo
que si tienes son clases de algoritmos de encriptacion y con ellas puedes
encriptar tu string. Puedes usar estas funciones:

''' --
''' <summary>
''' Encrypts a string using the given provider and a key derived
from password using MD5.
''' </summary>
''' --
Public Shared Function Encrypt( _
ByVal text As String, ByVal password As String, ByVal
algorithmName As String) As String

' Create the provider object
Dim encProvider As SymmetricAlgorithm =
SymmetricAlgorithm.Create(algorithmName)

' Convert the string to a byte array
Dim data() As Byte = UTF8.GetBytes(text)

' Derive the key from the password
Dim iv() As Byte = {0, 0, 0, 0, 0, 0, 0, 0}
Dim keyb() As Byte = (New PasswordDeriveBytes(password,
iv).CryptDeriveKey( _
algorithmName, "MD5",
encProvider.KeySize, iv))

' Create an encryptor object
Dim transform As ICryptoTransform =
encProvider.CreateEncryptor(keyb, iv)

Try

' Encrypt the string and convert the result to Base64
Return
System.Convert.ToBase64String(transform.TransformFinalBlock(data, 0,
data.Length))

Finally

' Release the transform object
transform.Dispose()

End Try

End Function

''' --
''' <summary>
''' Encrypts a string using the given provider and a key derived
from password using MD5.
''' </summary>
''' --
Public Shared Function Decrypt( _
ByVal encryptedText As String, ByVal password As String, ByVal
algorithmName As String) As String

' Create the provider object
Dim encProvider As SymmetricAlgorithm =
SymmetricAlgorithm.Create(algorithmName)

' Convert the Base-64 string to a byte array
Dim data() As Byte =
System.Convert.FromBase64String(encryptedText)

' Derive the key from the password
Dim iv() As Byte = {0, 0, 0, 0, 0, 0, 0, 0}
Dim keyb() As Byte = (New PasswordDeriveBytes(password,
iv).CryptDeriveKey( _
algorithmName, "MD5", encProvider.KeySize,
iv))

' Create a decryptor object
Dim transform As ICryptoTransform =
encProvider.CreateDecryptor(keyb, iv)

Try

' Decrypt the data and convert it to a string
Return UTF8.GetString(transform.TransformFinalBlock(data, 0,
data.Length))

Finally

' Release the transform object
transform.Dispose()

End Try

End Function


Eduardo A. Morcillo [MS MVP VB]
http://www.mvps.org/emorcillo

Preguntas similares