Enlace a video
Enlace a Ejemplo
Saludos.
Codigo C#Function asc2hex(ByVal StrName As String) As String Dim cont As Integer = 0 Dim strAcum As String = "" For cont = 1 To Len(StrName) strAcum &= Hex(Asc(Mid(StrName, cont, 1))) Next cont Return strAcum End Function
public string asc2hex(string StrName) { int cont = 0; string strAcum = ""; for (cont = 1; cont <= Strings.Len(StrName); cont++) { strAcum += Conversion.Hex(Strings.Asc(Strings.Mid(StrName, cont, 1))); } return strAcum; }
Public Function hexbi(ByVal hex As String) As Long Dim bin As String = "" bin = Convert.ToString(Convert.ToInt32(hex, 16), 2) Return bin End Function
public long hexbi(string hex) { string bin = ""; bin = Convert.ToString(Convert.ToInt32(hex, 16), 2); return bin; }
Codigo C#.Public Function asciiaHex(ByVal ascci As String) As ArrayList Dim arr As New ArrayList Dim sBufer As StringBuilder = New StringBuilder Dim i As Integer For i = 0 To ascci.Length - 1 sBufer.Append(Convert.ToInt32(ascci(i)).ToString("x")) arr.Add(Convert.ToInt32(ascci(i)).ToString("x")) Next Return arr End Function
Funcion que convierte un arreglo de bytes en Hexadecimal.public ArrayList asciiaHex(string ascci) { ArrayList arr = new ArrayList(); StringBuilder sBufer = new StringBuilder(); int i = 0; for (i = 0; i <= ascci.Length - 1; i++) { sBufer.Append(Convert.ToInt32(ascci[i]).ToString("x")); arr.Add(Convert.ToInt32(ascci[i]).ToString("x")); } return arr; }
Codigo C#.Public Function ByteToHex(ByVal comByte As Byte()) As String 'Creamos un objeto stringBuilder Dim builder As New StringBuilder(comByte.Length * 3) 'Recorrer Cada Byte de la matriz For Each data As Byte In comByte If data <> 0 Then builder.Append(Convert.ToString(data, 16).PadLeft(2, "0"c).PadRight(3, " "c)) 'Convertir el byte a string y agregar a el stringbuilder End If Next 'Regresamos el valor convertido Return builder.ToString().ToUpper() End Function
Estas cuatro funciones son muy importantes , cuando trabajamos con dispositivos seriales en el siguiente post les enseñare como comente arriba, como manipular un billetero por el puerto serial.public string ByteToHex(byte[] comByte) { //Creamos un objeto stringBuilder StringBuilder builder = new StringBuilder(comByte.Length * 3); //Recorrer Cada Byte de la matriz foreach (byte data in comByte) { if (data != 0) { builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' ')); //Convertir el byte a string y agregar a el stringbuilder } } //Regresamos el valor convertido return builder.ToString().ToUpper(); }
Private Function girarImagen(ByVal imgOriginal As Image, ByVal grados As Decimal) As Image Try If rdbDerecha.Checked Then grados = -grados End If 'Asignamos imagen original Dim bmp As New Bitmap(imgOriginal) 'Serie de Puntos para conocer las esquinas de la imagen Dim lrg As Single = bmp.Width Dim alt As Single = bmp.Height Dim esq As Point() = {New Point(0, 0), New Point(lrg, 0), New Point(0, alt), New Point(lrg, alt)} ' Establece centro del Rectangulo Dim cx As Single = lrg / 2 Dim cy As Single = alt / 2 Dim i As Long For i = 0 To 3 esq(i).X -= cx esq(i).Y -= cy Next i Dim PI As Decimal = 3.1416 ' Rotacion. Dim angtheta As Single = Single.Parse(grados) * PI / 180.0 Dim sintheta As Single = Math.Sin(angtheta) Dim costheta As Single = Math.Cos(angtheta) Dim X As Single Dim Y As Single For i = 0 To 3 X = esq(i).X Y = esq(i).Y esq(i).X = X * costheta + Y * sintheta esq(i).Y = -X * sintheta + Y * costheta Next i ' Translacion X >= 0 and Y >=0 para todas las esquinas. Dim xmin As Single = esq(0).X Dim ymin As Single = esq(0).Y For i = 1 To 3 If xmin > esq(i).X Then xmin = esq(i).X If ymin > esq(i).Y Then ymin = esq(i).Y Next i For i = 0 To 3 esq(i).X -= xmin esq(i).Y -= ymin Next i ' Crear bitmap de salida y objetco graphics. Dim bmpSalida As New Bitmap(CInt(-2 * xmin), CInt(-2 * ymin)) Dim grSalida As Graphics = Graphics.FromImage(bmpSalida) 'Preservar Ultima Esquina ReDim Preserve esq(2) 'Pintamos resultado de imagen Girada. grSalida.DrawImage(bmp, esq) Return bmpSalida Catch ex As Exception MsgBox("Error al Girar Imagen, Error:" & ex.Message, MsgBoxStyle.Critical, "Excepcion") Return Nothing End Try End FunctionCodigo C#private Image girarImagen(Image imgOriginal, decimal grados) { try { if (rdbDerecha.Checked) { grados = -grados; } //Asignamos imagen original Bitmap bmp = new Bitmap(imgOriginal); //Serie de Puntos para conocer las esquinas de la imagen float lrg = bmp.Width; float alt = bmp.Height; Point[] esq = { new Point(0, 0), new Point(lrg, 0), new Point(0, alt), new Point(lrg, alt) }; // Establece centro del Rectangulo float cx = lrg / 2; float cy = alt / 2; long i = 0; for (i = 0; i <= 3; i++) { esq(i).X -= cx; esq(i).Y -= cy; } decimal PI = 3.1416; // Rotacion. float angtheta = float.Parse(grados) * PI / 180.0; float sintheta = Math.Sin(angtheta); float costheta = Math.Cos(angtheta); float X = 0; float Y = 0; for (i = 0; i <= 3; i++) { X = esq(i).X; Y = esq(i).Y; esq(i).X = X * costheta + Y * sintheta; esq(i).Y = -X * sintheta + Y * costheta; } // Translacion X >= 0 and Y >=0 para todas las esquinas. float xmin = esq(0).X; float ymin = esq(0).Y; for (i = 1; i <= 3; i++) { if (xmin > esq(i).X) xmin = esq(i).X; if (ymin > esq(i).Y) ymin = esq(i).Y; } for (i = 0; i <= 3; i++) { esq(i).X -= xmin; esq(i).Y -= ymin; } // Crear bitmap de salida y objetco graphics. Bitmap bmpSalida = new Bitmap(Convert.ToInt32(-2 * xmin), Convert.ToInt32(-2 * ymin)); Graphics grSalida = Graphics.FromImage(bmpSalida); //Preservar Ultima Esquina Array.Resize(ref esq, 3); //Pintamos resultado de imagen Girada. grSalida.DrawImage(bmp, esq); return bmpSalida; } catch (Exception ex) { Interaction.MsgBox("Error al Girar Imagen, Error:" + ex.Message, MsgBoxStyle.Critical, "Excepcion"); return null; } }Pues ahi esta el codigo para girar la imagen, el ejemplo completo se los dejo en el siguiente link: girarImagen.rar (75 KB) https://mega.co.nz/#!wVpmCDRA!M7jSTF2N-vGMjSGsHBAz81o9vMUg69wG3_vSG31ZuDM Cualquier pregunta o duda por aqui andamos. Saludos...
Private Function buscarLetra(ByVal nombreCancion As String, ByVal nombreArtista As String) As String Dim lw As LyricWiki = New LyricWiki Dim lr As LyricsResult = lw.getSong(nombreArtista, nombreCancion) Dim html As String = RetHTML(lr.url) If html <> "" And html IsNot Nothing Then 'Buscamos donde empieza letra de cancion Dim primerCoincid As Integer = html.IndexOf("</div> &#") 'Buscamos donde termina la cancion Dim segundaConcid As Integer = html.IndexOf("NewPP") 'Se Determina largo de la cancion Dim largo As Integer = segundaConcid - primerCoincid 'Leemos caracteres ASCII de la cancion Dim letraAscii As String = Mid((html), primerCoincid + 1, largo) 'Separamos la cancion por cierre de corchete Dim renglonAScii() As String = Split(letraAscii, ">") Dim arrCodigos As New ArrayList Dim cancion As String = "" 'Recorremos los renglones de la cancion For i = 0 To renglonAScii.Count - 1 'Separamos letra por letra del renglon Dim codigo() As String = Split(renglonAScii(i).ToString, ";") Try For j = 0 To codigo.Count - 2 'Eliminamos caracters de escape Dim cod As String = Trim(Replace(codigo(j), "&#", "")) 'Se convierte de ASCII a Texto cancion &= Chr(cod) Next cancion += vbCrLf Catch ex As Exception cancion &= "" End Try Next Return cancion Else Return "" End If End FunctionCodigo C#private string buscarLetra(string nombreCancion, string nombreArtista) { LyricWiki lw = new LyricWiki(); LyricsResult lr = lw.getSong(nombreArtista, nombreCancion); string html = RetHTML(lr.url); if (!string.IsNullOrEmpty(html) & html != null) { //Buscamos donde empieza letra de cancion int primerCoincid = html.IndexOf("</div> &#"); //Buscamos donde termina la cancion int segundaConcid = html.IndexOf("NewPP"); //Se Determina largo de la cancion int largo = segundaConcid - primerCoincid; //Leemos caracteres ASCII de la cancion string letraAscii = Strings.Mid((html), primerCoincid + 1, largo); //Separamos la cancion por cierre de corchete string[] renglonAScii = Strings.Split(letraAscii, ">"); ArrayList arrCodigos = new ArrayList(); string cancion = ""; //Recorremos los renglones de la cancion for (i = 0; i <= renglonAScii.Count - 1; i++) { //Separamos letra por letra del renglon string[] codigo = Strings.Split(renglonAScii[i].ToString(), ";"); try { for (j = 0; j <= codigo.Count - 2; j++) { //Eliminamos caracters de escape string cod = Strings.Trim(Strings.Replace(codigo[j], "&#", "")); //Se convierte de ASCII a Texto cancion += Strings.Chr(cod); } cancion += Constants.vbCrLf; } catch (Exception ex) { cancion += ""; } } return cancion; } else { return ""; } }Esta clase es la que nos devuelve la letra de la cancion en caso de existir, el funcionamiento es muy sencillo pones el nombre del artista y el nombre de la cancion que estas buscando, el boton buscar solamente llama al metodo de buscarCancion del webservice, si no encuentra la cancion nos devuelve vacio y eso se le pasa al textbox enriquecido. Les dejo el codigo de este modulo de busqueda de canciones. P.D. NO le digan a wikilyrics. wikiLyrics.rar (128 KB) https://mega.co.nz/#!hR4kRYBI!WhD5CiiW9ZZ3c6nIqoOFj3eO0cEIjYMhZLSufdV__CA Saludos.
''' ''' 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 SubCodigo 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 FunctionCodigo 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 VBPublic 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 FunctionCodigo 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 VBPublic 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 FunctionCode 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 FunctionCodigo 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 FunctionCodigo 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