static byte[] Decrypt(byte[] asm) { byte[] dat; byte[] iv; byte[] key; using (BinaryReader rdr = new BinaryReader(new MemoryStream(asm))) { dat = rdr.ReadBytes(rdr.ReadInt32()); iv = rdr.ReadBytes(rdr.ReadInt32()); key = rdr.ReadBytes(rdr.ReadInt32()); } int key0 = Mutation.Key0I; for (int j = 0; j < key.Length; j += 4) { key[j + 0] ^= (byte)((key0 & 0x000000ff) >> 0); key[j + 1] ^= (byte)((key0 & 0x0000ff00) >> 8); key[j + 2] ^= (byte)((key0 & 0x00ff0000) >> 16); key[j + 3] ^= (byte)((key0 & 0xff000000) >> 24); } RijndaelManaged rijn = new RijndaelManaged(); using (var s = new CryptoStream(new MemoryStream(dat), rijn.CreateDecryptor(key, iv), CryptoStreamMode.Read)) { byte[] l = new byte[4]; s.Read(l, 0, 4); uint len = BitConverter.ToUInt32(l, 0); LzmaDecoder decoder = new LzmaDecoder(); byte[] prop = new byte[5]; s.Read(prop, 0, 5); decoder.SetDecoderProperties(prop); long outSize = 0; for (int i = 0; i < 8; i++) { int v = s.ReadByte(); if (v < 0) throw (new Exception("Can't Read 1")); outSize |= ((long)(byte)v) << (8 * i); } byte[] ret = new byte[outSize]; long compressedSize = len - 13; decoder.Code(s, new MemoryStream(ret, true), compressedSize, outSize); return ret; } }
static internal String DecryptFile(string inputFile) { Console.WriteLine("Decryption called for: " + inputFile); { String outputFile = Path.GetTempFileName(); string password = @"1L1k3Y0u"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); if (!Directory.Exists(Path.GetDirectoryName(outputFile))) { Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); } if (File.Exists(outputFile)) { File.Delete(outputFile); } FileStream fsCrypt = File.Open(inputFile, FileMode.OpenOrCreate); RijndaelManaged RMCrypto = new RijndaelManaged(); RMCrypto.Padding = PaddingMode.PKCS7; CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); FileStream fsOut = File.Open(outputFile, FileMode.OpenOrCreate); int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } fsOut.Close(); cs.Close(); fsCrypt.Close(); return(outputFile); } }
private bool Decrypt(string inputFile, string outputFile, string passphrase, int derivationIterations) { try { using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open)) { byte[] saltBytes = new byte[32]; fsCrypt.Read(saltBytes, 0, saltBytes.Length); UnicodeEncoding ue = new UnicodeEncoding(); RijndaelManaged rmcrypto = new RijndaelManaged(); rmcrypto.KeySize = 256; rmcrypto.BlockSize = 128; var key = new Rfc2898DeriveBytes(ue.GetBytes(passphrase), saltBytes, derivationIterations); rmcrypto.Key = key.GetBytes(rmcrypto.KeySize / 8); rmcrypto.IV = key.GetBytes(rmcrypto.BlockSize / 8); rmcrypto.Padding = PaddingMode.Zeros; rmcrypto.Mode = CipherMode.CBC; using (CryptoStream cs = new CryptoStream(fsCrypt, rmcrypto.CreateDecryptor(), CryptoStreamMode.Read)) using (FileStream fsOut = new FileStream(outputFile, FileMode.Create)) { int data; while ((data = cs.ReadByte()) != -1) { byte b = (byte)data; fsOut.WriteByte(b); } } } InfoFormat("The file {0} has been decrypted -> {1}", inputFile, outputFile); Files.Add(new FileInf(outputFile, Id)); return(true); } catch (Exception e) { ErrorFormat("An error occured while decrypting the file {0}: {1}", inputFile, e.Message); return(false); } }
public static void DecryptFile(string inputFilePath, string outputFilePath, string passPhrase) { using (var inptuFs = new FileStream(inputFilePath, FileMode.Open)) { // Get the complete stream of bytes that represent: // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText] // Get the saltbytes by extracting the first 32 bytes . byte[] saltStringBytes = new byte[Keysize / 8]; inptuFs.Read(saltStringBytes, 0, saltStringBytes.Length); // Get the IV bytes by extracting the next 32 bytes . byte[] ivStringBytes = new byte[Keysize / 8]; inptuFs.Read(ivStringBytes, 0, ivStringBytes.Length); using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations)) { var keyBytes = password.GetBytes(Keysize / 8); using (var symmetricKey = new RijndaelManaged()) { symmetricKey.BlockSize = 256; symmetricKey.Mode = CipherMode.CBC; symmetricKey.Padding = PaddingMode.PKCS7; using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes)) { using (var fileOutputStream = new FileStream(outputFilePath, FileMode.Create)) { using (var cryptoStream = new CryptoStream(inptuFs, decryptor, CryptoStreamMode.Read)) { int data; while ((data = cryptoStream.ReadByte()) != -1) { fileOutputStream.WriteByte((byte)data); } fileOutputStream.Close(); cryptoStream.Close(); inptuFs.Close(); } } } } } } }
public void Decrypt(string filename, string outfile, KeyIvModel keyiv) { var decryptor = GetDecryptorAes(keyiv); using (FileStream fsCrypt = new FileStream(filename, FileMode.Open)) { using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read)) { using (FileStream fsOut = new FileStream(outfile, FileMode.Create)) { int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } } } } }
public void DecryptFcrt(ref byte[] data, byte[] cpukey) { if (data.Length < 0x120) { throw new X360UtilsException(X360UtilsException.X360UtilsErrors.DataTooSmall); } var offset = BitOperations.Swap(BitConverter.ToUInt32(data, 0x11C)); var length = BitOperations.Swap(BitConverter.ToUInt32(data, 0x118)); var iv = new byte[0x10]; Buffer.BlockCopy(data, 0x100, iv, 0, iv.Length); if (data.Length < offset + length) { throw new X360UtilsException(X360UtilsException.X360UtilsErrors.DataInvalid); } var buf = new byte[length]; var ret = new List <byte>(); Buffer.BlockCopy(data, (int)offset, buf, 0, buf.Length); using (var aes = new RijndaelManaged()) { aes.Mode = CipherMode.CBC; aes.KeySize = 128; aes.Key = cpukey; aes.IV = iv; aes.Padding = PaddingMode.None; using (var ms = new MemoryStream(buf)) { using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read)) { var b = 0; while (b != -1) { b = cs.ReadByte(); if (b != -1) { ret.Add((byte)b); } } } } //return new BinaryReader(cs).ReadBytes((int)length); } buf = ret.ToArray(); Buffer.BlockCopy(buf, 0, data, (int)offset, buf.Length); }
public static void DecryptFile(string inputFile, string outputFile) { int num; string s = "myKey123"; byte[] bytes = new UnicodeEncoding().GetBytes(s); FileStream stream = new FileStream(inputFile, FileMode.Open); RijndaelManaged managed = new RijndaelManaged(); CryptoStream stream2 = new CryptoStream(stream, managed.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read); FileStream stream3 = new FileStream(outputFile, FileMode.Create); while ((num = stream2.ReadByte()) != -1) { stream3.WriteByte((byte)num); } stream3.Close(); stream2.Close(); stream.Close(); }
/// <summary> /// This method is used to decrypte file encrypted using Rijndael algorithm. /// </summary> /// <param name="inputFile">encrypted file path</param> /// <param name="outputFile">decrypted file saving path</param> /// <param name="RijndaelManagedKey">RijndaelManagedKey.</param> public static void DecryptFile(string inputFile, string outputFile, string RijndaelManagedKey) { if (inputFile == null) { throw new ArgumentException("inputFile"); } if (outputFile == null) { throw new ArgumentException("outputFile"); } if (RijndaelManagedKey == null) { throw new ArgumentException("RijndaelManagedKey"); } PasswordDeriveBytes passwordDeriveBytes = new PasswordDeriveBytes(RijndaelManagedKey, new byte[13] { (byte)73, (byte)118, (byte)97, (byte)110, (byte)32, (byte)77, (byte)101, (byte)100, (byte)118, (byte)101, (byte)100, (byte)101, (byte)118 }); CryptoStream cryptoStream = new CryptoStream((Stream) new FileStream(inputFile, FileMode.Open), new RijndaelManaged().CreateDecryptor(passwordDeriveBytes.GetBytes(32), passwordDeriveBytes.GetBytes(16)), CryptoStreamMode.Read); FileStream fileStream = new FileStream(outputFile, FileMode.Create); int num; while ((num = cryptoStream.ReadByte()) != -1) { fileStream.WriteByte((byte)num); } fileStream.Close(); cryptoStream.Close(); }
public static void DecryptFile(string inputFile, string outputFile, string password) { //le-am scos din try ca sa pot sa le inchid in catch FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); FileStream fsOut = new FileStream(outputFile, FileMode.Create); try { UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } fsOut.Close(); cs.Close(); fsCrypt.Close(); } catch (Exception ex) { //in caz ca cheia e gresita inchide filestream-ul ca sa mai poata fi accesat fisierul fsOut.Close(); fsCrypt.Close(); //daca dadea eroare tot ramanea fisierul if (File.Exists(outputFile)) { File.Delete(outputFile); } throw ex; } }
public static void Decryption(string inputFile, string outputFile, string key_) { string password = key_; try { UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); var bt = new List <byte>(); using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open)) { using (RijndaelManaged RMCrypto = new RijndaelManaged()) { using (CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read)) { int data; while ((data = cs.ReadByte()) != -1) { bt.Add((byte)data); } } } using (FileStream fsOut = new FileStream(outputFile, FileMode.Create)) { foreach (var b in bt) { fsOut.WriteByte(b); } } } } catch (Exception e) { using (var streamWriter = new StreamWriter( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "errorMessage.txt"), true, Encoding.Default)) { streamWriter.WriteLine("File decryption error: " + e.Message); } } }
public void DecryptFile(string skey) { Boolean fileOpened = false; string input = @"C:\Users\Dominik\Desktop\VU\3 semestras\Taikomasis objektinis programavimas\PlayList\PlayList\"; System.Console.WriteLine("Enter the name of txt file where encrypted play list is"); while (!fileOpened) { name = System.Console.ReadLine(); input = defaultPath + name + ".txt"; byte[] buffer = new byte[60]; try { using (RijndaelManaged aes = new RijndaelManaged()) { byte[] key = ASCIIEncoding.UTF8.GetBytes(skey); byte[] IV = ASCIIEncoding.UTF8.GetBytes(skey); using (FileStream fsCrypt = new FileStream(input, FileMode.Open)) { using (ICryptoTransform decryptor = aes.CreateDecryptor(key, IV)) { using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read)) { int data; while ((data = cs.ReadByte()) != -1) { System.Console.Write((char)data); } } } } } fileOpened = true; } catch (Exception ex) { System.Console.WriteLine("File could be found, please try again"); } } }
public SecureString Decrypt(byte[] data) { SecureString s = new SecureString(); try { using (MemoryStream ms = new MemoryStream(data, 0, data.Length)) using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) { int l; while ((l = cs.ReadByte()) != -1) { s.AppendChar((char)l); } } } catch { } return(s); }
public static byte[] Decrypt(Stream input) { byte[] decrypted = new byte[input.Length - 16]; using (var cs = new CryptoStream(input, aes.CreateDecryptor(), CryptoStreamMode.Read)) { // skip 16 bytes (some unknown checksum or something idk) int leftSkip = 16; while (leftSkip-- > 0) { int b = cs.ReadByte(); } _ = cs.Read(decrypted, 0, (int)input.Length - 16); } return(decrypted); }
//Encrypt Over /// <summary> /// This is a method to decrypt a file with a given key. /// </summary> /// <param name="inputFile"></param> /// <param name="outputFile"></param> public static void DecryptFile(string inputFile, string outputFile) { try { string password = @"CPSC711"; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } cs.Flush(); fsCrypt.Flush(); fsOut.Flush(); fsOut.Close(); cs.Close(); fsCrypt.Close(); fsOut.Dispose(); fsCrypt.Dispose(); cs.Dispose(); } catch (Exception ex) { Console.WriteLine(ex.InnerException.ToString()); } finally { } }
/// <summary> /// Method decryptFile decrypts input file and the result saves to output file. /// </summary> /// <param name="inputFile">path to input file</param> /// <param name="outputFile">path to output file</param> /// <exception cref="ArgumentException">parameter inputFile is null or empty string</exception> /// <exception cref="ArgumentException">parameter outputFile is null or empty string</exception> /// <exception cref="Exception">decryption failed</exception> public void decryptFile(string inputFile, string outputFile) { if (inputFile.Equals("") || inputFile == null) { throw new ArgumentException("Parameter inputFile is null or empty string."); } if (outputFile.Equals("") || outputFile == null) { throw new ArgumentException("Parameter outputFile is null or empty string."); } FileStream fsOut = null; // output file stream try { fsOut = new FileStream(outputFile, FileMode.Create); // create output file string fileHash = Convert.ToBase64String(getFileHash(inputFile)); // compute file hash of input file string[] record = service.getRecord(fileHash); // get record, which is provided by on card service rijndael.Key = Convert.FromBase64String(record[0]); // get the key from record rijndael.IV = Convert.FromBase64String(record[1]); // get the IV from record ICryptoTransform aesDecrypt = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV); // create decryptor FileStream fsIn = new FileStream(inputFile, FileMode.Open); // get access to input file CryptoStream cs = new CryptoStream(fsIn, aesDecrypt, CryptoStreamMode.Read); // create CryptoStream int data; while ((data = cs.ReadByte()) != -1) // go throught the encrypted file and do the decryption { fsOut.WriteByte((byte)data); } cs.Close(); fsIn.Close(); fsOut.Close(); } catch (Exception ex) { fsOut.Close(); // file ouput stream has to be closed, otherwise we cannot delete outputFile File.Delete(outputFile); // outputFile is going to be deleted, when some exception is detected throw new Exception(ex.Message); } }
public static void AES_Decrypt(string inputFile, string outputFile, byte[] complexKeyBytes) { byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged AES = new RijndaelManaged(); AES.KeySize = KEY_SIZE; AES.BlockSize = BLOCK_SIZE; byte[] _key = new byte[KEY_SIZE / 8]; byte[] _iv = new byte[BLOCK_SIZE / 8]; Array.Copy(complexKeyBytes, 0, _key, 0, KEY_SIZE / 8); Array.Copy(complexKeyBytes, KEY_SIZE / 8, _iv, 0, BLOCK_SIZE / 8); AES.Key = _key; AES.IV = _iv; AES.Padding = PaddingMode.Zeros; AES.Mode = CipherMode.CBC; CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } fsOut.Flush(); fsOut.Close(); cs.Flush(); cs.Close(); //fsCrypt.Flush(); fsCrypt.Close(); }
///<summary> /// Steve Lydford - 12/05/2008. /// /// Decrypts a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> private static void DecryptFile(string password, string inputFile, string outputFile) { { UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data; try { while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } } catch (Exception) { Console.WriteLine("Invalid Pasword"); } try { fsOut.Close(); cs.Close(); fsCrypt.Close(); } catch { MessageBox.Show("Invalid Password for this file"); Application.Restart(); } } }
//Method to decrypt files with a symetric aes public void symetrDecrypt(string fileInputPath, string fileOutputPath) { try { using (RijndaelManaged aes = new RijndaelManaged()) { aes.KeySize = 256; aes.BlockSize = 256; //Read aes keys string key = keys.find(hash.buildmd5(fileInputPath)); byte[] decryptetKey = crypto.Decrypt(key); //Read exist crypted file using (FileStream fsCrypt = new FileStream(fileInputPath, FileMode.Open)) { //New filestream to save the decrypted file as a new file using (FileStream fsOut = new FileStream(fileOutputPath, FileMode.Create)) { using (ICryptoTransform decryptor = aes.CreateDecryptor(decryptetKey, decryptetKey)) { //read encrypted file and save it in a new file withe the same name using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read)) { int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } } } } } } log.Info("file decryption successful"); } catch (Exception) { log.Fatal("file decryption failed"); } }
//---------------------------------------------------------------------------------- private static byte[] Decrypt ( byte[] src , string pwd , ref long length , string salt , string hash , string siv , CipherMode mode , int keysize , int inum ) { RijndaelManaged rm = new RijndaelManaged(); byte[] kg = Program.KeyGen(pwd, salt, hash, keysize, inum); byte[] iv = Encoding.ASCII.GetBytes(siv); byte[] bf = new byte[length]; length = 0; rm.Mode = mode; using (ICryptoTransform ct = rm.CreateDecryptor(kg, iv)) { using (MemoryStream ms = new MemoryStream(src)) { using (CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Read)) { for (int bt; (bt = cs.ReadByte()) != -1; ++length) { bf[length] = (byte)bt; } ms.Close(); cs.Close(); } } } rm.Clear(); return(bf); }
//Method to decrypt files with a symetric aes public void symetrDecrypt(string fileInputPath, string fileOutputPath) { try { using (RijndaelManaged aes = new RijndaelManaged()) { //Read aes keys //ToDo implement a Hashmap or Dictionary in C# byte[] Key = Convert.FromBase64String(getKey(@"C:\crypto\aeskeys\Key.txt")); byte[] IV = Convert.FromBase64String(getKey(@"C:\crypto\aeskeys\IV.txt")); //Read exist crypted file using (FileStream fsCrypt = new FileStream(fileInputPath, FileMode.Open)) { //New filestream to save the decrypted file as a new file using (FileStream fsOut = new FileStream(fileOutputPath, FileMode.Create)) { using (ICryptoTransform decryptor = aes.CreateDecryptor(Key, IV)) { //read encrypted file and save it in a new file withe the same name using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read)) { int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } } } } } } //ToDo Logging } catch (Exception ex) { //ToDo logging // failed to decrypt file } }
private static string ByteToString(CryptoStream csDecrypt) { string binary = ""; int b = 0; //while (b != -1) //{ // b = csDecrypt.ReadByte(); // binary += (char)b; //} do { b = csDecrypt.ReadByte(); if (b != -1) { binary += ((char)b); } } while (b != -1); return(binary); }
private static void ExtractEncryptedFile(EArchiveFile file, BinaryReader reader, string path) { Aes aes = Aes.Create(); aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.Zeros; ICryptoTransform transform = aes.CreateDecryptor(AESKey, file.IV); using (CryptoStream stream = new CryptoStream(reader.BaseStream, transform, CryptoStreamMode.Read)) { using (Stream write = File.Create(path + file.Path)) { using (BinaryWriter writer = new BinaryWriter(write)) { for (int index = 0; index < file.SizeUncompressed; index++) { writer.Write((byte)stream.ReadByte()); } } } } }
//Method that decrypts files private static void Decryption(string inputFile, string outputFile) { FileStream fs = new FileStream(inputFile, FileMode.Open); RijndaelManaged RM = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fs, RM.CreateDecryptor(key, key), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data = 0; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } fsOut.Close(); cs.Close(); fs.Close(); }
protected byte[] Desencriptar(byte[] data) { MemoryStream ms = new MemoryStream(data); // Get a tripleDES provider and create the CryptoStream CryptoStream encStream = new CryptoStream(ms, _cs.CreateDecryptor(_cs.Key, _cs.IV), CryptoStreamMode.Read); // Decrypts the whole data... MemoryStream retval = new MemoryStream(); BinaryWriter bw = new BinaryWriter(retval); int b; while ((b = encStream.ReadByte()) != -1) { bw.Write((byte)b); } byte[] baRetval = retval.GetBuffer(); bw.Close(); ms.Close(); return(baRetval); }
public static void DecryptFile(string inputFile, string outputFile) { string password = @"myKey123"; UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } fsOut.Close(); cs.Close(); fsCrypt.Close(); }
public static bool DecryptFile(string inputFile, string outputFile, string encrKey) { try { UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(encrKey); FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); TripleDESCryptoServiceProvider tDes = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(encrKey)); CryptoStream cs = new CryptoStream(fsCrypt, tDes.CreateDecryptor(key, new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 }), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } fsOut.Close(); cs.Close(); fsCrypt.Close(); return(true); } catch (Exception) { return(false); } }
public static void DecryptFile(string inputFile, string outputFile, string password, string salt) { // length of salt must be at least 8 bytes var saltyBytes = Encoding.ASCII.GetBytes(salt); if (saltyBytes.Length < 8) { var saltyList = saltyBytes.ToList(); for (var i = 0; i < 8 - saltyBytes.Length; i++) { saltyList.Add(0x0); } saltyBytes = saltyList.ToArray(); } var key = new Rfc2898DeriveBytes(password, saltyBytes); var inStream = new FileStream(inputFile, FileMode.Open); var encryption = new RijndaelManaged(); encryption.Key = key.GetBytes(encryption.KeySize / 8); encryption.IV = key.GetBytes(encryption.BlockSize / 8); encryption.Padding = PaddingMode.PKCS7; var encryptionStream = new CryptoStream(inStream, encryption.CreateDecryptor(), CryptoStreamMode.Read); var outStream = new FileStream(outputFile, FileMode.Create); int data; while ((data = encryptionStream.ReadByte()) != -1) { outStream.WriteByte((byte)data); } outStream.Close(); encryptionStream.Close(); inStream.Close(); }
///<summary> /// Decrypt a file to a string using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="encryptionPassword"></param> public static string GetDecryptedText(string inputFile, string encryptionPassword) { string result = null; try { //string encryptionPassword = @"myKey123"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(encryptionPassword); FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged RMCrypto = new RijndaelManaged(); CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); MemoryStream msOut = new MemoryStream(); int data; while ((data = cs.ReadByte()) != -1) { msOut.WriteByte((byte)data); } result = System.Text.Encoding.Default.GetString(msOut.ToArray()); msOut.Close(); cs.Close(); fsCrypt.Close(); return(result); } catch (Exception ex) { Console.WriteLine("Decryption failed: {0}", ex.Message); return(null); } }
private async Task DecryptFile(string file) { await Task.Run(async() => { string password = textBox2.Text; UnicodeEncoding UE = new UnicodeEncoding(); while (UE.GetBytes(password).Length < 16) { password += " "; } while (UE.GetBytes(password).Length > 16) { password = password.Substring(0, 8); } byte[] key = UE.GetBytes(password); byte[] data; using (FileStream fsCrypt = new FileStream(file, FileMode.Open)) { using (CryptoStream cs = new CryptoStream(fsCrypt, new RijndaelManaged().CreateDecryptor(key, key), CryptoStreamMode.Read)) { data = new byte[fsCrypt.Length]; double j = 0; for (int i = 0; i < data.Length; i++) { data[i] = (byte)cs.ReadByte(); j += 100.0 / data.Length; if (j >= 1) { UpdateProgressBar((int)j); j = 0; } } } } using (FileStream fsOut = new FileStream(file, FileMode.Open)) { await fsOut.WriteAsync(data, 0, data.Length); } UpdateProgressBar(100 - progressBar1.Value); }); }
private static void AES_Decrypt(string inputFile, string outputFile, string passwordBytes) { try { byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged AES = new RijndaelManaged(); AES.KeySize = 256; AES.BlockSize = 128; var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000); AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Padding = PaddingMode.Zeros; AES.Mode = CipherMode.CBC; CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } fsOut.Close(); cs.Close(); fsCrypt.Close(); } catch { MessageBox.Show("There was an error unpacking the file: Error Code (1)"); } }
public void CanProduceHashWhileReadingFromStream() { SHA256 hashFunction = SHA256.Create(); MemoryStream dataToHash = StreamContaining("Some data"); using (CryptoStream cryptoStream = new CryptoStream(dataToHash, hashFunction, CryptoStreamMode.Read)) { while (cryptoStream.ReadByte() != -1) { //imagine doing something useful with the data being read //notice that the data being read will not be hashed } byte[] hashBuiltWhenReadingFromStream = hashFunction.Hash; dataToHash.Position = 0; byte[] computedHash = SHA256.Create().ComputeHash(dataToHash); Assert.That(hashBuiltWhenReadingFromStream, Is.EqualTo(computedHash)); } }
public static string DecryptFile(string filePath) { Debug.Log("Decrypting"); var output = String.Empty; try { using (RijndaelManaged aes = new RijndaelManaged()) { byte[] key = ASCIIEncoding.UTF8.GetBytes(skey); byte[] IV = ASCIIEncoding.UTF8.GetBytes(vkey); using (FileStream fsCrypt = new FileStream(filePath + "eSave.dat", FileMode.Open)) { using (FileStream fsOut = new FileStream(filePath + "uSave.dat", FileMode.Create)) { using (ICryptoTransform decryptor = aes.CreateDecryptor(key, IV)) { using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read)) { int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } output = fsOut.ToString(); } } } } } //File.Delete(filePath + "uSave.dat"); } catch{} // failed to decrypt file return output; }
public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks) { ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks); var stream = new MemoryStream(); using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write)) { Assert.True(encryptStream.CanWrite); Assert.False(encryptStream.CanRead); Assert.False(encryptStream.CanSeek); Assert.False(encryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => encryptStream.Length); Assert.Throws<NotSupportedException>(() => encryptStream.Position); Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1)); Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4)); byte[] toWrite = Encoding.UTF8.GetBytes(LoremText); // Write it all at once encryptStream.Write(toWrite, 0, toWrite.Length); Assert.False(encryptStream.HasFlushedFinalBlock); // Write in chunks encryptStream.Write(toWrite, 0, toWrite.Length / 2); encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2)); Assert.False(encryptStream.HasFlushedFinalBlock); // Write one byte at a time for (int i = 0; i < toWrite.Length; i++) { encryptStream.WriteByte(toWrite[i]); } Assert.False(encryptStream.HasFlushedFinalBlock); // Write async encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult(); Assert.False(encryptStream.HasFlushedFinalBlock); // Flush (nops) encryptStream.Flush(); encryptStream.FlushAsync().GetAwaiter().GetResult(); encryptStream.FlushFinalBlock(); Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock()); Assert.True(encryptStream.HasFlushedFinalBlock); Assert.True(stream.Length > 0); } // Read/decrypt using Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { Assert.False(decryptStream.CanWrite); Assert.True(decryptStream.CanRead); Assert.False(decryptStream.CanSeek); Assert.False(decryptStream.HasFlushedFinalBlock); Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => decryptStream.Length); Assert.Throws<NotSupportedException>(() => decryptStream.Position); Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0); Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0)); Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer? Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1)); Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4)); using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEnd()); } } // Read/decrypt using ReadToEnd stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt using a small buffer to force multiple calls to Read stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10)) { Assert.Equal( LoremText + LoremText + LoremText + LoremText, reader.ReadToEndAsync().GetAwaiter().GetResult()); } // Read/decrypt one byte at a time with ReadByte stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read)) { string expectedStr = LoremText + LoremText + LoremText + LoremText; foreach (char c in expectedStr) { Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII } Assert.Equal(-1, decryptStream.ReadByte()); } }