Siempre hay que pensar en el estado de la informacion que se esta manejando en nuestros sistema de informacion, sobre todo si estamos hablando de aplicaciones criticas en las cuales se maneja informacion confidencial de los clientes, como puede ser tarjeta de credito, cuentas de cheques, en estos casos si la informacion no esta bien resguardada se puede robar informacion o en su defecto cambiarla por otra. Por todo ello, creemos interesante que los usuarios se conciencien de la importancia de mantener los datos de estos sistemas de forma encriptada, a raiz de esto les presento algunas funciones para encriptar informacion, todas las funciones se escribiran en VB. NET y C#
1.- La Primera funcion habla del metodo de cifrado usando SHA512.
Ver Descripcion
Codigo VB
'''
''' Metodo de Cifrado usando algoritmo SHA512
'''
''' Algoritmo irreversible cifra lo que este en la propiedad cadena y lo guarda en cadenaCifrada
Public Function Crifrar_SHA512() as string
Try
Dim uEncode As New UnicodeEncoding()
Dim bytCadena() As Byte = uEncode.GetBytes(cadena)
Dim sha As New System.Security.Cryptography.SHA512Managed()
Dim hash() As Byte = sha.ComputeHash(bytCadena)
cadenaCif = Convert.ToBase64String(hash)
bError = False
sMsg = "Cifrado Exitoso."
return cadenaCif
Catch ex As Exception
bError = True
sMsg = "Error de Cifrado : " & ex.Message
End Try
End Sub
Codigo C #
///
/// Metodo de Cifrado usando algoritmo SHA512
///
/// Algoritmo irreversible cifra lo que este en la propiedad cadena y lo guarda en cadenaCifrada
public string Crifrar_SHA512()
{
try {
UnicodeEncoding uEncode = new UnicodeEncoding();
byte[] bytCadena = uEncode.GetBytes(cadena);
System.Security.Cryptography.SHA512Managed sha = new System.Security.Cryptography.SHA512Managed();
byte[] hash = sha.ComputeHash(bytCadena);
cadenaCif = Convert.ToBase64String(hash);
bError = false;
sMsg = "Cifrado Exitoso.";
return cadenaCif;
} catch (Exception ex) {
bError = true;
sMsg = "Error de Cifrado : " + ex.Message;
}
}
Ahora otra funcion utilizando el algoritmo SHA382
Codigo VB
'''
''' Metodo de Cifrado usando algoritmo SHA384
'''
''' Retorna la cadena Cifrada o en su defecto el error al Cifrar
''' Algoritmo irreversible cifra lo que este en la propiedad cadena y lo guarda en cadenaCifrada
Public Function Cifrar_SHA384() As String
Try
Dim uEncode As New UnicodeEncoding()
Dim bytCadena() As Byte = uEncode.GetBytes(cadena)
Dim sha As New System.Security.Cryptography.SHA384Managed()
Dim hash() As Byte = sha.ComputeHash(bytCadena)
cadenaCif = Convert.ToBase64String(hash)
bError = False
sMsg = "Cifrado Exitoso."
Return cadenaCif
Catch ex As Exception
bError = True
sMsg = "Error de Cifrado : " & ex.Message
Return sMsg
End Try
End Function
Codigo C#
///
/// Metodo de Cifrado usando algoritmo SHA384
///
/// Retorna la cadena Cifrada o en su defecto el error al Cifrar
/// Algoritmo irreversible cifra lo que este en la propiedad cadena y lo guarda en cadenaCifrada
public string Cifrar_SHA384()
{
try {
UnicodeEncoding uEncode = new UnicodeEncoding();
byte[] bytCadena = uEncode.GetBytes(cadena);
System.Security.Cryptography.SHA384Managed sha = new System.Security.Cryptography.SHA384Managed();
byte[] hash = sha.ComputeHash(bytCadena);
cadenaCif = Convert.ToBase64String(hash);
bError = false;
sMsg = "Cifrado Exitoso.";
return cadenaCif;
} catch (Exception ex) {
bError = true;
sMsg = "Error de Cifrado : " + ex.Message;
return sMsg;
}
}
Existen mas algoritmos de SHA , pueden las funciones quedarian igual !!! SHA1 etc, ahora si pasamos a lo mas interesante, encriptar una cadena con el algoritmo 3DES ver Descripcion , a continuacion las funciones para encriptar/desencriptar:
Codigo VB
Public Function Cifrar_3DES() As String
Try
Dim threedes As TripleDES = New TripleDESCryptoServiceProvider()
threedes.Key = StringToByte("loco", 24)
threedes.IV = StringToByte("12345678")
Dim key As Byte() = threedes.Key
Dim IV As Byte() = threedes.IV
Dim encryptor As ICryptoTransform = threedes.CreateEncryptor(key, IV)
Dim msEncrypt As New MemoryStream()
Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)
csEncrypt.Write(StringToByte(cadena), 0, StringToByte(cadena).Length)
csEncrypt.FlushFinalBlock()
Dim encrypted As Byte() = msEncrypt.ToArray()
cadenaCif = ByteToString(encrypted)
bError = False
sMsg = "Cifrado Exitoso."
Return cadenaCif
Catch ex As Exception
bError = True
sMsg = "Error de Cifrado : " & ex.Message
Return sMsg
End Try
End Function
Codigo C#
public string Cifrar_3DES()
{
try {
TripleDES threedes = new TripleDESCryptoServiceProvider();
threedes.Key = StringToByte("loco", 24);
threedes.IV = StringToByte("12345678");
byte[] key = threedes.Key;
byte[] IV = threedes.IV;
ICryptoTransform encryptor = threedes.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
csEncrypt.Write(StringToByte(cadena), 0, StringToByte(cadena).Length);
csEncrypt.FlushFinalBlock();
byte[] encrypted = msEncrypt.ToArray();
cadenaCif = ByteToString(encrypted);
bError = false;
sMsg = "Cifrado Exitoso.";
return cadenaCif;
} catch (Exception ex) {
bError = true;
sMsg = "Error de Cifrado : " + ex.Message;
return sMsg;
}
}
Funcion para Desencriptar
Codigo VB
Public Function Decifrar_3DES() As String
Try
Dim threedes As TripleDES = New TripleDESCryptoServiceProvider()
threedes.Key = StringToByte("loco", 24)
threedes.IV = StringToByte("12345678")
Dim key As Byte() = threedes.Key
Dim IV As Byte() = threedes.IV
Dim decryptor As ICryptoTransform = threedes.CreateDecryptor(key, IV)
Dim msDecrypt As New MemoryStream(cadenaCif)
Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
cadena = ByteToString(csDecrypt)
bError = False
sMsg = "Descifrado Exitoso."
Return cadena
Catch ex As Exception
bError = True
sMsg = "Descifrado fallo: " & ex.Message
Return sMsg
End Try
End Function
Code C#
public string Decifrar_3DES()
{
try {
TripleDES threedes = new TripleDESCryptoServiceProvider();
threedes.Key = StringToByte("loco", 24);
threedes.IV = StringToByte("12345678");
byte[] key = threedes.Key;
byte[] IV = threedes.IV;
ICryptoTransform decryptor = threedes.CreateDecryptor(key, IV);
MemoryStream msDecrypt = new MemoryStream(cadenaCif);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
cadena = ByteToString(csDecrypt);
bError = false;
sMsg = "Descifrado Exitoso.";
return cadena;
} catch (Exception ex) {
bError = true;
sMsg = "Descifrado fallo: " + ex.Message;
return sMsg;
}
}
Comentar que este ultimo metodo 3DES utiliza algunas funciones para conversion de datos que se ponen a continuacion:
Codigo VB
'''
''' Funcion para convertir de String a Byte
'''
'''Cadena que se convertira
''' regresa un arreglo de bytes
''' funcion utilizadad por el algortimo 3DES
Private Function StringToByte(ByVal StringToConvert As String) As Byte()
Dim CharArray As Char() = StringToConvert.ToCharArray()
Dim ByteArray As Byte() = New Byte(CharArray.Length - 1) {}
For i As Integer = 0 To CharArray.Length - 1
ByteArray(i) = Convert.ToByte(CharArray(i))
Next
Return ByteArray
End Function
'''
''' Funcion para convertir de string a bytes especificando el tamanio
'''
'''cadena a convertir
'''tamanio
''' regresa un arreglo de bytes
''' Funcion utilizada por el algoritmo 3DES
Private Function StringToByte(ByVal StringToConvert As String, ByVal length As Integer) As Byte()
Dim CharArray As Char() = StringToConvert.ToCharArray()
Dim ByteArray As Byte() = New Byte(length - 1) {}
For i As Integer = 0 To CharArray.Length - 1
ByteArray(i) = Convert.ToByte(CharArray(i))
Next
Return ByteArray
End Function
'''
''' Funcion para convertir de bytes a string
'''
'''buffer de bytes en forma de cryptostream
''' regresa una cadena
''' Funcion utilizada por el Algoritmo 3DES
Private Function ByteToString(ByVal buff As CryptoStream) As String
Dim sbinary As String = ""
Dim b As Integer = 0
Do
b = buff.ReadByte()
If b <> -1 Then
sbinary += (ChrW(b))
End If
Loop While b <> -1
Return (sbinary)
End Function
'''
''' Funcion para convertir byte a string
'''
'''buffer de bytes a convertir
''' regresa una cadena
''' Funcion utilizada por el algoritmo 3DES
Private Function ByteToString(ByVal buff As Byte()) As String
Dim sbinary As String = ""
For i As Integer = 0 To buff.Length - 1
' hex format
sbinary += buff(i).ToString("X2")
Next
Return (sbinary)
End Function
Codigo C#
///
/// Funcion para convertir de String a Byte
///
///Cadena que se convertira
/// regresa un arreglo de bytes
/// funcion utilizadad por el algortimo 3DES
private byte[] StringToByte(string StringToConvert)
{
char[] CharArray = StringToConvert.ToCharArray();
byte[] ByteArray = new byte[CharArray.Length];
for (int i = 0; i <= CharArray.Length - 1; i++) {
ByteArray[i] = Convert.ToByte(CharArray[i]);
}
return ByteArray;
}
///
/// Funcion para convertir de string a bytes especificando el tamanio
///
///cadena a convertir
///tamanio
/// regresa un arreglo de bytes
/// Funcion utilizada por el algoritmo 3DES
private byte[] StringToByte(string StringToConvert, int length)
{
char[] CharArray = StringToConvert.ToCharArray();
byte[] ByteArray = new byte[length];
for (int i = 0; i <= CharArray.Length - 1; i++) {
ByteArray[i] = Convert.ToByte(CharArray[i]);
}
return ByteArray;
}
///
/// Funcion para convertir de bytes a string
///
///buffer de bytes en forma de cryptostream
/// regresa una cadena
/// Funcion utilizada por el Algoritmo 3DES
private string ByteToString(CryptoStream buff)
{
string sbinary = "";
int b = 0;
do {
b = buff.ReadByte();
if (b != -1) {
sbinary += (Strings.ChrW(b));
}
} while (b != -1);
return (sbinary);
}
///
/// Funcion para convertir byte a string
///
///buffer de bytes a convertir
/// regresa una cadena
/// Funcion utilizada por el algoritmo 3DES
private string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i <= buff.Length - 1; i++) {
// hex format
sbinary += buff[i].ToString("X2");
}
return (sbinary);
}
Y Por ultimo les muestro una funcion para encriptar por el metodo AES:
Codigo VB
'''
''' Metodo para Cifrar usando el algoritmo AES
'''
''' Cifra el valor que este definido en cadena y lo guarda en cadenaCifrada
Public Function Cifrar_AES() As String
Dim contrasena As String = "loco"
Dim cad As String = "l0c0"
Dim algoritmo As String = "sha512"
Dim iteraciones As Integer = 1000
Dim vectorInicial As String = "1234567896541235"
Dim tamanollave As Integer = 256
Try
Dim vectorInicialBytes As Byte() = Encoding.ASCII.GetBytes(vectorInicial)
Dim cadenaValoresBytes As Byte() = Encoding.ASCII.GetBytes(cad)
Dim llaveBytes As Byte() = Encoding.UTF8.GetBytes(cadena)
Dim contra As Rfc2898DeriveBytes
contra = New Rfc2898DeriveBytes(contrasena, cadenaValoresBytes, iteraciones)
Dim tamañoLlaveBytes As Byte() = contra.GetBytes(tamanollave \ 8)
Dim llaveSimetrica As New RijndaelManaged()
llaveSimetrica.Mode = CipherMode.CBC
Dim encriptador As ICryptoTransform = llaveSimetrica.CreateEncryptor(tamañoLlaveBytes, vectorInicialBytes)
Dim lector As New MemoryStream()
Dim lectorCripo As New CryptoStream(lector, encriptador, CryptoStreamMode.Write)
lectorCripo.Write(llaveBytes, 0, llaveBytes.Length)
lectorCripo.FlushFinalBlock()
Dim textoCifradoBytes As Byte() = lector.ToArray()
lector.Close()
lectorCripo.Close()
cadenaCif = Convert.ToBase64String(textoCifradoBytes)
bError = False
sMsg = "Cifrado Exitoso."
Return cadenaCif
Catch ex As Exception
bError = True
sMsg = "Error de Cifrado : " & ex.Message
Return sMsg
End Try
End Function
'''
''' Metodo para Descifrar usando el algoritmo AES
'''
''' Descifra el valor que este definido en cadenaCifrada y lo guarda en cadena
Public Function Descifrar_AES() As String
Dim contrasena As String = "loco"
Dim cad As String = "l0c0"
Dim algoritmo As String = "sha512"
Dim iteraciones As Integer = 1000
Dim vectorInicial As String = "1234567896541235"
Dim tamanollave As Integer = 256
Try
Dim vectorInicialB As Byte()
vectorInicialB = Encoding.ASCII.GetBytes(vectorInicial)
Dim cadenaB As Byte()
cadenaB = Encoding.ASCII.GetBytes(cad)
Dim textoACifrarB As Byte()
textoACifrarB = Convert.FromBase64String(cadenaCif)
Dim contra As Rfc2898DeriveBytes
contra = New Rfc2898DeriveBytes(contrasena, cadenaB, iteraciones)
Dim llaveB As Byte()
llaveB = contra.GetBytes(tamanollave / 8)
Dim claveSimetrica As RijndaelManaged
claveSimetrica = New RijndaelManaged()
claveSimetrica.Mode = CipherMode.CBC
Dim descifrador As ICryptoTransform
descifrador = claveSimetrica.CreateDecryptor(llaveB, vectorInicialB)
Dim lector As MemoryStream
lector = New MemoryStream(textoACifrarB)
Dim crypto As CryptoStream
crypto = New CryptoStream(lector, descifrador, CryptoStreamMode.Read)
Dim textoPlanoB As Byte()
ReDim textoPlanoB(textoACifrarB.Length)
Dim bytesDesencriptados As Integer
bytesDesencriptados = crypto.Read(textoPlanoB, 0, textoPlanoB.Length)
lector.Close()
crypto.Close()
Dim textoPlano As String
textoPlano = Encoding.UTF8.GetString(textoPlanoB, 0, bytesDesencriptados)
cadena = textoPlano
bError = False
Return cadena
sMsg = "Descifrado Exitoso."
Catch ex As Exception
bError = True
sMsg = "Descifrado fallo: " & ex.Message
Return sMsg
End Try
End Function
Codigo C#
///
/// Metodo para Cifrar usando el algoritmo AES
///
/// Cifra el valor que este definido en cadena y lo guarda en cadenaCifrada
public string Cifrar_AES()
{
string contrasena = "loco";
string cad = "l0c0";
string algoritmo = "sha512";
int iteraciones = 1000;
string vectorInicial = "1234567896541235";
int tamanollave = 256;
try {
byte[] vectorInicialBytes = Encoding.ASCII.GetBytes(vectorInicial);
byte[] cadenaValoresBytes = Encoding.ASCII.GetBytes(cad);
byte[] llaveBytes = Encoding.UTF8.GetBytes(cadena);
Rfc2898DeriveBytes contra = default(Rfc2898DeriveBytes);
contra = new Rfc2898DeriveBytes(contrasena, cadenaValoresBytes, iteraciones);
byte[] tamañoLlaveBytes = contra.GetBytes(tamanollave / 8);
RijndaelManaged llaveSimetrica = new RijndaelManaged();
llaveSimetrica.Mode = CipherMode.CBC;
ICryptoTransform encriptador = llaveSimetrica.CreateEncryptor(tamañoLlaveBytes, vectorInicialBytes);
MemoryStream lector = new MemoryStream();
CryptoStream lectorCripo = new CryptoStream(lector, encriptador, CryptoStreamMode.Write);
lectorCripo.Write(llaveBytes, 0, llaveBytes.Length);
lectorCripo.FlushFinalBlock();
byte[] textoCifradoBytes = lector.ToArray();
lector.Close();
lectorCripo.Close();
cadenaCif = Convert.ToBase64String(textoCifradoBytes);
bError = false;
sMsg = "Cifrado Exitoso.";
return cadenaCif;
} catch (Exception ex) {
bError = true;
sMsg = "Error de Cifrado : " + ex.Message;
return sMsg;
}
}
///
/// Metodo para Descifrar usando el algoritmo AES
///
/// Descifra el valor que este definido en cadenaCifrada y lo guarda en cadena
public string Descifrar_AES()
{
string contrasena = "loco";
string cad = "l0c0";
string algoritmo = "sha512";
int iteraciones = 1000;
string vectorInicial = "1234567896541235";
int tamanollave = 256;
try {
byte[] vectorInicialB = null;
vectorInicialB = Encoding.ASCII.GetBytes(vectorInicial);
byte[] cadenaB = null;
cadenaB = Encoding.ASCII.GetBytes(cad);
byte[] textoACifrarB = null;
textoACifrarB = Convert.FromBase64String(cadenaCif);
Rfc2898DeriveBytes contra = default(Rfc2898DeriveBytes);
contra = new Rfc2898DeriveBytes(contrasena, cadenaB, iteraciones);
byte[] llaveB = null;
llaveB = contra.GetBytes(tamanollave / 8);
RijndaelManaged claveSimetrica = default(RijndaelManaged);
claveSimetrica = new RijndaelManaged();
claveSimetrica.Mode = CipherMode.CBC;
ICryptoTransform descifrador = default(ICryptoTransform);
descifrador = claveSimetrica.CreateDecryptor(llaveB, vectorInicialB);
MemoryStream lector = default(MemoryStream);
lector = new MemoryStream(textoACifrarB);
CryptoStream crypto = default(CryptoStream);
crypto = new CryptoStream(lector, descifrador, CryptoStreamMode.Read);
byte[] textoPlanoB = null;
textoPlanoB = new byte[textoACifrarB.Length + 1];
int bytesDesencriptados = 0;
bytesDesencriptados = crypto.Read(textoPlanoB, 0, textoPlanoB.Length);
lector.Close();
crypto.Close();
string textoPlano = null;
textoPlano = Encoding.UTF8.GetString(textoPlanoB, 0, bytesDesencriptados);
cadena = textoPlano;
bError = false;
return cadena;
sMsg = "Descifrado Exitoso.";
} catch (Exception ex) {
bError = true;
sMsg = "Descifrado fallo: " + ex.Message;
return sMsg;
}
}
Cualquier duda con el funcionamiento andamos por aqui, Saludos ... Eso es todo por este dia a cotinuacion les pongo el link al codigo fuente donde se hace uso de la clase encriptacion :
https://mega.co.nz/#!oMJ1RLiT!JZH2cB3po6kGQV8joXI95z1rESliGIMmCa3dQteYEaE