public string Upload(string path, string filename, string key, int alg) { try { byte[] f = File.ReadAllBytes(path); StoredFile sf = new StoredFile(); sf.username = Username; sf.filename = filename; sf.hash = MD5.HashString(f); switch (alg) { case 0: sf.data = DoubleTransposition.Encrypt(f, key, sf.hash); sf.size = sf.data.Length; break; case 1: sf.data = XTEA.Encrypt(f, key, sf.hash); sf.size = sf.data.Length; break; default: throw new Exception("You have not chosen an algorithm."); } svc.Upload(Username, sf, Token); Refresh(); return("File successfuly uploaded."); } catch (Exception e) { return(e.Message); } }
private static void Initialize() { // Initializing XTEA encryption object if (CloudCypherXTEA == null) { CloudCypherXTEA = new XTEA(); } // Creating cloud storage directory if (!Directory.Exists(StoragePath)) { var dir = Directory.CreateDirectory(StoragePath); dir.Attributes = FileAttributes.Directory | FileAttributes.Hidden; } // Initializing cloud key if (CryptedCloudKey != null) { return; } var CypherMD5 = new MD5(); CryptedCloudKey = CypherMD5.Crypt(Encoding.ASCII.GetBytes(CloudKey)); CloudCypherXTEA.SetKey(CryptedCloudKey); }
private IPacketIn ReadPacket(IPacketIn packet) { try { byte[] buffer = ReadBuffer(packet.Length - _bufferSize); if (_needToDecrypt) { if (_idBuffer == null) { //throw new Exception("InitialBuffer not provided for packet id " + packet.Id); _idBuffer = ReadBuffer(8); } buffer = XTEA.Decrypt(buffer, Config.Pong); byte[] newBuffer = new byte[_idBuffer.Length + buffer.Length]; _idBuffer.CopyTo(newBuffer, 0); buffer.CopyTo(newBuffer, _idBuffer.Length); buffer = newBuffer; } packet.ParseBuffer(buffer); //Length - buffer because of alread read data _log.Packet("Read PacketID: " + packet.Id.ToString("X2")); return(packet); } catch (Exception e) { _log.Error("Error with client: " + _ip + " Exception: " + e); Drop("IOException: " + e.Message); } return(null); }
/// <summary> /// Reads the PAK file metadata, including file list information and the file list /// </summary> /// <exception cref="NotSupportedException">Is thrown if the given PAK file does not have a valid signature</exception> private void ReadMetadata() { using (BinaryReader reader = new BinaryReader(new MemoryStream(File.ReadAllBytes(FilePath)))) { reader.BaseStream.Seek(-9L, SeekOrigin.End); uint fileListOffset = reader.ReadUInt32(); uint fileCount = reader.ReadUInt32(); if ((reader.ReadByte()) != 0x12) { throw new NotSupportedException("The signature of this PAK file is invalid!"); } reader.BaseStream.Seek(fileListOffset, SeekOrigin.Begin); for (uint i = 0; i < fileCount; i++) { FileEntry fileEntry = new FileEntry(); fileEntry.FileNameLength = reader.ReadByte(); fileEntry.Compression = reader.ReadByte(); fileEntry.Offset = reader.ReadUInt32(); fileEntry.FileSize = reader.ReadUInt32(); fileEntry.RealFileSize = reader.ReadUInt32(); byte[] tempName = reader.ReadBytes(fileEntry.FileNameLength); if (fileEntry.Compression < 4) { uint decryptionKey = (uint)Key; reader.BaseStream.Seek(1L, SeekOrigin.Current); fileEntry.FileName = Encoding.UTF8.GetString(XOR.Cipher(tempName, decryptionKey)); } else { uint[] decryptionKey = (uint[])Key; fileEntry.Compression ^= 0x20; fileEntry.FileName = DecryptFileName(tempName, decryptionKey); uint[] decryptionData = { fileEntry.Offset, fileEntry.RealFileSize }; uint[] resultData = XTEA.Decipher(16, decryptionData, decryptionKey); fileEntry.Offset = resultData[0]; fileEntry.RealFileSize = resultData[1]; } Entries.Add(fileEntry); } } }
public void XTEAEcnryption(FileInfo file, FormModel model) { bool threadSuccesfull = false; var timeStarted = DateTime.Now; try { //OutputFileName string outputFileName = FileNameCreator.CreateFileEncryptedName( model.Folders.OutputFolder, file.Name, model.AlgorithmName); //Log loggerController.Add(" ! File enc: " + file.Name + ", Alg: " + model.AlgorithmName); //Read a file char by char, and encrypt it using (FileStream fsw = new FileStream(outputFileName, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fsw, new ASCIIEncoding())) { //Writing the extension char[] extension = file.Extension.Substring(1, file.Extension.Length - 1).ToCharArray(); char extensionLength = (char)extension.Length; bw.Write(extensionLength); for (var k = 0; k < extension.Length; k++) { bw.Write(extension[k]); } //Reading and encrypting files var readedValue = File.ReadAllBytes(file.FullName); var encryptedValue = XTEA.Encrypt(readedValue); bw.Write(encryptedValue); if (LoadedFilesController._END_OF_ENC_DEC_THREADS) { bw.Dispose(); fsw.Dispose(); File.Delete(outputFileName); Thread.CurrentThread.Abort(); } } } threadSuccesfull = true; Thread.Sleep(250); } catch (Exception ex) { loggerController.Add(" ? Enc exception: " + ex.Message); threadSuccesfull = false; } finally { this.ThreadEnds(file, threadSuccesfull, timeStarted); } }
internal bool IsGameAuthPacket(byte[] data) { if (data.Length != 56) { return(false); } data = XTEA.Decrypt(data, _pong); return(data[0] == 0x6D); }
/// <summary> /// Sends a packet to the client /// </summary> /// <param name="packet"> The Packet </param> internal void SendPacket(IPacket packet) { try { _stream.Write(_needToDecrypt ? XTEA.Encrypt(packet.Data, Config.Pong) : packet.Data, 0, packet.Data.Length); } catch (IOException e) { _log.Error("Error with client: " + _ip + " Exception: " + e); Drop("IOException: " + e.Message); } }
/// <summary> /// Stores the user's credentials in PlayerPrefs. /// </summary> /// <param name="username">The username to store.</param> /// <param name="token">The token to store.</param> /// <returns>Whether the operations was successfull.</returns> public bool RememberUserCredentials(string username, string token) { if (string.IsNullOrEmpty(UserCredentialsPreferences) || string.IsNullOrEmpty(Settings.EncryptionKey) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(token)) { return(false); } var credentials = XTEA.Encrypt(username, Settings.EncryptionKey) + "#" + XTEA.Encrypt(token, Settings.EncryptionKey); PlayerPrefs.SetString(UserCredentialsPreferences, credentials); PlayerPrefs.Save(); return(true); }
/// <summary> /// Reads the file entries of the PAK file /// </summary> public void ReadFileEntries() { long Position = Reader.BaseStream.Position; Reader.BaseStream.Seek(FileListOffset, SeekOrigin.Begin); for (uint i = 0; i < FileCount; i++) { FileEntry fileEntry = new FileEntry(); fileEntry.FileNameLength = Reader.ReadByte(); fileEntry.Compression = Reader.ReadByte(); fileEntry.Offset = Reader.ReadUInt32(); fileEntry.FileSize = Reader.ReadUInt32(); fileEntry.RealFileSize = Reader.ReadUInt32(); byte[] tempName = Reader.ReadBytes(fileEntry.FileNameLength); if (fileEntry.Compression < 4 && fileEntry.Compression > -1) { uint decryptionKey = (uint)Key; fileEntry.Unknown1 = Reader.ReadByte(); fileEntry.FileName = Encoding.UTF8.GetString(XOR.Cipher(tempName, decryptionKey)); } else { uint[] decryptionKey = (uint[])Key; fileEntry.Compression ^= 0x20; fileEntry.FileName = DecryptFileName(tempName, decryptionKey); uint[] decryptionData = new uint[] { fileEntry.Offset, fileEntry.RealFileSize }; uint[] resultData = XTEA.Decipher(16, decryptionData, decryptionKey); fileEntry.Offset = resultData[0]; fileEntry.RealFileSize = resultData[1]; } Entries.Add(fileEntry); } Reader.BaseStream.Seek(Position, SeekOrigin.Begin); }
/// <summary> /// Decrypts the name of a file using XTEA /// </summary> /// <param name="fileNameBuffer">Bytes of the file name</param> /// <param name="key">Key to decrypt the filename with</param> /// <returns>The decrypted filename</returns> private static string DecryptFileName(byte[] fileNameBuffer, uint[] key) { Span <byte> nameSpan = fileNameBuffer; for (int j = 0; j < nameSpan.Length; j = j + 8) { Span <byte> chunk = nameSpan.Slice(j, 8); Span <uint> decrypted = XTEA.Decipher(16, MemoryMarshal.Cast <byte, uint>(chunk).ToArray(), key); Span <byte> resource = MemoryMarshal.AsBytes(decrypted); resource.CopyTo(chunk); } return(Encoding.UTF8.GetString(nameSpan.ToArray().TakeWhile(x => x != 0x00).ToArray())); }
/// <summary> /// Processes received packet /// </summary> /// <param name="id"> Packet id or Packet initial buffer </param> private void ProcessPacket(byte[] id) { if (_needToDecrypt) { id = XTEA.Decrypt(id, Config.Pong); } _idBuffer = id; switch (id[0]) { case (byte)InPackets.HandshakePacket: _log.Packet("Received HandshakePacket"); ContinueHandshake(); break; case (byte)InPackets.GameAuthorizationPacket: _log.Packet("Received GameAuthorizationPacket"); VerifyAuth(); break; case (byte)InPackets.CharacterCreatePacket: _log.Packet("Received CharacterCreatePacket"); CreateCharacter(); break; case (byte)InPackets.CharacterChoosePacket: // TODO Code for map enter _log.Packet("Received CharacterChoosePacket"); GameEnter(); break; case (byte)InPackets.LauncherNamePacket: _log.Packet("Received LauncherNamePacket.\nSooooo useful..."); break; case (byte)InPackets.UnknownPacket1: _log.Packet("Received UnknownPacket1."); break; default: _log.PacketConsole("Unknown Packet ID: " + id[0]); Drop("Unknown Packet ID " + id[0]); break; } }
/// <summary> /// Decrypts and parses the updatelist file /// /// Saves the parsed updatelist in the Document instance attribute /// </summary> public void Parse() { if (DecryptionKey == null) { throw new NullReferenceException("DecryptionKey needs to be set using the SetDecryptionKey instance method!"); } Span <byte> updateList = File.ReadAllBytes(FilePath); for (int i = 0; i < updateList.Length; i += 8) { Span <byte> chunk = updateList.Slice(i, 8); Span <uint> decrypted = XTEA.Decipher(16, MemoryMarshal.Cast <byte, uint>(chunk).ToArray(), DecryptionKey); Span <byte> resource = MemoryMarshal.AsBytes(decrypted); resource.CopyTo(chunk); } Document = Encoding.UTF8.GetString(updateList.ToArray()); }
public string Download(string filename, string key, int alg, Download form) { try { StoredFile sf = svc.Download(Username, filename, Token); byte[] f; switch (alg) { case 0: f = DoubleTransposition.Decrypt(sf.data, key, sf.hash); break; case 1: f = XTEA.Decrypt(sf.data, key, sf.hash); break; default: throw new Exception("You have not chosen an algorithm."); } form.Save(filename, f); return("File successfuly downloaded."); } catch (Exception e) { return(e.Message); } }
internal void DecryptPacket() { if (Length % 8 == 0 || Length == MaxBuffer) { Crypted = true; byte[] _key = new byte[16]; if (DestinationPort == _authPort || SourcePort == _authPort) { _key = _pong; } else if (DestinationPort == _gamePort) { if (IsGameAuthPacket(Data)) { DecryptedData = XTEA.Decrypt(Data, _pong); return; } if (XTEAKey1 == null) { UpdateKeys(); } _key = XTEAKey1; } else if (SourcePort == _gamePort) { if (XTEAKey2 == null) { UpdateKeys(); } _key = XTEAKey2; } else { return; } DecryptedData = XTEA.Decrypt(Data, _key); Id = DecryptedData[0]; } }
private void ProcessPacket(byte[] id) { if (_needToDecrypt) { id = XTEA.Decrypt(id, Config.Pong); } switch (id[0]) { case (byte)InPackets.HandshakePacket: ContinueHandshake(); break; case (byte)InPackets.LoginPacket: VerifyLogin(id); break; default: Drop("Unknown Packet"); break; } }
/// <summary> /// If the user's credentials are stored in PlayerPrefs, this method will retrieve them. /// </summary> /// <param name="username">Contains the username if retrieval was successfull, empty string otherwise.</param> /// <param name="token">Contains the token if retrieval was successfull, empty string otherwise.</param> /// <returns>Whether retrieval was successfull or not.</returns> public bool GetStoredUserCredentials(out string username, out string token) { username = token = ""; if (string.IsNullOrEmpty(UserCredentialsPreferences) || string.IsNullOrEmpty(Settings.EncryptionKey) || !PlayerPrefs.HasKey(UserCredentialsPreferences)) { return(false); } var credentials = PlayerPrefs.GetString(UserCredentialsPreferences).Split('#'); if (credentials.Length != 2) { return(false); } try { username = XTEA.Decrypt(credentials[0], Settings.EncryptionKey); token = XTEA.Decrypt(credentials[1], Settings.EncryptionKey); return(true); } catch { LogHelper.Warning("Failed to retrieve user credentials."); return(false); } }
private static void Initialize() { // Initializing objects used for encryption if (CypherDoubleTransposition == null) { CypherDoubleTransposition = new DoubleTransposition(); } if (CypherXTEA == null) { CypherXTEA = new XTEA(); } if (CypherKnapsack == null) { CypherKnapsack = new Knapsack(); } if (CypherMD5 == null) { CypherMD5 = new MD5(); } // Initializing algorithm dictionary if (EncryptionDictionary == null) { EncryptionDictionary = new Dictionary <int, Func <byte[], byte[]> >() { // Encryption methods { (int)Algorithm.DoubleTranposition, CypherDoubleTransposition.Crypt }, { (int)Algorithm.XTEA, CypherXTEA.Crypt }, { (int)Algorithm.Knapsack, CypherKnapsack.Crypt }, { (int)Algorithm.MD5, CypherMD5.Crypt }, // Decryption methods, enum value + number of algorithms { (int)Algorithm.DoubleTranposition + AlgoNumber, CypherDoubleTransposition.Decrypt }, { (int)Algorithm.XTEA + AlgoNumber, CypherXTEA.Decrypt }, { (int)Algorithm.Knapsack + AlgoNumber, CypherKnapsack.Decrypt }, { (int)Algorithm.MD5 + AlgoNumber, CypherKnapsack.Decrypt } } } ; // Initializing key and IV dictionary if (KeyIVDictionary == null) { KeyIVDictionary = new Dictionary <int, Func <byte[], bool> >() { // Set Key methods { (int)Algorithm.DoubleTranposition, CypherDoubleTransposition.SetKey }, { (int)Algorithm.XTEA, CypherXTEA.SetKey }, { (int)Algorithm.Knapsack, CypherKnapsack.SetKey }, { (int)Algorithm.MD5, CypherMD5.SetKey }, // Set IV methods, enum value + number of algorithms { (int)Algorithm.DoubleTranposition + AlgoNumber, CypherDoubleTransposition.SetIV }, { (int)Algorithm.XTEA + AlgoNumber, CypherXTEA.SetIV }, { (int)Algorithm.Knapsack + AlgoNumber, CypherKnapsack.SetIV }, { (int)Algorithm.MD5 + AlgoNumber, CypherMD5.SetIV } } } ; // Initializing property dictionary if (PropertyDictionary == null) { PropertyDictionary = new Dictionary <int, Func <IDictionary <string, byte[]>, bool> >() { // Set Property methods { (int)Algorithm.DoubleTranposition, CypherDoubleTransposition.SetAlgorithmProperties }, { (int)Algorithm.XTEA, CypherXTEA.SetAlgorithmProperties }, { (int)Algorithm.Knapsack, CypherKnapsack.SetAlgorithmProperties }, { (int)Algorithm.MD5, CypherMD5.SetAlgorithmProperties }, } } ; }
public void XTEADecryption(FileInfo file, FormModel model) { bool threadSuccesfull = false; var timeStarted = DateTime.Now; try { //OutputFileName string outputFileName = ""; //Log loggerController.Add(" ! File dec: " + file.Name + ", Alg: " + model.AlgorithmName); //Reading the extension var readedValues = File.ReadAllBytes(file.FullName); int lenght = 0; var extensionLength = (int)readedValues[0]; lenght++; char[] extension = new char[extensionLength]; int j = 0; for (var i = 1; i <= extensionLength; i++) { extension[j] = (char)readedValues[i]; j++; lenght++; } var finalExtesnion = "." + new string(extension); //OutputFileName outputFileName = FileNameCreator.CreateFileDecryptedName( model.Folders.OutputFolder, file.Name, finalExtesnion); using (FileStream fsw = new FileStream(outputFileName, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fsw, new ASCIIEncoding())) { //DEC byte[] newValue = new byte[readedValues.Length - lenght]; int k = 0; for (int i = lenght; i < readedValues.Length; i++) { newValue[k] = readedValues[i]; k++; } var decryptedValue = XTEA.Decrypt(newValue); bw.Write(decryptedValue); if (LoadedFilesController._END_OF_ENC_DEC_THREADS) { bw.Dispose(); fsw.Dispose(); File.Delete(outputFileName); Thread.CurrentThread.Abort(); } } } threadSuccesfull = true; Thread.Sleep(250); } catch (Exception ex) { loggerController.Add(" ? Dec exception: " + ex.Message); threadSuccesfull = false; } finally { this.ThreadEnds(file, threadSuccesfull, timeStarted); } }
private void Download(System.ComponentModel.DoWorkEventArgs e) { // Initializing service proxy var cloudProxy = new CloudServiceClient(); try { // Initializing client-side decryption var clientCypher = new XTEA(); // Getting decryption key clientCypher.SetKey(Encoding.ASCII.GetBytes(cloudProxy.GetKey())); // Initializing stream from service var length = cloudProxy.DownloadFile(ref _cloudFileName, out var inputStream); // Write stream to disk using (var writeStream = new FileStream(_localFilePath, FileMode.CreateNew, FileAccess.Write)) { // Initializing buffer var buffer = new byte[ChunkSize]; // Initializing boolean determining whether it's the last chunk var lastChunk = false; do { // Read bytes from input stream var bytesRead = inputStream.Read(buffer, 0, ChunkSize); if (bytesRead == 0) { break; } // Check if it is the last chunk if (bytesRead < ChunkSize) { var temp = new byte[bytesRead]; Array.Copy(buffer, temp, bytesRead); buffer = temp; lastChunk = true; } // Decrypt data from the buffer var decryptedBuffer = clientCypher.Decrypt(buffer); // Write bytes to output stream writeStream.Write(decryptedBuffer, 0, decryptedBuffer.Length); // Update progress bar if (lastChunk) { backgroundWorker.ReportProgress(100); } else { backgroundWorker.ReportProgress((int)(writeStream.Position * 100 / length)); } // Check for cancellation if (!backgroundWorker.CancellationPending) { continue; } e.Cancel = true; inputStream.Dispose(); return; } while (!lastChunk); writeStream.Close(); } // Deallocate stream inputStream.Dispose(); } catch (Exception exception) { throw new ArgumentException(exception.Message); } finally { // Close service proxy cloudProxy.Close(); } }
public void XTEABMPDecryption(FileInfo file, FormModel model) { bool threadSuccesfull = false; var timeStarted = DateTime.Now; try { if (!file.Extension.Contains("bmp")) { throw new Exception("File is not bmp!"); } //OutputFileName string outputFileName = ""; //Log loggerController.Add(" ! File dec: " + file.Name + ", Alg: " + model.AlgorithmName); //OutputFileName outputFileName = FileNameCreator.CreateFileDecryptedName( model.Folders.OutputFolder, file.Name, ".bmp"); using (FileStream fsw = new FileStream(outputFileName, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(fsw, new ASCIIEncoding())) { //Reading and encrypting files var readedValue = File.ReadAllBytes(file.FullName); long pos = readedValue[10] + 256 * (readedValue[11] + 256 * (readedValue[12] + 256 * readedValue[13])); byte[] header = new byte[pos]; for (int i = 0; i < header.Length; i++) { header[i] = readedValue[i]; } byte[] data = readedValue.Skip(header.Length).ToArray(); var decryptedValue = XTEA.Decrypt(data); decryptedValue = header.Concat(decryptedValue).ToArray(); bw.Write(decryptedValue); if (LoadedFilesController._END_OF_ENC_DEC_THREADS) { bw.Dispose(); fsw.Dispose(); File.Delete(outputFileName); Thread.CurrentThread.Abort(); } } } threadSuccesfull = true; Thread.Sleep(250); } catch (Exception ex) { loggerController.Add(" ? Dec exception: " + ex.Message); threadSuccesfull = false; } finally { this.ThreadEnds(file, threadSuccesfull, timeStarted); } }