public void PackData(byte[] data, int datalength, byte[] outdata, out int outlength) { var cmdlen = 0; int rand_len; var start_pos = 2; if (send_back_cmd.Count > 0) { cmdlen += 2; //TODO send_tcp_mss = recv_tcp_mss; rand_len = GetSendRandLen(datalength + cmdlen); outlength = rand_len + datalength + cmdlen + 2; start_pos += cmdlen; outdata[0] = (byte)(send_back_cmd[0] ^ last_client_hash[14]); outdata[1] = (byte)((send_back_cmd[0] >> 8) ^ last_client_hash[15]); outdata[2] = (byte)(datalength ^ last_client_hash[12]); outdata[3] = (byte)((datalength >> 8) ^ last_client_hash[13]); send_back_cmd.Clear(); } else { rand_len = GetSendRandLen(datalength); outlength = rand_len + datalength + 2; outdata[0] = (byte)(datalength ^ last_client_hash[14]); outdata[1] = (byte)((datalength >> 8) ^ last_client_hash[15]); } { var rnd_data = new byte[rand_len]; random.NextBytes(rnd_data); if (datalength > 0) { encryptor.Encrypt(data, datalength, data, out datalength); Array.Copy(data, 0, outdata, start_pos, datalength); if (rand_len > 0) { rnd_data.CopyTo(outdata, start_pos + datalength); } } else { rnd_data.CopyTo(outdata, start_pos); } } var key = new byte[user_key.Length + 4]; user_key.CopyTo(key, 0); BitConverter.GetBytes(pack_id).CopyTo(key, key.Length - 4); var md5 = CreateHMAC(key); ++pack_id; { var md5data = md5.ComputeHash(outdata, 0, outlength); last_client_hash = md5data; Array.Copy(md5data, 0, outdata, outlength, 2); outlength += 2; } }
/// <summary> /// Encrypts the committed file using the specified symmetric encryption key. /// </summary> /// <param name="key">The symmetric encryption key.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="key" /> is <c>null</c>.</exception> /// <exception cref="InvalidOperationException">Thrown if the file has not been committed to the cache.</exception> /// <exception cref="IOException">Thrown if there's a problem reading or writing file data.</exception> /// <exception cref="CryptographicException">Thrown if there's any encryption failure.</exception> /// <remarks> /// <note> /// This method may be called only on files that have been already been committed to the cache. /// </note> /// </remarks> public void Encrypt(SymmetricKey key) { if (key == null) { throw new ArgumentNullException("key"); } if (IsUploading) { throw new ArgumentNullException(string.Format("Cannot encrypt file [{0}] until it has been committed to the cache.", ID)); } if (!File.Exists(this.Path)) { throw new InvalidOperationException(string.Format("Cannot encrypt web transfer file with ID [{0}] because it does not exist.", ID)); } var encryptedTempPath = this.Path + ".encrypting"; using (var encryptor = new StreamEncryptor(key)) { encryptor.Encrypt(this.Path, encryptedTempPath); } File.Delete(this.Path); File.Move(encryptedTempPath, this.Path); }
public void StreamCryptography_FileEncrypt() { // Verify that we can encrypt one file to another and then decrypt it. var key = Crypto.GenerateSymmetricKey(CryptoAlgorithm.AES, 256); var inputPath = Path.GetTempFileName(); var encryptedPath = Path.GetTempFileName(); var decryptedPath = Path.GetTempFileName(); byte[] data; byte[] buffer; data = new byte[16 * 1024]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } try { using (var fs = new FileStream(inputPath, FileMode.Create, FileAccess.ReadWrite)) { fs.Write(data, 0, data.Length); } using (var encryptor = new StreamEncryptor(key)) { encryptor.Encrypt(inputPath, encryptedPath); } buffer = File.ReadAllBytes(encryptedPath); Assert.IsFalse(Helper.ArrayEquals(data, buffer)); using (var decryptor = new StreamDecryptor(key)) { decryptor.Decrypt(encryptedPath, decryptedPath); } buffer = File.ReadAllBytes(decryptedPath); Assert.IsTrue(Helper.ArrayEquals(data, buffer)); } finally { if (File.Exists(inputPath)) { File.Delete(inputPath); } if (File.Exists(encryptedPath)) { File.Delete(encryptedPath); } if (File.Exists(decryptedPath)) { File.Delete(decryptedPath); } } }
public override byte[] ClientUdpPreEncrypt(byte[] plaindata, int datalength, out int outlength) { byte[] outdata = new byte[datalength + 1024]; if (user_key == null) { user_id = new byte[4]; int index_of_split = Server.param.IndexOf(':'); if (index_of_split > 0) { try { uint user = uint.Parse(Server.param.Substring(0, index_of_split)); user_key = System.Text.Encoding.UTF8.GetBytes(Server.param.Substring(index_of_split + 1)); BitConverter.GetBytes(user).CopyTo(user_id, 0); } catch (Exception ex) { Logging.Log(LogLevel.Warn, $"Faild to parse auth param, fallback to basic mode. {ex}"); } } if (user_key == null) { random.NextBytes(user_id); user_key = Server.key; } } byte[] auth_data = new byte[3]; random.NextBytes(auth_data); MbedTLS.HMAC md5 = CreateHMAC(Server.key); byte[] md5data = md5.ComputeHash(auth_data, 0, auth_data.Length); int rand_len = UdpGetRandLen(random_client, md5data); byte[] rand_data = new byte[rand_len]; random.NextBytes(rand_data); outlength = datalength + rand_len + 8; encryptor = (StreamEncryptor)EncryptorFactory.GetEncryptor("chacha20", Convert.ToBase64String(user_key) + Convert.ToBase64String(md5data, 0, 16)); { byte[] iv = new byte[8]; Array.Copy(Server.key, iv, 8); encryptor.SetIV(iv); } encryptor.Encrypt(plaindata, datalength, outdata, out datalength); rand_data.CopyTo(outdata, datalength); auth_data.CopyTo(outdata, outlength - 8); byte[] uid = new byte[4]; for (int i = 0; i < 4; ++i) { uid[i] = (byte)(user_id[i] ^ md5data[i]); } uid.CopyTo(outdata, outlength - 5); { md5 = CreateHMAC(user_key); md5data = md5.ComputeHash(outdata, 0, outlength - 1); Array.Copy(md5data, 0, outdata, outlength - 1, 1); } return(outdata); }
public void StreamCryptography_PartialStream() { // Verify that we can encrypt/decrypt a portion of a stream. var key = Crypto.GenerateSymmetricKey(CryptoAlgorithm.AES, 256); var data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var input = new MemoryStream(); var encrypted = new MemoryStream(); var decrypted = new MemoryStream(); byte[] buffer; input.Write(data, 0, data.Length); // Verify encryption. using (var encryptor = new StreamEncryptor(key)) { encrypted.Write(new byte[] { 0 }, 0, 1); input.Position = 1; encryptor.Encrypt(input, encrypted, 8); encrypted.Write(new byte[] { 9 }, 0, 1); Assert.IsTrue(encrypted.Length > 2); encrypted.Position = 1; buffer = new byte[8]; encrypted.Read(buffer, 0, 8); Assert.IsFalse(Helper.ArrayEquals(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, buffer)); } // Verify decryption. using (var decryptor = new StreamDecryptor(key)) { buffer = new byte[] { 0 }; encrypted.Position = 0; encrypted.Read(buffer, 0, 1); decrypted.Write(buffer, 0, 1); decrypted.Position = 1; decryptor.Decrypt(encrypted, decrypted, (int)(encrypted.Length - 2)); buffer = new byte[] { 9 }; encrypted.Read(buffer, 0, 1); decrypted.Write(buffer, 0, 1); decrypted.Position = 0; buffer = new byte[(int)decrypted.Length]; decrypted.Read(buffer, 0, buffer.Length); Assert.IsTrue(Helper.ArrayEquals(data, buffer)); } }
public void SecurityLoadAndSend(string file_name, NetworkStream networkStream, byte[] key, DIFFIE_HELMAN aes) { using (stream = new FileStream(file_name, FileMode.Open)) { long length = stream.Length; int read = 0; file_length = BitConverter.GetBytes(stream.Length); aes.Encrypt(this.file_length); //Шифруем длину данных networkStream.Write(file_length, 0, file_length.Length); while (length > 0) { read = stream.Read(buf, 0, buf.Length); this.buf = StreamEncryptor.Encrypt(this.buf, key); //Дешифруем данные ключём потокового шифратора aes.Encrypt(this.buf); //Шифруем данные для передачи по сети networkStream.Write(this.buf, 0, read); length -= read; } } }
public void StreamCryptography_EntireStream() { // Verify that we can encrypt an entire stream and the decrypt it. var key = Crypto.GenerateSymmetricKey(CryptoAlgorithm.AES, 256); var data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var input = new MemoryStream(); var encrypted = new MemoryStream(); var decrypted = new MemoryStream(); byte[] buffer; input.Write(data, 0, data.Length); // Verify encryption. using (var encryptor = new StreamEncryptor(key)) { input.Position = 0; encryptor.Encrypt(input, encrypted); Assert.IsTrue(encrypted.Length > 0); encrypted.Position = 0; buffer = new byte[(int)encrypted.Length]; encrypted.Read(buffer, 0, buffer.Length); Assert.IsFalse(Helper.ArrayEquals(data, buffer)); } // Verify decryption. using (var decryptor = new StreamDecryptor(key)) { encrypted.Position = 0; decryptor.Decrypt(encrypted, decrypted); Assert.IsTrue(decrypted.Length > 0); decrypted.Position = 0; buffer = new byte[(int)decrypted.Length]; decrypted.Read(buffer, 0, buffer.Length); Assert.IsTrue(Helper.ArrayEquals(data, buffer)); } }
public void SecurityLoadAndSave(string file_name, NetworkStream networkStream, byte[] key, DIFFIE_HELMAN aes) { using (stream = new FileStream(file_name, FileMode.CreateNew)) { /*networkStream.Read(file_length, 0, file_length.Length); //Считываем длину данных в потоке long length = BitConverter.ToInt64(file_length, 0); //Переводим длину*/ byte[] file_data = null; FileProtocolReader.Read(ref file_data,networkStream); file_data = aes.Decript(file_data); this.buf = StreamEncryptor.Encrypt(file_data, key); //Шифруем потоковым шифратором stream.Write(buf, 0, buf.Length); //Записываем данные в файл /*int read = 0; while (networkStream.DataAvailable) { read = networkStream.Read(this.buf, 0, buf.Length); //Считываем данные из сетевого потока aes.Decript(this.buf); //Дешифруем данные из сети this.buf = StreamEncryptor.Encrypt(this.buf,key); //Шифруем потоковым шифратором stream.Write(buf, 0, read); //Записываем данные в файл length -= read; }*/ } }