/// <summary> /// Contructor por defecto. /// </summary> /// <param name="alg">Proveedor (algoritmo) seleccionado.</param> /// <param name="action">Acción a realizar.</param> internal CryptoServiceProvider(CryptoProvider alg, CryptoAction action) { // asignamos las opciones seleccionadas. // proveedor (algoritmo) de encripción y acción a realizar. this.algorithm = alg; this.cAction = action; }
public void EncryptDecryptFile(string InFileName, string OutFileName, CryptoAction Action) { bool flag = !File.Exists(InFileName); if (flag) { throw new Exception("No se ha encontrado el archivo."); } checked { try { bool flag2 = stringKey == null || stringIV == null; if (flag2) { throw new Exception("Error al inicializar la clave y el vector."); } FileStream fileStream = new FileStream(InFileName, FileMode.Open, FileAccess.Read); FileStream fileStream2 = new FileStream(OutFileName, FileMode.OpenOrCreate, FileAccess.Write); fileStream2.SetLength(0L); byte[] key = MakeKeyByteArray(); byte[] iV = MakeIVByteArray(); byte[] buffer = new byte[4097]; long length = fileStream.Length; long num = 0L; ICryptoTransform serviceProvider = new CryptoServiceProvider((CryptoServiceProvider.CryptoProvider)algorithm, (CryptoServiceProvider.CryptoAction)Action).GetServiceProvider(key, iV); CryptoStream cryptoStream = null; if (Action != CryptoAction.Encrypt) { if (Action == CryptoAction.Desencrypt) { cryptoStream = new CryptoStream(fileStream2, serviceProvider, CryptoStreamMode.Write); } } else { cryptoStream = new CryptoStream(fileStream2, serviceProvider, CryptoStreamMode.Write); } while (num < length) { int num2 = fileStream.Read(buffer, 0, 4096); cryptoStream.Write(buffer, 0, num2); num += unchecked ((long)num2); } bool flag3 = cryptoStream != null; if (flag3) { cryptoStream.Close(); } fileStream.Close(); fileStream2.Close(); } catch (Exception ex) { throw ex; } } }
private static ICryptoTransform CreateCryptoTransform(SymmetricAlgorithm algorithm, CryptoAction action) { byte[] key = Encoding.ASCII.GetBytes(stringKey); byte[] vector = Encoding.ASCII.GetBytes(stringVector); return action == CryptoAction.Encrypt ? algorithm.CreateEncryptor(key, vector) : algorithm.CreateDecryptor(key, vector); }
private static byte[] ExecuteCryptoAction(byte[] textArray, CryptoAction action) { var algorithm = SymmetricAlgorithm.Create(); using (var memory = new MemoryStream()) { using (var transform = CreateCryptoTransform(algorithm, action)) { using (var cryptoStream = new CryptoStream(memory, transform, CryptoStreamMode.Write)) cryptoStream.Write(textArray, 0, textArray.Length); } return memory.ToArray(); } }
private string EncryptDecryptString(string Password, string InputString, CryptoAction direction, byte[] BT = null) { byte[] bytKey; byte[] bytIV; bytKey = CreateKey(Password); bytIV = CreateIV(Password); switch (direction) { case CryptoAction.ActionEncrypt: { return(""); } case CryptoAction.ActionDecrypt: { return(DecryptStringMain(BT, bytKey, bytIV, direction)); } } return(""); }
//Devuelve la cadena cifrada. public string CryptoDecryptor(string cadenaOriginal, CryptoAction accion) { //creamos el flujo tomando la memoria como respaldo. MemoryStream memStream; try { //verificamos que la llave y el VI han sido proporcionados. if (_key != null && _IV != null) { //obtenemos el arreglo de bytes correspondiente a la llave //y al vector de inicialización. byte[] key = MakeKeyByteArray(); byte[] IV = MakeIVByteArray(); //convertimos el mensaje original en sus correspondiente //arreglo de bytes. byte[] textoplano = (accion == CryptoAction.Encrypt ? Encoding.UTF8.GetBytes(cadenaOriginal) : Convert.FromBase64String(cadenaOriginal)); //creamos el flujo memStream = new MemoryStream(cadenaOriginal.Length * (accion == CryptoAction.Encrypt ? 2 : 1)); //obtenemos nuestro objeto cifrador, usando la clase //CryptoServiceProvider codificada anteriormente. CryptoServiceProvider cryptoProvider = new CryptoServiceProvider((CryptoServiceProvider.CryptoProvider) this.algorithm, (CryptoServiceProvider.CryptoAction)accion); ICryptoTransform transform = cryptoProvider.GetServiceProvider(key, IV); //creamos el flujo de cifrado, usando el objeto cifrador creado y almancenando //el resultado en el flujo MemoryStream. CryptoStream cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write); //ciframos el mensaje. cryptoStream.Write(textoplano, 0, textoplano.Length); //cerramos el flujo de cifrado. cryptoStream.Close(); } else { throw new Exception("Error al inicializar la clave y el vector"); } } catch { throw; } return(accion == CryptoAction.Encrypt ? Convert.ToBase64String(memStream.ToArray()) : Encoding.UTF8.GetString(memStream.ToArray())); }
private String GetEncryptionResult(CryptoAction action, String incomingText) { String result = ""; int power = alphabet.Length; int keyword_index = 0; foreach (char symbol in incomingText) { int c = Array.IndexOf(alphabet, symbol); int k = Array.IndexOf(alphabet, key[keyword_index]); int p = 0; switch (action) { case (CryptoAction.DECODE): { p = (c + power - k) % power; break; }; case (CryptoAction.ENCODE): { p = (c + k) % power; break; }; } result += alphabet[p]; keyword_index = GetKeywordIndex(keyword_index, key.Length); } return(result); }
private void FileSelectButton_Click(object sender, RoutedEventArgs e) { bool? result = FileSelector.ShowDialog(); if (result == true) { FilePathLabel.Content = (FileSelector.FileName.Split('\\'))[FileSelector.FileName.Split('\\').Length - 1]; if (FileSelector.FileName.EndsWith(".enc")) { EncryptDecryptButton.Content = "Decrypt"; taskType = CryptoAction.Decrypting; } else { EncryptDecryptButton.Content = "Encrypt"; taskType = CryptoAction.Encrypting; } } }
private string DecryptStringMain(byte[] InputString, byte[] bytKey, byte[] bytIV, CryptoAction Direction) { byte[] inputInBytes = InputString; byte[] result = null; using (MemoryStream encryptedStream = new MemoryStream()) { CryptoStream csCryptoStream = null; System.Security.Cryptography.RijndaelManaged cspRijndael = new System.Security.Cryptography.RijndaelManaged(); cspRijndael.Padding = PaddingMode.ISO10126; switch (Direction) { case CryptoAction.ActionEncrypt: { csCryptoStream = new CryptoStream(encryptedStream, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write); break; } case CryptoAction.ActionDecrypt: { csCryptoStream = new CryptoStream(encryptedStream, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write); break; } } csCryptoStream.Write(inputInBytes, 0, inputInBytes.Length); csCryptoStream.FlushFinalBlock(); encryptedStream.Position = 0; result = new byte[encryptedStream.Length - 1 + 1]; encryptedStream.Read(result, 0, (int)encryptedStream.Length); } return(new UTF8Encoding().GetString(result)); }
private void EncryptOrDecryptFile(string strInputFile, string strOutputFile, byte[] bytKey, byte[] bytIV, CryptoAction Direction) { try //In case of errors. { //Setup file streams to handle input and output. fsInput = new System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read); fsOutput = new System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write); fsOutput.SetLength(0); //make sure fsOutput is empty //Declare variables for encrypt/decrypt process. byte[] bytBuffer = new byte[4097]; //holds a block of bytes for processing long lngBytesProcessed = 0; //running count of bytes processed long lngFileLength = fsInput.Length; //the input file's length int intBytesInCurrentBlock = 0; //current bytes being processed CryptoStream csCryptoStream = null; //Declare your CryptoServiceProvider. System.Security.Cryptography.RijndaelManaged cspRijndael = new System.Security.Cryptography.RijndaelManaged(); //Setup Progress Bar pbStatus.Value = 0; pbStatus.Maximum = 100; //Determine if ecryption or decryption and setup CryptoStream. switch (Direction) { case CryptoAction.ActionEncrypt: csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write); break; case CryptoAction.ActionDecrypt: csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write); break; } //Use While to loop until all of the file is processed. while (lngBytesProcessed < lngFileLength) { //Read file with the input filestream. intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096); //Write output file with the cryptostream. csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock); //Update lngBytesProcessed lngBytesProcessed = lngBytesProcessed + System.Convert.ToInt64(intBytesInCurrentBlock); //Update Progress Bar pbStatus.Value = System.Convert.ToInt32((lngBytesProcessed / (double)lngFileLength) * 100); } //Close FileStreams and CryptoStream. csCryptoStream.Close(); fsInput.Close(); fsOutput.Close(); //If encrypting then delete the original unencrypted file. if (Direction == CryptoAction.ActionEncrypt) { FileInfo fileOriginal = new FileInfo(strFileToEncrypt); fileOriginal.Delete(); } //If decrypting then delete the encrypted file. if (Direction == CryptoAction.ActionDecrypt) { FileInfo fileEncrypted = new FileInfo(strFileToDecrypt); fileEncrypted.Delete(); } //Update the user when the file is done. string Wrap = "\r" + "\n"; if (Direction == CryptoAction.ActionEncrypt) { MessageBox.Show("Encryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information); //Update the progress bar and textboxes. pbStatus.Value = 0; txtFileToEncrypt.Text = "Click Browse to load file."; txtPassEncrypt.Text = ""; txtConPassEncrypt.Text = ""; txtDestinationEncrypt.Text = ""; btnChangeEncrypt.Enabled = false; btnEncrypt.Enabled = false; } else { //Update the user when the file is done. MessageBox.Show("Decryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information); //Update the progress bar and textboxes. pbStatus.Value = 0; txtFileToDecrypt.Text = "Click Browse to load file."; txtPassDecrypt.Text = ""; txtConPassDecrypt.Text = ""; txtDestinationDecrypt.Text = ""; btnChangeDecrypt.Enabled = false; btnDecrypt.Enabled = false; } //Catch file not found error. } //TODO: INSTANT C# TODO TASK: There is no C# equivalent to 'When' //TODO: INSTANT C# TODO TASK: Calls to the VB 'Err' object are not converted by Instant C#: catch // When Err.Number = 53 //if file not found { MessageBox.Show("Please check to make sure the path and filename" + "are correct and if the file exists.", "Invalid Path or Filename", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); //Catch all other errors. And delete partial files. fsInput.Close(); fsOutput.Close(); if (Direction == CryptoAction.ActionDecrypt) { FileInfo fileDelete = new FileInfo(txtDestinationDecrypt.Text); fileDelete.Delete(); pbStatus.Value = 0; txtPassDecrypt.Text = ""; txtConPassDecrypt.Text = ""; MessageBox.Show("Please check to make sure that you entered the correct" + "password.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { FileInfo fileDelete = new FileInfo(txtDestinationEncrypt.Text); fileDelete.Delete(); pbStatus.Value = 0; txtPassEncrypt.Text = ""; txtConPassEncrypt.Text = ""; MessageBox.Show("This file cannot be encrypted.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
/// <summary> /// Cifrar o Descifrar el archivo especificado y almacenada la información /// cifrada en el archivo destino proporcionado. /// </summary> /// <param name="InFileName">Nombre del archivo original.</param> /// <param name="OutFileName">Nombre del archivo destino.</param> /// <param name="Action">Acción a realizar sobre el archivo.</param> public void CifrarDescifrarArchivo(string InFileName, string OutFileName, CryptoAction Action) { // si el archivo especificado no existe, if (!File.Exists(InFileName)) { // generamos una excepción informándolo. throw new Exception("No se ha encontrado el archivo."); } try { // si la llave de cifrado y el VI están establecidos if (stringKey != null && stringIV != null) { // creamos el flujo de entrada, desde el archivo original. FileStream fsIn = new FileStream(InFileName, FileMode.Open, FileAccess.Read); // creamos el flujo de salida, hacía el archivo de salida especificado. FileStream fsOut = new FileStream(OutFileName, FileMode.OpenOrCreate, FileAccess.Write); // establecemos la capacidad del archivo de salida a 0. fsOut.SetLength(0); byte[] key = MakeKeyByteArray(); // creamos la llave de cifrado. byte[] IV = MakeIVByteArray(); // y el vector de inicialización. byte[] byteBuffer = new byte[4096]; // creamos un buffer de bytes. long largoArchivo = fsIn.Length; // establecemos variables de control long bytesProcesados = 0; // para la lectura y escritura de los archivos. int bloqueBytes = 0; // creamos nuestro objeto cifrador, desde la clase CryptoServiceProvider. CryptoServiceProvider cryptoProvider = new CryptoServiceProvider((CryptoServiceProvider.CryptoProvider) this.algorithm, (CryptoServiceProvider.CryptoAction)Action); ICryptoTransform transform = cryptoProvider.GetServiceProvider(key, IV); CryptoStream cryptoStream = null; // dependiendo de la acción especificada, switch (Action) { case CryptoAction.Encrypt: // creamos el cifrador, almacenando el resultado en el flujo de salida. cryptoStream = new CryptoStream(fsOut, transform, CryptoStreamMode.Write); break; // ó el descifrador, almacenando el resultado en el flujo de salida. case CryptoAction.Desencrypt: cryptoStream = new CryptoStream(fsOut, transform, CryptoStreamMode.Write); break; } // mientras el número de bytes procesados es menor que el // largo del archivo while (bytesProcesados < largoArchivo) { // leemos un bloque de datos y lo almacenamos en el buffer. bloqueBytes = fsIn.Read(byteBuffer, 0, 4096); // ciframos los datos del buffer cryptoStream.Write(byteBuffer, 0, bloqueBytes); // incrementamos el contador de bytes procesados. bytesProcesados += (long)bloqueBytes; } // cerramos los flujos de datos. if (cryptoStream != null) { cryptoStream.Close(); } fsIn.Close(); fsOut.Close(); } else { // si los valores de la llave de cifrado y/o el VI no se han // asignado, lo informámos mediante una excepción. throw new Exception("Error al inicializar la clave y el vector."); } } catch { throw; } }
internal ICryptoTransform GetServiceProvider(byte[] Key, byte[] IV) { ICryptoTransform cryptoTransform = null; ICryptoTransform result; switch (algorithm) { case CryptoProvider.DES: { DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider(); CryptoAction cryptoAction = cAction; if (cryptoAction != CryptoAction.Encrypt) { if (cryptoAction == CryptoAction.Desencrypt) { cryptoTransform = dESCryptoServiceProvider.CreateDecryptor(Key, IV); } } else { cryptoTransform = dESCryptoServiceProvider.CreateEncryptor(Key, IV); } result = cryptoTransform; break; } case CryptoProvider.TripleDES: { TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider(); CryptoAction cryptoAction2 = cAction; if (cryptoAction2 != CryptoAction.Encrypt) { if (cryptoAction2 == CryptoAction.Desencrypt) { cryptoTransform = tripleDESCryptoServiceProvider.CreateDecryptor(Key, IV); } } else { cryptoTransform = tripleDESCryptoServiceProvider.CreateEncryptor(Key, IV); } result = cryptoTransform; break; } case CryptoProvider.RC2: { RC2CryptoServiceProvider rC2CryptoServiceProvider = new RC2CryptoServiceProvider(); CryptoAction cryptoAction3 = cAction; if (cryptoAction3 != CryptoAction.Encrypt) { if (cryptoAction3 == CryptoAction.Desencrypt) { cryptoTransform = rC2CryptoServiceProvider.CreateDecryptor(Key, IV); } } else { cryptoTransform = rC2CryptoServiceProvider.CreateEncryptor(Key, IV); } result = cryptoTransform; break; } case CryptoProvider.Rijndael: { Rijndael rijndael = new RijndaelManaged(); CryptoAction cryptoAction4 = cAction; if (cryptoAction4 != CryptoAction.Encrypt) { if (cryptoAction4 == CryptoAction.Desencrypt) { cryptoTransform = rijndael.CreateDecryptor(Key, IV); } } else { cryptoTransform = rijndael.CreateEncryptor(Key, IV); } result = cryptoTransform; break; } default: throw new CryptographicException("Error al inicializar al proveedor de cifrado"); } return(result); }
internal CryptoServiceProvider(CryptoProvider alg, CryptoAction action) { algorithm = alg; cAction = action; }
public CryptoServiceProvider(CryptoProvider Alg, CryptoAction Action) { //asignamos las opciones seleccionadas. this.algorithm = Alg; this.cAction = Action; }