Namespaces utilizados:
- System;
- System.Security.Cryptography;
Argumentos:
- PlainText: Texto a cifrar.
- Password: Nuestra contraseña.
- hashAlgorithm: El algoritmo para generar el hash, puede ser MD5 o SHA1.
- SaltValue: Puede ser cualquier cadena.
- InitialVector: Debe ser una cadena de 16 bytes, es decir, 16 caracteres.
- PasswordIterations: Con uno o dos será suficiente.
- KeySize: Puede ser cualquiera de estos tres valores: 128, 192 o 256.
Esta función cifra:
Código
public static string Encrypt(string PlainText, string Password, string SaltValue, string hashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { try { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue); byte[] plainTextBytes = Encoding.UTF8.GetBytes(PlainText); PasswordDeriveBytes password = new PasswordDeriveBytes(Password, saltValueBytes, hashAlgorithm, PasswordIterations); byte[] keyBytes = password.GetBytes(KeySize / 8); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, InitialVectorBytes); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); byte[] cipherTextBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); string cipherText = Convert.ToBase64String(cipherTextBytes); return cipherText; } catch { MessageBox.Show("The typed information is wrong. Please, check it.", "FoS TeaM", MessageBoxButtons.OK, MessageBoxIcon.Stop); return null; } }
Y esta descifra:
Código
public static string Decrypt(string PlainText, string Password, string SaltValue, string HashAlgorithm, int PasswordIterations, string InitialVector, int KeySize) { try { byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector); byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue); byte[] cipherTextBytes = Convert.FromBase64String(PlainText); PasswordDeriveBytes password = new PasswordDeriveBytes(Password, saltValueBytes, HashAlgorithm, PasswordIterations); byte[] keyBytes = password.GetBytes(KeySize / 8); symmetricKey.Mode = CipherMode.CBC; ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, InitialVectorBytes); int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); return plainText; } catch { MessageBox.Show("The typed information is wrong. Please, check it.", "FoS TeaM", MessageBoxButtons.OK, MessageBoxIcon.Stop); return null; } }
Salu2