📜 ⬆️ ⬇️

Implementing ECB Encryption with the Marshall C # Library

Hello! Increasingly, I meet the questions of friends and colleagues, and just requests on the topic “how to implement C # encryption”. So who will be interested to tell how this can be implemented.
ECB mode is a block cipher application method that allows you to convert a sequence of open data blocks into a sequence of encrypted data blocks. More precisely you can find out on wikipedia. I will go to the essence of the question.

For example, we have a file that needs to be encrypted. The first thing that comes to mind: there must be a function that takes a file or a path to it as an argument. Call this function _CRYPTO:

static void CRYPTO(string f) { string H = File.ReadAllText(f); FileStream FILE = File.Open(f, FileMode.Open); byte[] Key = Encoding.Default.GetBytes("key12345678"); Array.Resize(ref Key, 16); RijndaelManaged RMCrypto = new RijndaelManaged(); RMCrypto.Mode = CipherMode.ECB; RMCrypto.Padding = PaddingMode.Zeros; RMCrypto.KeySize = 128; RMCrypto.Key = Key; ICryptoTransform Encryptor = RMCrypto.CreateEncryptor(); CryptoStream Crypt = new CryptoStream(FILE, Encryptor, CryptoStreamMode.Write); using (StreamWriter sw = new StreamWriter(Crypt, Encoding.Unicode)) { sw.Write(H); sw.Flush(); } Console.WriteLine(H); FILE.Close(); } 


In fact, everything is simple! The Key variable can take any values ​​you wish. For example, I made a generator that produced a random combination and wrote it to a file. RMCrypto.Mode = CipherMode.ECB implements the type of encryption. The most interesting thing about this code is the write parameter of the Encoding.Unicode type. Here we change the encoding for encryption.
')
Well, the function that implements the decryption of the DERCYPTO file:

 static void DECRYPTO(string f) { FileStream FILE = File.Open(f, FileMode.Open); string S = FILE.ToString(); string plaintext = null; byte[] Key = Encoding.Default.GetBytes("key12345678"); Array.Resize(ref Key, 16); RijndaelManaged RMCrypto = new RijndaelManaged(); RMCrypto.Mode = CipherMode.ECB; RMCrypto.Padding = PaddingMode.Zeros; RMCrypto.KeySize = 128; RMCrypto.Key = Key; ICryptoTransform Decryptor = RMCrypto.CreateDecryptor(); CryptoStream Crypt = new CryptoStream(FILE, Decryptor, CryptoStreamMode.Read); using (StreamReader sw = new StreamReader(Crypt, Encoding.Unicode)) { plaintext = sw.ReadToEnd(); } File.WriteAllText(f, plaintext.ToString()); Console.WriteLine(plaintext); FILE.Close(); } 


Do not forget to close the files after the execution of operations, otherwise errors will occur as the threads will not be closed.

Source: https://habr.com/ru/post/180863/


All Articles