Please enable / Bitte aktiviere JavaScript!
Veuillez activer / Por favor activa el Javascript![ ? ]
C# How to encrypt a file? - bug-code.com Q&A

C# How to encrypt a file?

0 like 0 dislike
21 views
Hello!
There is a file you want to encrypt by the method of permutation key. Make a pair of key-value (Dictionary), where the key is a letter key, value - List of bytes. The problem is that for the integrity of the picture need to the number of bytes is a multiple of the number of characters in the key. Can't figure out how to add zeros to the beginning of the file.

An example of my code for encryption of text:
code
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace coding_encoding { class Crypto { private string key; private char[] temp; public Crypto(string key) { this.key = key; temp = this.key.ToCharArray(); Array.Sort(temp); } /// /// Method to decrypt a string the key. /// /// String that needs decoding./// Key to be used decrypt./// The decoded string.public string Decrypt(string message) { sortedKey string = string.Empty; string result = string.Empty; Dictionary dictionaryIntChar = new Dictionary(); Dictionary> keyValuePairs; Dictionary> resultDictionary = new Dictionary>(); for (int i = 0; i < key.Length; i++) dictionaryIntChar[i] = key[i]; foreach (char ch in temp) sortedKey += ch; //here is adding a symbol for multiplicity while (message.Length % key.Length != 0) message += " "; keyValuePairs = GetDictionary(message, sortedKey); for (int i = 0; i < key.Length; i++) { for (int j = i; j < message.Length; j += key.Length) { resultDictionary[dictionaryIntChar[i]] = keyValuePairs[dictionaryIntChar[i]]; } } //the layout of the received message return Composition(key.ToCharArray(), resultDictionary); } /// /// Method to encrypt a string by key. /// /// The string to encrypt./// The key which will be encrypted./// Encrypted string.public string Encrypt(string message) { Dictionary> keyValuePairs; string result = string.Empty; //add in a line of blank characters to preserve the integrity of columns while (message.Length % key.Length != 0) message += " "; keyValuePairs = GetDictionary(message, key); //the layout of the received message return Composition(temp, keyValuePairs); } /// /// The layout of the received message. /// /// An array of the letters of the key./// Dictionary key-value/// The composed message.private string Composition(char[] editKey, Dictionary> keyValuePairs) { string result = string.Empty; for (int i = 0; i < keyValuePairs[editKey[0]].Count; i++) for (int j = 0; j < editKey.Length; j++) result += keyValuePairs[editKey[j]][i].ToString(); return result; } /// /// Get a dictionary of key-value. /// /// The message you want to bind to the letters of the key/// The letters of the key to which will be attached to the message/// Dictionaryprivate Dictionary> GetDictionary(string message, string key) { Dictionary> result = new Dictionary>(); for (int i = 0; i < key.Length; i++) { List listChar = new List(); //add the column character key for (int j = i; j < message.Length; j += key.Length) { listChar.Add(message[j]); } //binding the key-value result.Add(key[i], listChar); } return result; } } }

asked by | 21 views

1 Answer

0 like 0 dislike
Honestly, I don't quite understand what the problem is. If the file is not too large, you can read it into memory using File.ReadAllText, then encode the content and write into another file. If the file is large, you can use the FileStream logic changes a little, but nothing too complicated.

I slightly optimized Your code for strings:
class Crypto2 { private readonly int[] _key; private readonly int[] _inversedKey; public Crypto2(string key) { var indexPairs = key .Select((chr, idx1) => new { chr, idx1 }) // assign each symbol index .OrderBy(arg => arg.chr) // sort by symbol .Select((arg, idx2) => new { arg.idx1, idx2 }) // now build an array of pairs of "the original index" <=> "sorted index". .ToArray(); // Generate a straight key: the "less than" symbol (in alphabetical order), the smaller its index in the destination array. // "a" => 0, ... , "b" => 5 // Get: "Caesar" => [4, 1, 2, 0, 3, 5] _key = indexPairs .OrderBy(arg => arg.idx1) .Select(arg => arg.idx2) .ToArray(); // The reverse operation to decode _inversedKey = indexPairs .OrderBy(arg => arg.idx2) .Select(arg => arg.idx1) .ToArray(); } public string Encrypt(string message) { return EncryptDecrypt(message, _key); } public string Decrypt(string message) { return EncryptDecrypt(message, _inversedKey); } private static string EncryptDecrypt(string message, int[] key) { var keyLength = key.Length; var messageLength = message.Length; if (messageLength % keyLength > 0) { // Complement of the string with spaces if necessary message = message.The padright(messageLength + keyLength - messageLength % keyLength, ' '); } // Never use string concatenation in a loop (like result += keyValuePairs[editKey[j]][i].ToString();). It is very slow. // For these purposes there is a special class StringBuilder. // We know the length of the destination string, so initialize StringBuilder correctly. var sb = new StringBuilder(messageLength) {Length = message.Length}; for (var i = 0; i < message.Length; i++) { // Calculate the end index to insert the symbol. // The first part of the expression "i / keyLength * keyLength" - i rounding down to the nearest value divisible by keyLength // Second part of "key[i % keyLength]" - calculate the new character position based on the key. var idx = i / keyLength * keyLength + key[i % keyLength]; sb[idx] = message[i]; } return sb.ToString(); } }


And here is the same code for the files:

class Crypto3 { private readonly int[] _key; private readonly int[] _inversedKey; public Crypto3(string key) { var indexPairs = key .Select((chr, idx1) => new {chr, idx1}) .OrderBy(arg => arg.chr) .Select((arg, idx2) => new { arg.idx1, idx2 }) .ToArray(); _key = indexPairs .OrderBy(arg => arg.idx1) .Select(arg => arg.idx2) .ToArray(); _inversedKey = indexPairs .OrderBy(arg => arg.idx2) .Select(arg => arg.idx1) .ToArray(); } public void Encrypt(string sourceFile, string destinationFile) { EncryptDecrypt(sourceFile, destinationFile, _key); } public void Decrypt(string sourceFile, string destinationFile) { EncryptDecrypt(sourceFile, destinationFile, _inversedKey); } private static void EncryptDecrypt(string sourceFile, string destinationFile, int[] key) { var keyLength = key.Length; var buffer1 = new byte[keyLength]; var buffer2 = new byte[keyLength]; using (var source = new FileStream(sourceFile, FileMode.Open)) using (var destination = new FileStream(destinationFile, FileMode.OpenOrCreate)) { while (true) { var read = source.Read(buffer1, 0, keyLength); if (read == 0) { return; } else if (read < keyLength) { for (int i = read; i < keyLength; i++) { buffer1[i] = (byte) ' '; } } for (var i = 0; i < keyLength; i++) { var idx = i / keyLength * keyLength + key[i % keyLength]; buffer2[idx] = buffer1[i]; } destination.Write(buffer2, 0, keyLength); } } } }
answered by
Welcome to Bug-code Q&A, where you can ask questions and receive answers from other members of the community.

24.8k questions

46.2k answers

0 comments

12.7k users

24,788 questions
46,220 answers
0 comments
12,722 users