|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Text; |
| 3 | + |
| 4 | +namespace CryptoSoft; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// File manager class |
| 8 | +/// This class is used to encrypt and decrypt files |
| 9 | +/// </summary> |
| 10 | +public class FileManager(string path, string key) |
| 11 | +{ |
| 12 | + private string FilePath { get; } = path; |
| 13 | + private string Key { get; } = key; |
| 14 | + |
| 15 | + /// <summary> |
| 16 | + /// check if the file exists |
| 17 | + /// </summary> |
| 18 | + private bool CheckFile() |
| 19 | + { |
| 20 | + if (File.Exists(FilePath)) |
| 21 | + return true; |
| 22 | + |
| 23 | + Console.WriteLine("File not found."); |
| 24 | + Thread.Sleep(1000); |
| 25 | + return false; |
| 26 | + } |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Encrypts the file with xor encryption |
| 30 | + /// </summary> |
| 31 | + public int TransformFile() |
| 32 | + { |
| 33 | + if (!CheckFile()) return -1; |
| 34 | + Stopwatch stopwatch = Stopwatch.StartNew(); |
| 35 | + var fileBytes = File.ReadAllBytes(FilePath); |
| 36 | + var keyBytes = ConvertToByte(Key); |
| 37 | + fileBytes = XorMethod(fileBytes, keyBytes); |
| 38 | + File.WriteAllBytes(FilePath, fileBytes); |
| 39 | + stopwatch.Stop(); |
| 40 | + return (int)stopwatch.ElapsedMilliseconds; |
| 41 | + } |
| 42 | + |
| 43 | + /// <summary> |
| 44 | + /// Convert a string in byte array |
| 45 | + /// </summary> |
| 46 | + /// <param name="text"></param> |
| 47 | + /// <returns></returns> |
| 48 | + private static byte[] ConvertToByte(string text) |
| 49 | + { |
| 50 | + return Encoding.UTF8.GetBytes(text); |
| 51 | + } |
| 52 | + |
| 53 | + /// <summary> |
| 54 | + /// </summary> |
| 55 | + /// <param name="fileBytes">Bytes of the file to convert</param> |
| 56 | + /// <param name="keyBytes">Key to use</param> |
| 57 | + /// <returns>Bytes of the encrypted file</returns> |
| 58 | + private static byte[] XorMethod(IReadOnlyList<byte> fileBytes, IReadOnlyList<byte> keyBytes) |
| 59 | + { |
| 60 | + var result = new byte[fileBytes.Count]; |
| 61 | + for (var i = 0; i < fileBytes.Count; i++) |
| 62 | + { |
| 63 | + result[i] = (byte)(fileBytes[i] ^ keyBytes[i % keyBytes.Count]); |
| 64 | + } |
| 65 | + |
| 66 | + return result; |
| 67 | + } |
| 68 | +} |
0 commit comments