simple password example encrypt decrypt cipher c# encryption encryption-symmetric des

password - Cifrado realmente simple con C#y SymmetricAlgorithm



simple encryption c# (3)

Estoy buscando un método muy simple de cripta / descifrado. Usaré siempre la misma llave estática. Soy consciente de los riesgos de este enfoque. Actualmente estoy usando el siguiente código, pero no genera el mismo resultado después de cifrar y descifrar la misma cadena (hay algo de basura en medio de la cadena).

public static string Crypt(this string text) { string result = null; if (!String.IsNullOrEmpty(text)) { byte[] plaintextBytes = Encoding.Unicode.GetBytes(text); SymmetricAlgorithm symmetricAlgorithm = DES.Create(); symmetricAlgorithm.Key = new byte[8] {1, 2, 3, 4, 5, 6, 7, 8}; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateEncryptor(), CryptoStreamMode.Write)) { cryptoStream.Write(plaintextBytes, 0, plaintextBytes.Length); } result = Encoding.Unicode.GetString(memoryStream.ToArray()); } } return result; } public static string Decrypt(this string text) { string result = null; if (!String.IsNullOrEmpty(text)) { byte[] encryptedBytes = Encoding.Unicode.GetBytes(text); SymmetricAlgorithm symmetricAlgorithm = DES.Create(); symmetricAlgorithm.Key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; using (MemoryStream memoryStream = new MemoryStream(encryptedBytes)) { using (CryptoStream cryptoStream = new CryptoStream(memoryStream, symmetricAlgorithm.CreateDecryptor(), CryptoStreamMode.Read)) { byte[] decryptedBytes = new byte[encryptedBytes.Length]; cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length); result = Encoding.Unicode.GetString(decryptedBytes); } } } return result; }

Puedo cambiar lo que sea necesario, sin límites (pero solo quiero tener un método para cifrar y otro para descifrar sin compartir las variables entre ellos).

Gracias.


¿Qué tal algo como esto?

Código

using System; using System.Security.Cryptography; using System.Text; public static class StringUtil { private static byte[] key = new byte[8] {1, 2, 3, 4, 5, 6, 7, 8}; private static byte[] iv = new byte[8] {1, 2, 3, 4, 5, 6, 7, 8}; public static string Crypt(this string text) { SymmetricAlgorithm algorithm = DES.Create(); ICryptoTransform transform = algorithm.CreateEncryptor(key, iv); byte[] inputbuffer = Encoding.Unicode.GetBytes(text); byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); return Convert.ToBase64String(outputBuffer); } public static string Decrypt(this string text) { SymmetricAlgorithm algorithm = DES.Create(); ICryptoTransform transform = algorithm.CreateDecryptor(key, iv); byte[] inputbuffer = Convert.FromBase64String(text); byte[] outputBuffer = transform.TransformFinalBlock(inputbuffer, 0, inputbuffer.Length); return Encoding.Unicode.GetString(outputBuffer); } }

Prueba de unidad

[Test] public void Test() { string expected = "this is my test string"; string a = expected.Crypt(); Debug.WriteLine(a); string actual = a.Decrypt(); Assert.AreEqual(expected, actual); }

EDITAR:

Para aclarar: soy consciente de que esto no es una buena práctica.

"Soy consciente de los riesgos de este enfoque".

Iv''e asumió que el OP también está al tanto y realizará cambios relevantes en el código antes de considerar el uso de algo como esto en un entorno de producción.

La pregunta enfatiza la simplicidad sobre la buena práctica.


Deberá establecer el modo de cifrado en CipherMode.ECB o usar un IV.

SymmetricAlgorithm symmetricAlgorithm = DES.Create(); symmetricAlgorithm.Key = new byte[8] { 1, 2, 3, 4, 5, 6, 7, 8 }; symmetricAlgorithm.Mode = CipherMode.ECB; ...

Otro punto es no usar la codificación Unicode. Utilice Base64 en su lugar. Unicode podría "destruir" los bytes que no son UTF-16.


Si no quiere manejar las teclas usted mismo, deje que el sistema operativo lo haga por usted. Por ejemplo, use Windows Data Protection (DPAPI).

Puede escribir su propia versión basada en string de los métodos System.Security.Cryptography.ProtectedData.Protect y Unprotect usando algo como:

public static string Crypt (this string text) { return Convert.ToBase64String ( ProtectedData.Protect ( Encoding.Unicode.GetBytes (text) ) ); } public static string Derypt (this string text) { return Encoding.Unicode.GetString ( ProtectedData.Unprotect ( Convert.FromBase64String (text) ) ); }