/// <summary> /// Encryptes the given data and sends it as a packet to the receiver /// </summary> /// <param name="data">The raw bytes that shall be send</param> /// <exception cref="IOException">If anything went wrong with the I/O</exception> public void SendPacket(params byte[] data) { try { // Encryptes the data using the received key byte[] encrypted = SimpleSecurityUtils.EncryptAES(data, this.aesKey, this.aesIv); // Checks if anything failed with the encryption if (encrypted == null) { throw new Exception("Encryption failed"); } // Sends the length of the packet this.stream.WriteByte((byte)encrypted.Length); this.stream.WriteByte((byte)(encrypted.Length >> 8)); // Sends the actual encrypted data this.stream.Write(encrypted, 0, encrypted.Length); this.stream.Flush(); } catch (Exception e) { // Converts any exception to an i/o-exception throw new IOException(e.Message); } }
/// <summary> /// Saves the config file encrypted using the passed key /// </summary> /// <param name="filePath">The path to the file where to save the configuration</param> /// <param name="key">The key for encrypting the file</param> /// <exception cref="ConfigException">Something went wrong while encryption (Unknown)</exception> /// <exception cref="Exception">All exception that can be passed on by File.WriteAllBytes called with the filePath</exception> public void SaveConfig(string filePath, string key) { // Generates the object that will be saved as the config file JObject json = new JObject() { ["port"] = this.Port, ["host"] = this.Host, ["rsa"] = SimpleSecurityUtils.SaveRSAToJson(this.PrivateKey) }; // Generates the actual key and iv from the previous plain text key byte[] aesKey = SimpleSecurityUtils.HashSHA256(Encoding.UTF8.GetBytes(key)); byte[] aesIv = SimpleSecurityUtils.HashMD5(Encoding.UTF8.GetBytes(key)); // Encryptes the config-json object byte[] encData = SimpleSecurityUtils.EncryptAES(Encoding.UTF8.GetBytes(json.ToString()), aesKey, aesIv); // Checks if the encryption failed if (encData == null) { // Unknown exception throw new ConfigException(); } // Writes all data to the file File.WriteAllBytes(filePath, encData); }