Esta pregunta fue respondida aqui:
El espacio de nombres System.Security.Cryptography
contiene todas las clases que necesita para realizar la mayoría de las tareas de cifrado estándar. Desafortunadamente, dado que el cifrado es un tema bastante complicado, las clases son algo difíciles de trabajar, especialmente para principiantes. A veces es difícil encontrar un ejemplo de trabajo simple para empezar. Pero, dado que soy amable, te ofreceré un ejemplo simple con el que puedes jugar y mejorar :)
La clase que probablemente quiera usar se llama RijndaelManaged
. Esa es la clase que implementa el típico cifrado AES
. Aquí hay una clase de muestra que usa eso para convertir cadenas de texto sin formato y matrices de bytes:
Public Class Aes256Encrypter
Public Function Encrypt(ByVal plainText As String, ByVal secretKey As String) As Byte()
Dim encryptedPassword As Byte()
Using outputStream As MemoryStream = New MemoryStream()
Dim algorithm As RijndaelManaged = getAlgorithm(secretKey)
Using cryptoStream As CryptoStream = New CryptoStream(outputStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write)
Dim inputBuffer() As Byte = Encoding.Unicode.GetBytes(plainText)
cryptoStream.Write(inputBuffer, 0, inputBuffer.Length)
cryptoStream.FlushFinalBlock()
encryptedPassword = outputStream.ToArray()
End Using
End Using
Return encryptedPassword
End Function
Public Function Decrypt(ByVal encryptedBytes As Byte(), ByVal secretKey As String) As String
Dim plainText As String = Nothing
Using inputStream As MemoryStream = New MemoryStream(encryptedBytes)
Dim algorithm As RijndaelManaged = getAlgorithm(secretKey)
Using cryptoStream As CryptoStream = New CryptoStream(inputStream, algorithm.CreateDecryptor(), CryptoStreamMode.Read)
Dim outputBuffer(0 To CType(inputStream.Length - 1, Integer)) As Byte
Dim readBytes As Integer = cryptoStream.Read(outputBuffer, 0, CType(inputStream.Length, Integer))
plainText = Encoding.Unicode.GetString(outputBuffer, 0, readBytes)
End Using
End Using
Return plainText
End Function
Private Function getAlgorithm(ByVal secretKey As String) As RijndaelManaged
Const salt As String = "put your salt here"
Const keySize As Integer = 256
Dim keyBuilder As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(secretKey, Encoding.Unicode.GetBytes(salt))
Dim algorithm As RijndaelManaged = New RijndaelManaged()
algorithm.KeySize = keySize
algorithm.IV = keyBuilder.GetBytes(CType(algorithm.BlockSize / 8, Integer))
algorithm.Key = keyBuilder.GetBytes(CType(algorithm.KeySize / 8, Integer))
algorithm.Padding = PaddingMode.PKCS7
Return algorithm
End Function
End Class
Deberías cambiar la constante salt
por otra cosa. Idealmente, ni siquiera sería una constante, ya que, para que sea lo más seguro posible, debe usar una sal diferente cada vez que realice el cifrado, pero ese es un tema totalmente distinto.
Si desea que el valor encriptado se devuelva como una cadena en lugar de una matriz de bytes, puede usar la codificación Base-64 para convertir la matriz de bytes a cadenas y desde cadenas como esta:
Public Class Aes256Base64Encrypter
Public Function Encrypt(ByVal plainText As String, ByVal secretKey As String) As String
Dim encryptedPassword As String = Nothing
Using outputStream As MemoryStream = New MemoryStream()
Dim algorithm As RijndaelManaged = getAlgorithm(secretKey)
Using cryptoStream As CryptoStream = New CryptoStream(outputStream, algorithm.CreateEncryptor(), CryptoStreamMode.Write)
Dim inputBuffer() As Byte = Encoding.Unicode.GetBytes(plainText)
cryptoStream.Write(inputBuffer, 0, inputBuffer.Length)
cryptoStream.FlushFinalBlock()
encryptedPassword = Convert.ToBase64String(outputStream.ToArray())
End Using
End Using
Return encryptedPassword
End Function
Public Function Decrypt(ByVal encryptedBytes As String, ByVal secretKey As String) As String
Dim plainText As String = Nothing
Using inputStream As MemoryStream = New MemoryStream(Convert.FromBase64String(encryptedBytes))
Dim algorithm As RijndaelManaged = getAlgorithm(secretKey)
Using cryptoStream As CryptoStream = New CryptoStream(inputStream, algorithm.CreateDecryptor(), CryptoStreamMode.Read)
Dim outputBuffer(0 To CType(inputStream.Length - 1, Integer)) As Byte
Dim readBytes As Integer = cryptoStream.Read(outputBuffer, 0, CType(inputStream.Length, Integer))
plainText = Encoding.Unicode.GetString(outputBuffer, 0, readBytes)
End Using
End Using
Return plainText
End Function
Private Function getAlgorithm(ByVal secretKey As String) As RijndaelManaged
Const salt As String = "put your salt here"
Const keySize As Integer = 256
Dim keyBuilder As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(secretKey, Encoding.Unicode.GetBytes(salt))
Dim algorithm As RijndaelManaged = New RijndaelManaged()
algorithm.KeySize = keySize
algorithm.IV = keyBuilder.GetBytes(CType(algorithm.BlockSize / 8, Integer))
algorithm.Key = keyBuilder.GetBytes(CType(algorithm.KeySize / 8, Integer))
algorithm.Padding = PaddingMode.PKCS7
Return algorithm
End Function
End Class
Si está almacenando el valor cifrado en un archivo de texto, XML o incluso una base de datos, a menudo es más fácil usar Base-64, así.